### Hapi Nes Server Setup (JavaScript) Source: https://github.com/hapijs/nes/blob/master/API.md Demonstrates how to set up a Hapi server with the Nes plugin for WebSocket communication. It includes configuring HTTP Basic authentication and setting up a subscription with a filter to exclude messages from the sender. ```javascript const Hapi = require('@hapi/hapi'); const Basic = require('@hapi/basic'); const Bcrypt = require('bcrypt'); const Nes = require('@hapi/nes'); const server = new Hapi.Server(); const start = async () => { await server.register([Basic, Nes]); // Set up HTTP Basic authentication const users = { john: { username: 'john', password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret' name: 'John Doe', id: '2133d32a' } }; const validate = async (request, username, password) => { const user = users[username]; if (!user) { return { isValid: false }; } const isValid = await Bcrypt.compare(password, user.password); const credentials = { id: user.id, name: user.name }; return { isValid, credentials }; }; server.auth.strategy('simple', 'basic', 'required', { validate }); // Set up subscription server.subscription('/items', { filter: (path, message, options) => { return (message.updater !== options.credentials.username); } }); await server.start(); server.publish('/items', { id: 5, status: 'complete', updater: 'john' }); server.publish('/items', { id: 6, status: 'initial', updater: 'steve' }); }; start(); ``` -------------------------------- ### Subscriptions (Server) Source: https://github.com/hapijs/nes/blob/master/API.md Illustrates setting up a subscription path on the server and publishing messages to it, which clients can then subscribe to. ```javascript const Hapi = require('@hapi/hapi'); const Nes = require('@hapi/nes'); const server = new Hapi.Server(); const start = async () => { await server.register(Nes); server.subscription('/item/{id}'); await server.start(); server.publish('/item/5', { id: 5, status: 'complete' }); server.publish('/item/6', { id: 6, status: 'initial' }); }; start(); ``` -------------------------------- ### NES Client Constructor and Event Handlers Source: https://github.com/hapijs/nes/blob/master/API.md Details the `Client` constructor for establishing WebSocket connections and the event handlers for managing connection status and errors. ```APIDOC Client: The client implements the **nes** protocol and provides methods for interacting with the server. It supports auto-connect by default as well as authentication. Constructor: - new Client(url, [options]): Creates a new client object. - url: The WebSocket address to connect to (e.g. 'wss://localhost:8000'). - options: Optional configuration object where: - ws: Available only when the client is used in node.js and passed as-is to the [**ws** module](https://www.npmjs.com/package/ws). - timeout: Server response timeout in milliseconds. Defaults to `false` (no timeout). Event Handlers: - onError: A property used to set an error handler with the signature `function(err)`. Invoked whenever an error happens that cannot be associated with a pending request. - onConnect: A property used to set a handler for connection events (initial connection and subsequent reconnections) with the signature `function()`. - onDisconnect: A property used to set a handler for disconnection events with the signature `function(willReconnect, log)` where: - willReconnect: a boolean indicating if the client will automatically attempt to reconnect. - log: an object with the following optional keys: - code: the [RFC6455](https://tools.ietf.org/html/rfc6455#section-7.4.1) status code. - explanation: the [RFC6455](https://tools.ietf.org/html/rfc6455#section-7.4.1) explanation for the `code`. - reason: a human-readable text explaining the reason for closing. - wasClean: if `false`, the socket was closed abnormally. ``` -------------------------------- ### Nes Protocol Hello Handshake Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Defines the initial connection handshake process. Covers client-initiated 'hello' messages with authentication and subscription details, and server responses including heartbeat configuration and socket identifiers. ```APIDOC Client Hello Message: type: 'hello' id: number | string (unique per-client request id) version: '2' auth: object (optional, authentication credentials) subs: array of strings (optional, subscription paths) Example Client Hello: { type: 'hello', id: 1, version: '2', auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } }, subs: ['/a', '/b'] } Server Hello Response: type: 'hello' id: number | string (same id from client) heartbeat: false | object interval: number (heartbeat interval in ms) timeout: number (response timeout in ms) socket: string (server generated socket identifier) Example Server Hello Success: { type: 'hello', id: 1, heartbeat: { interval: 15000, timeout: 5000 }, socket: 'abc-123' } Server Hello Response (Subscription Error): type: 'hello' id: number | string (same id from client) path: string (failed subscription path) statusCode: number (e.g., 403) payload: object (error details) Example Server Hello Subscription Error: { type: 'hello', id: 1, path: '/a', statusCode: 403, payload: { error: 'Subscription not found' } } ``` -------------------------------- ### Subscriptions (Client) Source: https://github.com/hapijs/nes/blob/master/API.md Demonstrates how a nes client can connect and subscribe to a specific path, receiving updates published by the server. ```javascript const Nes = require('@hapi/nes'); const client = new Nes.Client('ws://localhost'); const start = async () => { await client.connect(); const handler = (update, flags) => { // update -> { id: 5, status: 'complete' } // Second publish is not received (doesn't match) }; client.subscribe('/item/5', handler); }; start(); ``` -------------------------------- ### Nes Plugin Registration Options Source: https://github.com/hapijs/nes/blob/master/API.md Describes the options accepted during the hapi server.register() process for the nes plugin. These options control event callbacks and authentication settings. ```APIDOC server.register(nes, options, callback) Options: - onConnection: function(socket) - Description: Invoked for each incoming client connection. - Parameters: - socket: The Socket object of the incoming connection. - onDisconnection: function(socket) - Description: Invoked for each client connection on disconnect. - Parameters: - socket: The Socket object of the connection. - onMessage: async function(socket, message) - Description: Used to receive custom client messages (when client.message() is called). - Parameters: - socket: The Socket object of the message source. - message: The message sent by the client. - Returns: May return a response to the client. - auth: object | false - Description: Optional plugin authentication options. - Supported Values: - false: No client authentication supported. - object: - type: string - Description: The type of authentication flow supported. - Supported Types: - 'direct' (default): Plugin configures an internal auth endpoint. Credentials passed via client.connect() or directly. - 'cookie': Plugin configures a public auth endpoint. Client calls endpoint manually, sets a cookie. - 'token': Plugin configures a public auth endpoint. Client calls endpoint manually, receives token for client.connect(). - endpoint: string - Description: The HTTP path of the authentication endpoint. Defaults to '/nes/auth'. - id: string - Description: The authentication endpoint identifier. Defaults to 'nes.auth'. - route: object - Description: The hapi route config.auth settings for the authentication endpoint. - Example: { strategy: 'session' } - password: string - Description: Password for iron module to encrypt cookie/token values. Auto-generated if not provided, but recommended to set manually for consistency. ``` -------------------------------- ### Hapi Nes Client Connection (JavaScript) Source: https://github.com/hapijs/nes/blob/master/API.md Shows how to connect a Nes client to a WebSocket server, authenticate using Basic authentication, and subscribe to updates on a specific channel. It also includes a handler for received updates. ```javascript const Nes = require('@hapi/nes'); const client = new Nes.Client('ws://localhost'); // Authenticate as 'john' const start = async () => { await client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }); const handler = (update, flags) => { // First publish is not received (filtered due to updater key) // update -> { id: 6, status: 'initial', updater: 'steve' } }; client.subscribe('/items', handler); }; start(); ``` -------------------------------- ### Route Invocation (Server) Source: https://github.com/hapijs/nes/blob/master/API.md Demonstrates how to register the nes plugin with a Hapi server and define a route that can be invoked by a WebSocket client. ```javascript const Hapi = require('@hapi/hapi'); const Nes = require('@hapi/nes'); const server = new Hapi.Server(); const start = async () => { await server.register(Nes); server.route({ method: 'GET', path: '/h', config: { id: 'hello', handler: (request, h) => { return 'world!'; } } }); await server.start(); }; start(); ``` -------------------------------- ### Route Invocation (Client) Source: https://github.com/hapijs/nes/blob/master/API.md Shows how to connect a nes client to a Hapi WebSocket server and make a request to an invoked route. ```javascript const Nes = require('@hapi/nes'); var client = new Nes.Client('ws://localhost'); const start = async () => { await client.connect(); const payload = await client.request('hello'); // Can also request '/h' // payload -> 'world!' }; start(); ``` -------------------------------- ### Broadcast (Server) Source: https://github.com/hapijs/nes/blob/master/API.md Shows how to broadcast a message to all connected WebSocket clients using the nes library on the server. ```javascript const Hapi = require('@hapi/hapi'); const Nes = require('@hapi/nes'); const server = new Hapi.Server(); const start = async () => { await server.register(Nes); await server.start(); server.broadcast('welcome!'); }; start(); ``` -------------------------------- ### Route Authentication (Server) Source: https://github.com/hapijs/nes/blob/master/API.md Configures HTTP Basic authentication for a Hapi server and registers the nes plugin, allowing authenticated WebSocket connections. ```javascript const Hapi = require('@hapi/hapi'); const Basic = require('@hapi/basic'); const Bcrypt = require('bcrypt'); const Nes = require('@hapi/nes'); const server = new Hapi.Server(); const start = async () => { await server.register([Basic, Nes]); // Set up HTTP Basic authentication const users = { john: { username: 'john', password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret' name: 'John Doe', id: '2133d32a' } }; const validate = async (request, username, password) => { const user = users[username]; if (!user) { return { isValid: false }; } const isValid = await Bcrypt.compare(password, user.password); const credentials = { id: user.id, name: user.name }; return { isValid, credentials }; }; server.auth.strategy('simple', 'basic', { validate }); // Configure route with authentication server.route({ method: 'GET', path: '/h', config: { id: 'hello', handler: (request, h) => { return `Hello ${request.auth.credentials.name}`; } } }); await server.start(); }; start(); ``` -------------------------------- ### Messaging and Subscriptions Source: https://github.com/hapijs/nes/blob/master/API.md Enables sending custom messages to the server and managing real-time subscriptions to server updates. ```APIDOC await client.message(message) Sends a custom message to the server's onMessage handler. Parameters: - message (any): The message to send. Can be any type safely convertible to string via JSON.stringify(). await client.subscribe(path, handler) Subscribes to a server subscription. Parameters: - path (string): The subscription path (e.g., '/item/5' or '/updates'). - handler (function): Function to receive subscription updates with signature function(message, flags). - message (any): The subscription update sent by the server. - flags (object, optional): Object with optional flags. - revoked (boolean): Set to true if this is the last update due to subscription revocation. Notes: If called before connect(), server errors are thrown by connect(). await client.unsubscribe(path, handler) Cancels a subscription. Parameters: - path (string): The subscription path. - handler (function | null): The specific handler to remove, or null to remove all handlers for the path. client.subscriptions() Returns an array of current subscription paths. ``` -------------------------------- ### hapi nes server.subscription API Source: https://github.com/hapijs/nes/blob/master/API.md Declares a subscription path for clients to subscribe to. It defines the path, and optional configuration for filtering messages, authentication, and lifecycle events like subscribing and unsubscribing. ```APIDOC server.subscription(path, [options]) - Declares a subscription path for clients to subscribe to. - Parameters: - path: string - An HTTP-like path. Must begin with '/'. May contain path parameters supported by hapi route path parser. - options: object (optional) - filter: function(path, message, options) - A publishing filter function for per-client message decisions. - path: string - The path of the published update. - message: any - The message being published. - options: object - Additional subscription/client info. - socket: object - The current socket. - credentials: object - Client credentials if authenticated. - params: object - Parsed parameters from the publish message path. - internal: any - Internal options data passed to publish. - Returns: boolean or { override: any } - true to send, false to skip, or an override message. - auth: boolean or object - Subscription authentication options. - false: No authentication required. - object: Configuration object. - mode: 'required' | 'optional' - Authentication mode (defaults to 'required'). - scope: string | string[] - Authentication scope. - entity: 'user' | 'app' | 'any' - Required credentials type. - index: boolean - If true, maps authenticated sockets with 'user' property in credentials for server.publish(). Defaults to false. - onSubscribe: function(socket, path, params) - Called when a client subscribes. - socket: object - The incoming connection Socket object. - path: string - The path the client subscribed to. - params: object - Parsed parameters from the subscription request path. - onUnsubscribe: function(socket, path, params) - Called when a client unsubscribes. - socket: object - The incoming connection Socket object. - path: string - Path of the unsubscribed route. - params: object - Parsed parameters from the subscription request path. ``` -------------------------------- ### Route Authentication (Client) Source: https://github.com/hapijs/nes/blob/master/API.md Connects a nes client to a Hapi server using HTTP Basic authentication credentials and invokes an authenticated route. ```javascript const Nes = require('@hapi/nes'); const client = new Nes.Client('ws://localhost'); const start = async () => { await client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }); const payload = await client.request('hello') // Can also request '/h' // payload -> 'Hello John Doe' }; start(); ``` -------------------------------- ### Subscription Protocol Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Enables clients to subscribe to specific paths on the server. The server responds with subscription status or error details. ```APIDOC Client Subscription Request: type: 'sub' id: unique per-client request id (number or string) path: the requested subscription path Example: { type: 'sub', id: 4, path: '/box/blue' } Server Subscription Response: type: 'sub' id: the same id received from the client path: the requested path which failed to subscribe statusCode: (optional) HTTP equivalent status code if failed payload: (optional) error details if failed Example (Failure): { type: 'sub', id: 4, path: '/box/blue', statusCode: 403, payload: { error: 'Forbidden' } } ``` -------------------------------- ### Resource Request Protocol Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Enables clients to request resources from the server. The client specifies the HTTP method, path, headers, and payload. The server responds with the requested resource or error information. ```APIDOC Client Resource Request: type: 'request' id: unique per-client request id (number or string) method: corresponding HTTP method (e.g. 'GET') path: requested resource (HTTP path or resource name) headers: (optional) object with request headers payload: (optional) value to send with the request Example: { type: 'request', id: 2, method: 'POST', path: '/item/5', payload: { id: 5, status: 'done' } } Server Resource Response: type: 'request' id: the same id received from the client statusCode: HTTP equivalent status code payload: the requested resource headers: (optional) headers related to the request (e.g. {'content-type': 'text/html; charset=utf-8'}) Example (Success): { type: 'request', id: 2, statusCode: 200, payload: { status: 'ok' } } Example (Failure): Fields statusCode, headers, and payload will comply with standard error values. ``` -------------------------------- ### Broadcast (Client) Source: https://github.com/hapijs/nes/blob/master/API.md Illustrates how a nes client can receive broadcast messages by setting the onUpdate handler. ```javascript const Nes = require('@hapi/nes'); const client = new Nes.Client('ws://localhost'); const start = async () => { await client.connect(); client.onUpdate = (update) => { // update -> 'welcome!' }; }; start(); ``` -------------------------------- ### Connection Management Source: https://github.com/hapijs/nes/blob/master/API.md Handles connecting to and disconnecting from the nes server, including reconnection logic. ```APIDOC await client.connect([options]) Connects the client to the server. Parameters: - options (object, optional): Configuration object. - auth (any): Credentials for authentication. For 'token' type, it's the token response. For 'direct' type, it's an object with headers (e.g., { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } }). - reconnect (boolean): Whether to attempt reconnection. Defaults to true. - delay (number): Time in milliseconds to wait between reconnections. Delay is cumulative (1s, 2s, 3s, up to maxDelay). - maxDelay (number): Maximum delay time in milliseconds between reconnections. - retries (number): Number of reconnection attempts. Defaults to Infinity. - timeout (number): Socket connection timeout in milliseconds. Defaults to WebSocket implementation default. await client.disconnect() Disconnects the client from the server and stops future reconnects. ``` -------------------------------- ### Requests and Client Properties Source: https://github.com/hapijs/nes/blob/master/API.md Details how to make requests to server endpoints and access client-specific information like the socket ID. ```APIDOC await client.request(options) Sends an endpoint request to the server. Parameters: - options (string | object): Request details. - If string: The requested endpoint path or route id (defaults to GET method). - If object: - path (string): The requested endpoint path or route id. - method (string, optional): The requested HTTP method. Defaults to 'GET'. - headers (object, optional): Request headers. Cannot include Authorization header. Defaults to no headers. - payload (any): The request payload sent to the server. Returns: - object: Contains: - payload (any): The server response payload. - statusCode (number): The HTTP response status code. - headers (object): The HTTP response headers. Rejects: - Error: If the request failed. client.id The unique socket identifier assigned by the server. Set after connection establishment. ``` -------------------------------- ### NES Socket Object Methods and Properties Source: https://github.com/hapijs/nes/blob/master/API.md Details the properties and methods available on a `Socket` object representing a client connection, including identifiers, authentication state, and communication methods. ```APIDOC Socket Object: An object representing a client connection. Properties: - id: A unique socket identifier. - app: An object used to store application state per socket. Provides a safe namespace to avoid conflicts with the socket methods. - auth: The socket authentication state if any. Similar to the normal **hapi** `request.auth` object where: - isAuthenticated: a boolean set to `true` when authenticated. - credentials: the authentication credentials used. - artifacts: authentication artifacts specific to the authentication strategy used. - server: The socket's server reference. - connection: The socket's connection reference. Methods: - disconnect(): Closes a client connection. - isOpen(): Returns `true` is the socket connection is in ready state, otherwise `false`. - send(message): Sends a custom message to the client. `message` can be any type which can be safely converted to string using `JSON.stringify()`. - publish(path, message): Sends a subscription update to a specific client. `path` is the subscription string. If the client did not subscribe to the provided `path`, the client will ignore the update silently. `message` can be any type which can be safely converted to string using `JSON.stringify()`. - revoke(path, message, [options]): Revokes a subscription and optionally includes a last update. `path` is the subscription string. If the client is not subscribed to the provided `path`, the client will ignore it silently. `message` is an optional last subscription update sent to the client. Pass `null` to revoke the subscription without sending a last update. `options` is an optional settings object with `ignoreClosed` (boolean, defaults to `false`) to ignore errors if the underlying websocket has been closed. ``` -------------------------------- ### hapi nes server.publish API Source: https://github.com/hapijs/nes/blob/master/API.md Sends a message to all subscribed clients matching the provided path. It allows filtering messages based on subscription configurations and optionally targeting specific users. ```APIDOC await server.publish(path, message, [options]) - Sends a message to all subscribed clients. - Parameters: - path: string - The subscription path to match against available subscriptions. - message: any - The message to send, convertible to string via JSON.stringify(). - options: object (optional) - internal: any - Internal data passed to the filter function. - user: string - Optional user filter; sends message only to authenticated sockets where credentials.user matches. Requires subscription auth.index to be true. ``` -------------------------------- ### Server Broadcast Method Source: https://github.com/hapijs/nes/blob/master/API.md Sends a message to all connected WebSocket clients. Supports filtering messages by authenticated user credentials. ```APIDOC Server Methods: await server.broadcast(message, [options]) - Sends a message to all connected clients. - Parameters: - message: The message to send. Can be any type safely convertible to a string via JSON.stringify(). - options: Optional object with filtering capabilities. - user: Optional user filter. If provided, the message is sent only to authenticated sockets where credentials.user matches the provided value. Requires the `auth.index` option to be configured to `true`. - Note: In a multi-server deployment, messages are only received by clients connected to the current server. ``` -------------------------------- ### NES Server Socket Iteration Source: https://github.com/hapijs/nes/blob/master/API.md Iterates over all connected sockets on the server, with optional filtering by subscription path or user credentials. This operation is synchronous. ```APIDOC server.eachSocket(each, [options]) Iterates over all connected sockets, optionally filtering on those that have subscribed to a given subscription. This operation is synchronous. Parameters: - each: Iteration method in the form `async function(socket)`. - options: Optional options object - subscription: When set to a string path, limits the results to sockets that are subscribed to that path. - user: Optional user filter. When provided, the `each` method will be invoked with authenticated sockets with `credentials.user` equal to `user`. Requires the subscription `auth.index` options to be configured to `true`. ``` -------------------------------- ### Nes Protocol Heartbeat Mechanism Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Details the heartbeat flow for maintaining active connections. Covers server-initiated pings and client responses to ensure connection liveness. ```APIDOC Heartbeat Flow: Server -> Client -> Server Server sends heartbeat request: type: 'ping' Client responds to heartbeat: type: 'ping' id: number | string (unique per-client request id) Example Server Ping: { type: 'ping' } Example Client Ping Response: { type: 'ping', id: 6 } ``` -------------------------------- ### Reauthentication Protocol Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Handles client reauthentication when credentials expire. The client sends a 'reauth' message with its credentials. The server responds with a success message or error details. ```APIDOC Client Reauthentication Request: type: 'reauth' id: unique per-client request id (number or string) auth: authentication credentials (e.g., headers) Example: { type: 'reauth', id: 1, auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } } Server Reauthentication Response: type: 'reauth' id: the same id received from the client statusCode: (optional) HTTP status code if failed payload: (optional) error details if failed Example (Success): { type: 'reauth', id: 1 } Example (Failure): { type: 'reauth', id: 1, statusCode: 401, payload: { error: 'Unauthorized', message: 'Unknown username or incorrect password' } } ``` -------------------------------- ### Nes Client Reconnection and Reauthentication Source: https://github.com/hapijs/nes/blob/master/API.md Manages client reconnection authentication and server reauthentication. Includes methods to override reconnection credentials and to send updated authentication details to the server. ```APIDOC client.overrideReconnectionAuth(auth) Sets or overrides the authentication credentials used to reconnect the client on disconnect when the client is configured to automatically reconnect. Parameters: - auth: The authentication credentials, same as the `auth` option passed to `client.connect()`. Returns: - boolean: `true` if reconnection is enabled, otherwise `false` (method was ignored). Notes: - This method does not update credentials on the server. Use `client.reauthenticate()` for that purpose. client.reauthenticate(auth) Issues the `reauth` message to the server with updated `auth` details and also overrides the reconnection information if reconnection is enabled. Parameters: - auth: Updated authentication details. Returns: - Promise: Resolves with `true` if the request succeeds. Rejects: - Error: If the request failed. Notes: - The server will respond with an error and drop the connection if the new `auth` credentials are invalid. - When authentication has a limited lifetime, `reauthenticate()` should be called early enough to avoid the server dropping the connection. Related: - `client.overrideReconnectionAuth(auth)` ``` -------------------------------- ### Custom Message Protocol Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Allows clients to send arbitrary custom messages to the server. The server can echo these messages back or respond with errors. ```APIDOC Client Custom Message: type: 'message' id: unique per-client request id (number or string) message: any value (string, object, etc.) Example: { type: 'message', id: 3, message: 'hi' } Server Custom Message Response: type: 'message' id: the same id received from the client message: any value (string, object, etc.) Example: { type: 'message', id: 3, message: 'hello back' } Failure responses will include standard error fields. ``` -------------------------------- ### Event Handlers Source: https://github.com/hapijs/nes/blob/master/API.md Allows setting custom handlers for specific client events like heartbeat timeouts and message updates. ```APIDOC client.onHeartbeatTimeout = function(willReconnect) Sets a handler for heartbeat timeout events. Parameters: - willReconnect (boolean): Indicates if the client will automatically attempt to reconnect. Notes: The client disconnects the websocket on timeout. onDisconnect() is called after the server handshake. This handler notifies immediately for user actions. client.onUpdate = function(message) Sets a custom message handler. Invoked whenever the server calls server.broadcast() or socket.send(). Parameters: - message (any): The message received from the server. ``` -------------------------------- ### Nes Protocol Message Structure Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Defines the general structure for messages exchanged between client and server in the nes protocol. Includes details on message types, unique identifiers, and optional fields specific to message types. ```APIDOC Client Incoming Message: type: string (e.g., 'ping', 'hello', 'request', 'sub', 'unsub', 'message') id: number | string (unique per-client request id) additional type-specific fields. Server Outgoing Message: type: string (e.g., 'ping', 'hello', 'request', 'sub', 'unsub', 'message', 'update', 'pub', 'revoke') id: number | string (unique per-client request id) additional type-specific fields. Chunking: Messages exceeding WebSocket frame limits are chunked. - First chunks: prefixed with '+' - Last chunk: prefixed with '!' - JSON string is sliced into chunks. ``` -------------------------------- ### Nes Protocol Error Handling Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Specifies the structure for error messages returned by the server. Includes standard HTTP status codes, optional headers, and detailed error payloads. ```APIDOC Error Message Structure: type: string (message-specific type) id: number | string (request id) statusCode: number (HTTP equivalent, e.g., 4xx, 5xx) headers: object (optional, related to the request) payload: object error: string (HTTP equivalent error message) message: string (description of the error) additional error-specific fields. Example: { type: 'hello', id: 1, statusCode: 401, payload: { error: 'Unauthorized', message: 'Unknown username or incorrect password' } } ``` -------------------------------- ### Server Publish Message Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md A message sent from the server to all clients subscribed to a specific path, used for broadcasting events or data. ```APIDOC Server Publish Message: type: 'pub' path: the subscription path message: any value (string, object, etc.) Example: { type: 'pub', path: '/box/blue', message: { status: 'closed' } } ``` -------------------------------- ### Unsubscribe Protocol Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Allows clients to unsubscribe from server subscriptions. The server acknowledges the unsubscribe request or reports errors. ```APIDOC Client Unsubscribe Request: type: 'unsub' id: unique per-client request id (number or string) path: the subscription path Example: { type: 'unsub', id: 5, path: '/box/blue' } Server Unsubscribe Response: type: 'unsub' id: the same id received from the client (optional) standard error fields if failed Example: { type: 'unsub', id: 5 } ``` -------------------------------- ### Nes Client Error Types Source: https://github.com/hapijs/nes/blob/master/API.md Details the types of errors that can be decorated on client method errors, indicating the source or nature of the failure. ```APIDOC Error Decorators: When a client method returns or throws an error, the error is decorated with a `type` property. Possible `type` values: - 'disconnect': The socket disconnected before the request completed. - 'protocol': The client received an invalid message from the server violating the protocol. - 'server': An error response sent from the server. - 'timeout': A timeout event occurred. - 'user': User error (e.g., incorrect use of the API). - 'ws': A socket error. ``` -------------------------------- ### NES Request Socket Access Source: https://github.com/hapijs/nes/blob/master/API.md Provides access to the `Socket` object associated with an incoming request on the server. ```APIDOC Request Object: The following decorations are available on each request received via the nes connection. Properties: - socket: Provides access to the [`Socket`](#socket) object of the incoming connection. ``` -------------------------------- ### Server Update Message Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md A custom message sent from the server to a specific client or all connected clients, typically for broadcasting updates. ```APIDOC Server Update Message: type: 'update' message: any value (string, object, etc.) Example: { type: 'update', message: { some: 'message' } } ``` -------------------------------- ### Revoke Message Structure Source: https://github.com/hapijs/nes/blob/master/PROTOCOL.md Defines the structure of the message sent by the server to forcefully remove a client from a subscription. It includes the event type, the subscription path, and an optional message payload. ```javascript { type: 'revoke', path: '/box/blue', message: { reason: 'channel permissions changed' } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.