@eliware/mail-client 15.0.2 → 17.0.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/AGENTS.md CHANGED
@@ -41,8 +41,6 @@ Run focused tests first during development.
41
41
  Run one test file with `npm test -- tests/path/to/example.test.mjs`.
42
42
  Run multiple test files with `npm test -- tests/path/to/first.test.mjs tests/path/to/second.test.mjs`.
43
43
  Prevent repeated full-suite runs during development.
44
- Run the full `npm test` suite for final validation before a commit, milestone, or release.
45
-
46
- ## npm publication
44
+ Run the full `npm test` suite for final validation before a commit.
47
45
 
48
46
  Run `npm run pack` to check package contents. Follow approved release steps before publication.
package/README.md CHANGED
@@ -27,23 +27,23 @@ Call the mail-server API from Node.js and browser applications. Receive WebSocke
27
27
 
28
28
  ## Requirements
29
29
 
30
- Use Node.js 26 or later. Browser applications require Fetch, Headers, AbortSignal, and URL APIs.
30
+ Use Node.js 26 or later. Browser applications require Fetch, Headers, AbortSignal, URL, and WebSocket APIs.
31
31
 
32
32
  ## Setup
33
33
 
34
- Install the package with `npm install @eliware/mail-client`. Read the [usage guide](docs/usage.md) to configure the API URL and bearer-token provider.
34
+ Install the package with `npm install @eliware/mail-client`. Follow the [usage guide](docs/usage.md) to configure the API address and bearer-token provider.
35
35
 
36
36
  ## Usage
37
37
 
38
- Read the [usage guide](docs/usage.md), [API reference](docs/api.md), and [release notes](RELEASE_NOTES.md). Find runnable examples in [examples/README.md](examples/README.md).
38
+ Follow the [usage guide](docs/usage.md). Find client methods in the [API reference](docs/api.md) and version changes in the [release notes](RELEASE_NOTES.md).
39
39
 
40
40
  ## Development
41
41
 
42
- Read [AGENTS.md](AGENTS.md), [documentation](docs/README.md), and [specifications](specs/README.md) before changing files. Run `npm ci` to install locked dependencies.
42
+ Read [AGENTS.md](AGENTS.md) and [specifications](specs/README.md) before changing files. Find maintained guides in [documentation](docs/README.md).
43
43
 
44
44
  ## Testing
45
45
 
46
- Run `npm test` for aggregate checks. Run `npm run smoke` for an HTTP and WebSocket check.
46
+ Run `npm test` for aggregate validation. Run `npm run smoke` to check an HTTP and WebSocket connection.
47
47
 
48
48
  ## Troubleshooting
49
49
 
@@ -56,11 +56,10 @@ Keep long-lived API tokens in server-side secret stores. Do not expose them to b
56
56
  ## API
57
57
 
58
58
  Read the [API reference](docs/api.md) for client options, methods, events, logging, and errors.
59
- The Node.js entry uses `@eliware/log`. Browser logging stays silent by default.
60
59
 
61
60
  ## Packaging
62
61
 
63
- Follow approved release steps before you publish a version. Read [release notes](RELEASE_NOTES.md) for package changes.
62
+ Read [package details](docs/package.md) for runtime support, package contents, and version rules. Read [release notes](RELEASE_NOTES.md) for package changes.
64
63
 
65
64
  ## Examples
66
65
 
package/RELEASE_NOTES.md CHANGED
@@ -1,5 +1,43 @@
1
1
  # Release Notes
2
2
 
3
+ ## 17.0.0 — 2026-12-06
4
+
5
+ ### Added
6
+
7
+ - Expose event connection states through `connection.state` and the `onState` callback.
8
+ - Pass an `AbortSignal` to token providers. Abort it when a connection closes, a request times out, or the caller cancels a request.
9
+
10
+ ### Changed
11
+
12
+ - Change package root exports from named exports to a default-exported object. Import the default object. Read `createMailClient` and `MailApiError` from it.
13
+ - Use `@eliware/common/log` and remove the direct `@eliware/log` dependency.
14
+ - Require server authentication and event messages to use JSON text WebSocket frames. Reject binary frames.
15
+
16
+ ### Fixed
17
+
18
+ - Prevent duplicate reconnect timers from opening multiple event connections.
19
+ - Validate message IDs before validating Discord link data.
20
+ - Apply HTTP timeouts and caller cancellation while the token provider runs.
21
+
22
+ ## 15.0.3 — 2026-10-30
23
+
24
+ ### Added
25
+
26
+ - Add a package guide for runtime support, entrypoints, environment values, package contents, and publication.
27
+
28
+ ### Changed
29
+
30
+ - Set the package version to 15.0.3.
31
+ - Send `consumer_id` in durable WebSocket requests and use the server-stored consumer cursor.
32
+ - Reject `after` when a WebSocket connection uses `consumerId`.
33
+ - Keep `ready` pending while automatic reconnect retries token-provider or socket failures.
34
+ - Update locked transitive dependencies and simplify README navigation.
35
+
36
+ ### Fixed
37
+
38
+ - Stop queued event handlers after an earlier event handler fails.
39
+ - Reject browser WebSocket frames that contain binary `Blob` data.
40
+
3
41
  ## 15.0.2 — 2026-10-30
4
42
 
5
43
  ### Added
package/docs/README.md CHANGED
@@ -6,4 +6,5 @@ This directory contains user and API documentation for `@eliware/mail-client`.
6
6
 
7
7
  - [Usage](usage.md)
8
8
  - [API reference](api.md)
9
+ - [Package details](package.md)
9
10
  - [Troubleshooting](troubleshooting.md)
package/docs/api.md CHANGED
@@ -1,25 +1,25 @@
1
1
  # API reference
2
2
 
3
- The package root exports `createMailClient` and `MailApiError`. The TypeScript declarations live in the package and describe these exports.
3
+ The package root provides `createMailClient` and `MailApiError` through its default export. The TypeScript declarations describe these properties.
4
4
 
5
5
  ## Create a client
6
6
 
7
7
  Call `createMailClient(options)` to create an HTTP and WebSocket client.
8
8
 
9
- | Option | Required | Default | Description |
10
- | ---------------- | -------- | ---------------------------------------- | ---------------------------------------------- |
11
- | `baseUrl` | Yes | None | HTTP or HTTPS base address for mail-server. |
12
- | `getAccessToken` | Yes | None | Returns a bearer token as a string or promise. |
13
- | `fetchImpl` | No | `globalThis.fetch` | Supplies the Fetch function for HTTP requests. |
14
- | `WebSocketImpl` | No | `globalThis.WebSocket` | Supplies the WebSocket constructor. |
15
- | `timeoutMs` | No | `15000` | Sets the timeout for each HTTP request. |
16
- | `logger` | No | Node.js: `@eliware/log`, browser: silent | Supplies `debug`, `warn`, and `error` methods. |
9
+ | Option | Required | Default | Description |
10
+ | ---------------- | -------- | ----------------------------------------------- | ---------------------------------------------- |
11
+ | `baseUrl` | Yes | None | HTTP or HTTPS base address for mail-server. |
12
+ | `getAccessToken` | Yes | None | Returns a bearer token as a string or promise. |
13
+ | `fetchImpl` | No | `globalThis.fetch` | Supplies the Fetch function for HTTP requests. |
14
+ | `WebSocketImpl` | No | `globalThis.WebSocket` | Supplies the WebSocket constructor. |
15
+ | `timeoutMs` | No | `15000` | Sets the timeout for each HTTP request. |
16
+ | `logger` | No | Node.js: `@eliware/common/log`, browser: silent | Supplies `debug`, `warn`, and `error` methods. |
17
17
 
18
18
  Use an HTTP or HTTPS base address without a path, query, fragment, user name, or password. The client resolves request paths on that address. A leading `//` becomes one root slash. Absolute URLs must use the configured address.
19
19
 
20
- The token provider runs before each HTTP request and each new WebSocket connection. It must return a non-empty string. The client does not inspect token claims or refresh tokens by itself.
20
+ The token provider runs before each HTTP request and each new WebSocket connection. It must return a non-empty string. For WebSocket connections, the client passes an `AbortSignal` to the provider and aborts it when the connection closes. The client does not inspect token claims or refresh tokens by itself.
21
21
 
22
- The client combines the request timeout with a caller-provided `AbortSignal`. When one signal aborts, Fetch receives the combined signal. The client does not retry failed requests.
22
+ The client combines the request timeout with a caller-provided `AbortSignal`. It passes the combined signal to the token provider and Fetch. This stops token retrieval when the request times out or the caller aborts. The client does not retry failed requests.
23
23
 
24
24
  ## HTTP request methods
25
25
 
@@ -141,7 +141,7 @@ The error message uses the API error message when available. Network errors and
141
141
 
142
142
  ### `connectEvents(options)`
143
143
 
144
- Open the `/ws` route and receive event notifications. The WebSocket URL uses `ws` for an HTTP base address and `wss` for an HTTPS base address. The client puts the optional `after` cursor in the URL and excludes tokens.
144
+ Open the `/ws` route and receive event notifications. The WebSocket URL uses `ws` for an HTTP base address and `wss` for an HTTPS base address. The client puts the optional `after` cursor or `consumer_id` in the URL and excludes tokens.
145
145
 
146
146
  After the socket opens, the client sends this JSON frame as its first message:
147
147
 
@@ -155,23 +155,30 @@ The client waits for this server frame before it delivers events:
155
155
  { "type": "authenticated" }
156
156
  ```
157
157
 
158
- | Option | Default | Description |
159
- | --------------------- | ------------- | --------------------------------------------------------------------------- |
160
- | `onEvent(event)` | Required | Processes one JSON event. A returned promise delays cursor acknowledgement. |
161
- | `onError(error)` | No operation | Receives socket, handler, and acknowledgement errors. |
162
- | `logger` | Client logger | Overrides the logger for this event connection. |
163
- | `after` | Live edge | Starts event replay after a decimal cursor. |
164
- | `consumerId` | None | Enables server-side cursor acknowledgements. |
165
- | `autoReconnect` | `true` | Reconnects after unexpected closure. |
166
- | `retryDelayMs` | `500` | Sets the first reconnect wait interval. |
167
- | `maxReconnectDelayMs` | `30000` | Sets the longest reconnect wait interval. |
168
- | `WebSocketImpl` | Client option | Overrides the WebSocket constructor for this connection. |
158
+ The server must send authentication and event messages as JSON text frames. The client rejects binary frames.
169
159
 
170
- The connection object exposes `ready`, `cursor`, and `close()`. The `ready` promise resolves after the first authentication acknowledgement. It rejects if the first token request fails or the socket closes before authentication. A rejected token request retries automatically when `autoReconnect` is enabled. An invalid token value or WebSocket construction error stops automatic reconnects.
160
+ | Option | Default | Description |
161
+ | --------------------- | ------------- | ------------------------------------------------------------------------------ |
162
+ | `onEvent(event)` | Required | Processes one JSON event. A returned promise delays cursor acknowledgement. |
163
+ | `onError(error)` | No operation | Receives socket, handler, and acknowledgement errors. |
164
+ | `onState(change)` | No operation | Receives connection lifecycle state changes. |
165
+ | `logger` | Client logger | Overrides the logger for this event connection. |
166
+ | `after` | Live edge | Starts event replay after a decimal cursor. |
167
+ | `consumerId` | None | Sends `consumer_id` to the server and enables durable cursor acknowledgements. |
168
+ | `autoReconnect` | `true` | Reconnects after unexpected closure. |
169
+ | `retryDelayMs` | `500` | Sets the first reconnect wait interval. |
170
+ | `maxReconnectDelayMs` | `30000` | Sets the longest reconnect wait interval. |
171
+ | `WebSocketImpl` | Client option | Overrides the WebSocket constructor for this connection. |
172
+
173
+ The connection object exposes `state`, `ready`, `cursor`, and `close()`. Its state is `connecting`, `authenticated`, `reconnecting`, `closed`, or `failed`. The optional `onState` callback receives each state change with its prior state and retry details when available. Callback errors do not stop the connection.
174
+
175
+ The `ready` promise resolves after the first authentication acknowledgement. When `autoReconnect` is enabled, retryable token-provider failures and socket closures keep `ready` pending while the client retries. After the first authentication, use `state` or `onState` to observe later disconnects and recovery. The promise rejects when retries stop before authentication, the token value is invalid, socket construction fails, or the caller closes the connection.
171
176
 
172
177
  The server accepts cursors from `0` through the maximum Snowflake ID. It requires decimal strings without leading zeroes, except for `0` itself.
173
178
 
174
- The client calls one event handler at a time. With `consumerId`, it acknowledges an event after its handler succeeds. It advances `cursor` only after the server accepts that acknowledgement. If event handling or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
179
+ The client calls one event handler at a time. With `consumerId`, it sends that ID in the WebSocket URL and acknowledges each event after its handler succeeds. The server stores progress for that consumer. The client advances `cursor` only after the server accepts the acknowledgement. If event handling or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
180
+
181
+ Do not pass both `after` and `consumerId`. The server uses `after` for cursor-based replay and `consumer_id` for durable replay. The server rejects a request that includes both values.
175
182
 
176
183
  Without `consumerId`, `cursor` remains in memory and is used when the connection reconnects. Store the cursor outside the client if it must survive a new process start. Make event handlers safe to run more than once.
177
184
 
@@ -179,6 +186,6 @@ The event has `event_id`, `cursor`, `event_type`, `occurred_at`, and `payload` f
179
186
 
180
187
  ## Runtime logging
181
188
 
182
- The Node.js entry uses timestamped JSON logs through `@eliware/log` by default. Set `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL` to `debug` to enable debug records. The browser entry has no Node-only logging import and uses a silent logger by default. Supply an object with `debug`, `warn`, and `error` methods to inject a logger.
189
+ The Node.js entry uses timestamped JSON logs through `@eliware/common/log` by default. Set `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL` to `debug` to enable debug records. The browser entry has no Node-only logging import and uses a silent logger by default. Supply an object with `debug`, `warn`, and `error` methods to inject a logger.
183
190
 
184
191
  The client logs HTTP methods, response statuses, durations, error names, request IDs, and WebSocket lifecycle details. It does not log bearer tokens, message bodies, attachment bytes, event payloads, or full request addresses. Pass `logger` in event connection options to override the client logger for a WebSocket connection.
@@ -0,0 +1,47 @@
1
+ # Package details
2
+
3
+ ## Installation and support
4
+
5
+ Install the package with npm:
6
+
7
+ ```sh
8
+ npm install @eliware/mail-client
9
+ ```
10
+
11
+ The package supports Node.js 26 or later. Browser applications use Fetch, Headers, AbortSignal, URL, and WebSocket APIs. Use a bundler that honors the package `browser` export condition to select the browser entry.
12
+
13
+ The package root provides `createMailClient` and `MailApiError` through its default export. It includes TypeScript declarations at `src/index.d.ts`. Node.js uses `src/index.mjs`. Browser builds use `src/index.browser.mjs` and a silent logger by default.
14
+
15
+ The Node.js entry uses `@eliware/common/log` from the `@eliware/common` runtime dependency. The browser entry does not import the Node.js logger. Both entries expose the same client API.
16
+
17
+ ## Environment values
18
+
19
+ The library accepts `baseUrl` and `getAccessToken` as required client options. It does not read API URLs or API tokens from the environment. The examples use these application-owned values:
20
+
21
+ | Value | Example default | Required status | Purpose |
22
+ | ----------------------- | ---------------------------- | -------------------------------- | -------------------------------------------------------- |
23
+ | `MAIL_API_URL` | `https://mail.example.test` | Required by usage examples | Sets the mail-server base address. |
24
+ | `MAIL_API_TOKEN` | `replace-with-a-local-token` | Required by the Node.js examples | Supplies a bearer token to the example host. |
25
+ | `MAIL_WEB_API_TOKEN` | None | Required by the mail-web example | Supplies the server token for browser-token requests. |
26
+ | `MAIL_CLIENT_LOG_LEVEL` | `LOG_LEVEL` or `info` | Optional for the Node.js entry | Sets the package logger level. |
27
+ | `LOG_LEVEL` | `info` | Optional for the Node.js entry | Sets the logger level when the package value is missing. |
28
+
29
+ The host application reads the first three values and passes them to the library. Keep long-lived tokens on trusted servers. The library reads the two log-level values in the Node.js entry. The browser entry does not read them.
30
+
31
+ The package requires `baseUrl` and `getAccessToken` when you create a client. The environment values above belong to the example host applications. Only the two log-level values come from the library process environment.
32
+
33
+ ## Package contents
34
+
35
+ The npm package includes `src/`, `docs/`, `examples/`, `specs/`, `README.md`, `AGENTS.md`, `LICENSE`, `RELEASE_NOTES.md`, and `package.json`. These paths contain runtime entries, declarations, user guides, examples, and package metadata.
36
+
37
+ The package does not include tests, fixtures, coverage output, or the lockfile. npm installs the runtime dependency declared in `package.json`.
38
+
39
+ ## Versions and publication
40
+
41
+ The package uses numeric `MAJOR.MINOR.PATCH` versions. Each release tag follows `vMAJOR.MINOR.PATCH` and matches `package.json`.
42
+
43
+ The GitHub publication workflow tests each tagged commit with Node.js 26 before it publishes the package. It runs `npm test`.
44
+
45
+ npm adds provenance data that identifies the GitHub Actions build that published the package. The package is public on npm under `@eliware/mail-client`.
46
+
47
+ Read [release notes](../RELEASE_NOTES.md) for changes in each published version.
@@ -18,7 +18,7 @@ Allow the browser site address for both HTTP and WebSocket access. Check the bro
18
18
 
19
19
  ## WebSocket events are missing
20
20
 
21
- Wait for `connection.ready` before treating the connection as authenticated. The server must send `{"type":"authenticated"}` before it sends events.
21
+ Wait for `connection.ready` before treating the first connection as authenticated. Read `connection.state` or use `onState` to monitor later reconnects. The server must send `{"type":"authenticated"}` before it sends events.
22
22
 
23
23
  Check that the token provider returns a valid token when mail-client opens or reconnects a socket. Refresh browser tokens before they expire.
24
24
 
@@ -26,7 +26,7 @@ Check the `onError` callback for socket, event handler, or acknowledgement failu
26
26
 
27
27
  ## Debug logs are missing
28
28
 
29
- Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` before the Node.js process starts. The Node.js entry uses `@eliware/log` to write timestamped JSON records.
29
+ Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` before the Node.js process starts. The Node.js entry uses `@eliware/common/log` to write timestamped JSON records.
30
30
 
31
31
  The browser entry stays silent by default. Pass a logger with `debug`, `warn`, and `error` methods to receive browser-side records.
32
32
 
package/docs/usage.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # Usage guide
2
2
 
3
- Use `@eliware/mail-client` to call the mail-server HTTP API and receive mail events through WebSocket. The library works in Node.js 26 or later and current browsers.
3
+ Use `@eliware/mail-client` to call the mail-server HTTP API and receive mail events through WebSocket. The library works in Node.js 26 or later and in browsers that provide the required web APIs.
4
4
 
5
5
  ## Install the package
6
6
 
7
- After the npm release, install the package in the application that calls mail-server:
7
+ Install the package in the application that calls mail-server:
8
8
 
9
9
  ```sh
10
10
  npm install @eliware/mail-client
@@ -18,6 +18,8 @@ Use a long-lived API token in trusted Node.js applications. Keep a different tok
18
18
 
19
19
  Use a short-lived browser token in browser code. The mail-web server keeps its long-lived token and requests a browser token from `POST /api/auth/token`. The mail-web server sends the short-lived token to the signed-in browser through its authenticated session.
20
20
 
21
+ The library does not read `MAIL_API_URL`, `MAIL_API_TOKEN`, or `MAIL_WEB_API_TOKEN`. The host application reads those values and passes them through `baseUrl` and `getAccessToken`. Read [package details](package.md) for each value's purpose and default.
22
+
21
23
  EliD sign-in belongs to mail-web. This package does not run OAuth flows and does not depend on `@eliware/elid-client`.
22
24
 
23
25
  ## Create a Node.js client
@@ -25,7 +27,9 @@ EliD sign-in belongs to mail-web. This package does not run OAuth flows and does
25
27
  Pass the mail-server base address and a token provider. The client calls the provider for every HTTP request and each new WebSocket connection.
26
28
 
27
29
  ```js
28
- import { createMailClient } from "@eliware/mail-client";
30
+ import mailClient from "@eliware/mail-client";
31
+
32
+ const { createMailClient } = mailClient;
29
33
 
30
34
  const mail = createMailClient({
31
35
  baseUrl: process.env.MAIL_API_URL,
@@ -108,33 +112,35 @@ const events = browserMail.connectEvents({
108
112
  }
109
113
  },
110
114
  onError: (error) => logger.error("Mail event connection failed", { error }),
115
+ onState: ({ state }) => updateConnectionStatus(state),
111
116
  });
112
117
 
113
118
  await events.ready;
114
119
  ```
115
120
 
116
- The server sends `{"type":"authenticated"}` before it sends events. The client resolves `ready` after it receives that frame. The client rejects `ready` if the first connection closes before authentication succeeds.
121
+ The server sends `{"type":"authenticated"}` before it sends events. The client resolves `ready` after it receives that frame. If a retryable failure occurs first, `ready` stays pending until authentication succeeds or retries stop. Read `events.state` or use `onState` to monitor later disconnects and recovery after the first authentication.
117
122
 
118
123
  Events are notification signals. They can repeat and do not include complete message bodies or attachment bytes. Read current message data through the HTTP API. Make event handlers safe to run more than once.
119
124
 
120
125
  ## Process durable events
121
126
 
122
- Use a stable `consumerId` when the application must store progress on mail-server. Set `after` to a saved decimal cursor when processing must start from an earlier event.
127
+ Use a stable `consumerId` when the application must store progress on mail-server. The client sends it as `consumer_id` when it opens the WebSocket. The server resumes from the saved cursor for that consumer.
123
128
 
124
129
  ```js
125
130
  const events = browserMail.connectEvents({
126
131
  consumerId: "mail-discord-production",
127
- after: savedCursor,
128
132
  onEvent: handleEvent,
129
133
  onError: reportEventError,
130
134
  });
131
135
  ```
132
136
 
133
- The client runs one event handler at a time. After a handler succeeds, the client posts its cursor to the acknowledgement route. The client advances its cursor only after that request succeeds. If a handler or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
137
+ The client runs one event handler at a time. After a handler succeeds, the client posts its cursor to the acknowledgement route with the same consumer ID. The client advances its cursor only after that request succeeds. If a handler or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
138
+
139
+ Do not set `after` when you set `consumerId`. The server uses the durable consumer cursor for replay and rejects requests that include both values.
134
140
 
135
141
  Without `consumerId`, the client tracks the cursor in memory only. The client includes its current cursor when it reconnects. Store progress with `consumerId` when an application must continue after a new process starts.
136
142
 
137
- The client reconnects after unexpected socket closure or a token-provider failure by default. Set `autoReconnect` to `false` to disable reconnects. Call `events.close()` to stop the connection and its reconnect timer.
143
+ The client reconnects after unexpected socket closure or a token-provider failure by default. It reports `connecting`, `authenticated`, `reconnecting`, `closed`, and `failed` states. Set `autoReconnect` to `false` to disable reconnects. Call `events.close()` to stop the connection and its reconnect timer.
138
144
 
139
145
  ## Report errors
140
146
 
@@ -146,7 +152,7 @@ Use `onError` for WebSocket, event-handler, and event-acknowledgement failures.
146
152
 
147
153
  ## Configure logging
148
154
 
149
- The Node.js entry uses timestamped JSON logs through `@eliware/log` by default. Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` to enable debug records. Pass a logger with `debug`, `warn`, and `error` methods to use the host logger.
155
+ The Node.js entry uses timestamped JSON logs through `@eliware/common/log` by default. Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` to enable debug records. Pass a logger with `debug`, `warn`, and `error` methods to use the host logger.
150
156
 
151
157
  ```js
152
158
  const mail = createMailClient({
@@ -169,3 +175,5 @@ npm run typecheck
169
175
  npm run smoke
170
176
  npm run pack
171
177
  ```
178
+
179
+ The smoke check starts a local HTTP server and a fake WebSocket. It checks the browser entry without a live mail-server or credentials.
@@ -1,15 +1,26 @@
1
1
  # Examples
2
2
 
3
3
  The [basic example](basic.mjs) sends an authenticated request to the mail API status route.
4
+ The [smoke check](mail-client-smoke.mjs) uses a local HTTP server and a fake WebSocket.
4
5
 
5
- ## Prerequisites
6
+ ## Basic example
7
+
8
+ ### Prerequisites
6
9
 
7
10
  Use Node.js 26 or later. Set `MAIL_API_URL` and `MAIL_API_TOKEN` in the local environment. Do not commit credentials.
8
11
 
9
- ## Command
12
+ ### Command
10
13
 
11
14
  Run `node examples/basic.mjs` from the repository root.
12
15
 
13
- ## Expected result
16
+ ### Expected result
14
17
 
15
18
  The example prints the JSON response from the configured mail API. The API must be reachable and the token must have access to the status route.
19
+
20
+ ## Smoke check
21
+
22
+ The smoke check needs no credentials or live mail service. It starts a local API server and fake WebSocket, then checks token requests, status requests, authentication, and event delivery.
23
+
24
+ Run `npm run smoke` from the package root.
25
+
26
+ The check prints `mail-client smoke check passed` when each operation succeeds.
@@ -1,4 +1,6 @@
1
- import { createMailClient } from "../src/index.mjs";
1
+ import mailClient from "../src/index.mjs";
2
+
3
+ const { createMailClient } = mailClient;
2
4
 
3
5
  const mail = createMailClient({
4
6
  baseUrl: process.env.MAIL_API_URL ?? "https://mail.example.test",
@@ -1,6 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { createServer } from "node:http";
3
- import { createMailClient } from "../src/index.browser.mjs";
3
+ import mailClient from "../src/index.browser.mjs";
4
+
5
+ const { createMailClient } = mailClient;
4
6
 
5
7
  class SmokeSocket {
6
8
  static current;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eliware/mail-client",
3
- "version": "15.0.2",
3
+ "version": "17.0.0",
4
4
  "type": "module",
5
5
  "description": "Mail client library for the Eliware mail platform.",
6
6
  "keywords": [
@@ -41,10 +41,10 @@
41
41
  "node": ">=26"
42
42
  },
43
43
  "dependencies": {
44
- "@eliware/log": "^15.0.1"
44
+ "@eliware/common": "^17.0.0"
45
45
  },
46
46
  "devDependencies": {
47
- "@eliware/test": "^15.0.1",
47
+ "@eliware/test": "^17.0.0",
48
48
  "typescript": "^7.0.2"
49
49
  },
50
50
  "jest": {
@@ -94,7 +94,7 @@
94
94
  "url": "https://github.com/eliware/mail-client/issues"
95
95
  },
96
96
  "eliware": {
97
- "id": "E-1361",
97
+ "id": "E-1051",
98
98
  "apply": [
99
99
  "general",
100
100
  "library",
@@ -1,7 +1,7 @@
1
- version: "15.0"
1
+ version: "17.0"
2
2
  description: Requirements for the shared Eliware mail API client library.
3
3
  directives:
4
- - id: E-1361.0
4
+ - id: E-1051.0
5
5
  dos:
6
6
  - Provide HTTP API and WebSocket clients for Node.js and browser applications.
7
7
  - Publish the native ESM package as `@eliware/mail-client` with TypeScript declarations.
@@ -14,7 +14,7 @@ directives:
14
14
  - Do not depend on `@eliware/elid-client` or run OAuth flows.
15
15
  - Do not rewrite mail-cli, mail-discord, or mail-web in this repository.
16
16
 
17
- - id: E-1361.1
17
+ - id: E-1051.1
18
18
  dos:
19
19
  - Support mail-server routes for reads, searches, updates, sends, deletes, and send actions.
20
20
  - Save and find inbound and sent Discord links through authenticated mail-server routes.
@@ -28,7 +28,7 @@ directives:
28
28
  - Do not reshape API response bodies without documenting the change.
29
29
  - Do not retry a send without a stable idempotency key.
30
30
 
31
- - id: E-1361.2
31
+ - id: E-1051.2
32
32
  dos:
33
33
  - Use separate static API keys for mail-discord and mail-web server deployments.
34
34
  - Allow separate long-lived API keys for every mail-cli installation.
@@ -48,15 +48,20 @@ directives:
48
48
  - Do not add multi-user access rules or per-user mailbox scopes.
49
49
  - Do not store browser tokens in durable browser storage.
50
50
 
51
- - id: E-1361.3
51
+ - id: E-1051.3
52
52
  dos:
53
53
  - Authenticate WebSocket sessions after the browser opens each connection.
54
54
  - Send `{"type":"authenticate","token":"..."}` as the first WebSocket message.
55
+ - Require server authentication and event messages to use JSON text frames.
55
56
  - Wait for `{"type":"authenticated"}` before delivering events to callers.
56
57
  - Support different mail-server and mail-web domains without tokens in WebSocket URLs.
57
58
  - Reconnect safely and continue events from the last acknowledged cursor.
58
59
  - Retry WebSocket setup after token provider failures when automatic reconnect is enabled.
60
+ - Expose connection states so hosts can monitor authentication, retries, and terminal
61
+ failures.
59
62
  - Let stable consumer IDs acknowledge processed event cursors through the HTTP API.
63
+ - Send a stable consumer ID as `consumer_id` when opening a durable WebSocket connection.
64
+ - Use the server-stored consumer cursor for durable WebSocket event replay.
60
65
  - Move durable cursors only after handlers and server acknowledgements succeed.
61
66
  - Tolerate repeated events and refresh current data through the HTTP API after notifications.
62
67
  - Let callers process events without RabbitMQ payloads as a client contract.
@@ -65,9 +70,9 @@ directives:
65
70
  - Do not mark a WebSocket session authenticated before the server accepts its first message.
66
71
  - Do not use event notifications as complete message data.
67
72
 
68
- - id: E-1361.4
73
+ - id: E-1051.4
69
74
  dos:
70
- - Use `@eliware/log` directly for timestamped JSON logs in the Node.js package entry.
75
+ - Use `@eliware/common/log` for timestamped JSON logs in the Node.js package entry.
71
76
  - Set the default log level through `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL`.
72
77
  - Accept an injected logger with `debug`, `warn`, and `error` methods for HTTP and WebSocket
73
78
  events.
@@ -1,2 +1,4 @@
1
- export { MailApiError } from "./mail/api/error.mjs";
2
- export { createMailClient } from "./mail/client.mjs";
1
+ import MailApiError from "./mail/api/error.mjs";
2
+ import createMailClient from "./mail/client.mjs";
3
+
4
+ export default { createMailClient, MailApiError };
package/src/index.d.ts CHANGED
@@ -19,7 +19,7 @@ export interface WebSocketFactory {
19
19
 
20
20
  export interface MailClientOptions {
21
21
  baseUrl: string;
22
- getAccessToken: () => string | Promise<string>;
22
+ getAccessToken: (options?: { signal: AbortSignal }) => string | Promise<string>;
23
23
  fetchImpl?: typeof fetch;
24
24
  WebSocketImpl?: WebSocketFactory;
25
25
  timeoutMs?: number;
@@ -39,6 +39,7 @@ export interface EventConnectionOptions {
39
39
  consumerId?: string;
40
40
  onEvent(event: MailEvent): void | Promise<void>;
41
41
  onError?(error: Error): void;
42
+ onState?(change: EventConnectionStateChange): void;
42
43
  autoReconnect?: boolean;
43
44
  retryDelayMs?: number;
44
45
  maxReconnectDelayMs?: number;
@@ -46,7 +47,20 @@ export interface EventConnectionOptions {
46
47
  logger?: MailLogger;
47
48
  }
48
49
 
50
+ export type EventConnectionState =
51
+ "connecting" | "authenticated" | "reconnecting" | "closed" | "failed";
52
+
53
+ export interface EventConnectionStateChange {
54
+ state: EventConnectionState;
55
+ previousState: EventConnectionState;
56
+ closeCode?: number;
57
+ retryDelayMs?: number;
58
+ attempt?: number;
59
+ error?: Error;
60
+ }
61
+
49
62
  export interface EventConnection {
63
+ readonly state: EventConnectionState;
50
64
  readonly ready: Promise<void>;
51
65
  readonly cursor: string | null;
52
66
  close(): void;
@@ -162,11 +176,18 @@ export interface MailClient {
162
176
  connectEvents(options: EventConnectionOptions): EventConnection;
163
177
  }
164
178
 
165
- export class MailApiError extends Error {
179
+ declare class MailApiError extends Error {
166
180
  readonly status: number;
167
181
  readonly code: string;
168
182
  readonly requestId: string | null;
169
183
  readonly payload: unknown;
170
184
  }
171
185
 
172
- export function createMailClient(options: MailClientOptions): MailClient;
186
+ declare function createMailClient(options: MailClientOptions): MailClient;
187
+
188
+ declare const mailClient: {
189
+ createMailClient: typeof createMailClient;
190
+ MailApiError: typeof MailApiError;
191
+ };
192
+
193
+ export default mailClient;
package/src/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
- import { createLogger } from "@eliware/log";
2
- import { createMailClient as createClient } from "./mail/client.mjs";
1
+ import { createLogger } from "@eliware/common/log";
2
+ import createClient from "./mail/client.mjs";
3
+ import MailApiError from "./mail/api/error.mjs";
3
4
 
4
5
  const defaultLogger = createLogger({
5
6
  level: process.env.MAIL_CLIENT_LOG_LEVEL ?? process.env.LOG_LEVEL ?? "info",
@@ -8,8 +9,8 @@ const defaultLogger = createLogger({
8
9
  keys: ["token", "access_token", "authorization", "body", "payload", "attachments"],
9
10
  });
10
11
 
11
- export function createMailClient(options) {
12
+ function createMailClient(options) {
12
13
  return createClient({ ...options, logger: options?.logger ?? defaultLogger });
13
14
  }
14
15
 
15
- export { MailApiError } from "./mail/api/error.mjs";
16
+ export default { createMailClient, MailApiError };
@@ -1,4 +1,4 @@
1
- export class MailApiError extends Error {
1
+ class MailApiError extends Error {
2
2
  constructor(status, payload, headers) {
3
3
  const apiError = payload?.error;
4
4
  super(apiError?.message ?? `Mail API request failed with HTTP ${status}`);
@@ -9,3 +9,5 @@ export class MailApiError extends Error {
9
9
  this.payload = payload;
10
10
  }
11
11
  }
12
+
13
+ export default MailApiError;
@@ -20,7 +20,6 @@ function itemPath(collection, id, suffix = "") {
20
20
  }
21
21
 
22
22
  const maxDiscordSnowflake = 18_446_744_073_709_551_615n;
23
-
24
23
  function validateDiscordIds(channelId, messageId) {
25
24
  for (const [name, value] of [
26
25
  ["discordChannelId", channelId],
@@ -36,7 +35,7 @@ function validateDiscordIds(channelId, messageId) {
36
35
  }
37
36
  }
38
37
 
39
- export function createApiMethods({ request, requestJson }) {
38
+ function createApiMethods({ request, requestJson }) {
40
39
  const json = (method, path, body) =>
41
40
  requestJson(path, { method, ...(body === undefined ? {} : { body }) });
42
41
  const messages = {
@@ -47,9 +46,11 @@ export function createApiMethods({ request, requestJson }) {
47
46
  thread: (id) => requestJson(itemPath("messages", id, "/thread")),
48
47
  update: (id, changes) => json("PATCH", itemPath("messages", id), changes),
49
48
  delete: (id) => json("DELETE", itemPath("messages", id)),
50
- saveDiscordLink: (id, { discordChannelId, discordMessageId } = {}) => {
49
+ saveDiscordLink: (id, link = {}) => {
50
+ const path = itemPath("messages", id, "/discord-links"),
51
+ { discordChannelId, discordMessageId } = link ?? {};
51
52
  validateDiscordIds(discordChannelId, discordMessageId);
52
- return json("PUT", itemPath("messages", id, "/discord-links"), {
53
+ return json("PUT", path, {
53
54
  discord_channel_id: discordChannelId,
54
55
  discord_message_id: discordMessageId,
55
56
  });
@@ -74,9 +75,11 @@ export function createApiMethods({ request, requestJson }) {
74
75
  confirm_duplicate_risk: true,
75
76
  });
76
77
  },
77
- saveDiscordLink: (id, { discordChannelId, discordMessageId } = {}) => {
78
+ saveDiscordLink: (id, link = {}) => {
79
+ const path = itemPath("sent", id, "/discord-links"),
80
+ { discordChannelId, discordMessageId } = link ?? {};
78
81
  validateDiscordIds(discordChannelId, discordMessageId);
79
- return json("PUT", itemPath("sent", id, "/discord-links"), {
82
+ return json("PUT", path, {
80
83
  discord_channel_id: discordChannelId,
81
84
  discord_message_id: discordMessageId,
82
85
  });
@@ -143,3 +146,5 @@ export function createApiMethods({ request, requestJson }) {
143
146
  events,
144
147
  };
145
148
  }
149
+
150
+ export default createApiMethods;
@@ -1,8 +1,8 @@
1
- import { createApiMethods } from "./api/methods.mjs";
2
- import { createEventConnection } from "./event/connection.mjs";
3
- import { createTransport } from "./transport.mjs";
1
+ import createApiMethods from "./api/methods.mjs";
2
+ import createEventConnection from "./event/connection.mjs";
3
+ import createTransport from "./transport.mjs";
4
4
 
5
- export function createMailClient(options = {}) {
5
+ function createMailClient(options = {}) {
6
6
  const transport = createTransport(options);
7
7
  const api = createApiMethods(transport);
8
8
  return {
@@ -20,3 +20,5 @@ export function createMailClient(options = {}) {
20
20
  },
21
21
  };
22
22
  }
23
+
24
+ export default createMailClient;
@@ -5,7 +5,7 @@ function errorName(error) {
5
5
  return typeof error?.name === "string" ? error.name : "Error";
6
6
  }
7
7
 
8
- export function createEventConnectionLogger(logger = silentLogger) {
8
+ function createEventConnectionLogger(logger = silentLogger) {
9
9
  function write(level, message, metadata) {
10
10
  try {
11
11
  logger[level](message, metadata);
@@ -69,3 +69,5 @@ export function createEventConnectionLogger(logger = silentLogger) {
69
69
  },
70
70
  };
71
71
  }
72
+
73
+ export default createEventConnectionLogger;
@@ -0,0 +1,35 @@
1
+ function createEventConnectionState({ onState, onError, settleReady }) {
2
+ let state = "connecting";
3
+
4
+ function transition(nextState, details = {}) {
5
+ if (state === nextState) return;
6
+ const previousState = state;
7
+ state = nextState;
8
+ try {
9
+ onState({ state, previousState, ...details });
10
+ } catch {}
11
+ }
12
+
13
+ function report(error) {
14
+ try {
15
+ onError(error);
16
+ } catch {}
17
+ }
18
+
19
+ function fail(error) {
20
+ transition("failed", { error });
21
+ report(error);
22
+ settleReady(error);
23
+ }
24
+
25
+ return {
26
+ get state() {
27
+ return state;
28
+ },
29
+ transition,
30
+ report,
31
+ fail,
32
+ };
33
+ }
34
+
35
+ export default createEventConnectionState;
@@ -1,11 +1,13 @@
1
- import { createWebSocketSession } from "../websocket/session.mjs";
2
- import { socketUrl } from "../websocket/address.mjs";
3
- import { validateEventOptions } from "../websocket/options.mjs";
4
- import { createEventConnectionLogger } from "./connection-logging.mjs";
5
- import { createEventProcessor } from "./processor.mjs";
6
- import { createReadyState } from "../ready-state.mjs";
7
-
8
- export function createEventConnection({
1
+ import createWebSocketSession from "../websocket/session.mjs";
2
+ import socketUrl from "../websocket/address.mjs";
3
+ import validateEventOptions from "../websocket/options.mjs";
4
+ import createEventConnectionLogger from "./connection/logging.mjs";
5
+ import createEventProcessor from "./processor.mjs";
6
+ import createReadyState from "../ready-state.mjs";
7
+ import createEventConnectionState from "./connection/state.mjs";
8
+ import createReconnectScheduler from "./reconnect-scheduler.mjs";
9
+ import createTokenRequest from "./token-request.mjs";
10
+ export default function createEventConnection({
9
11
  baseUrl,
10
12
  getAccessToken,
11
13
  acknowledgeEvent,
@@ -14,6 +16,7 @@ export function createEventConnection({
14
16
  consumerId,
15
17
  onEvent,
16
18
  onError = () => {},
19
+ onState = () => {},
17
20
  autoReconnect = true,
18
21
  retryDelayMs = 500,
19
22
  maxReconnectDelayMs = 30_000,
@@ -25,6 +28,7 @@ export function createEventConnection({
25
28
  WebSocketImpl,
26
29
  onEvent,
27
30
  onError,
31
+ onState,
28
32
  consumerId,
29
33
  acknowledgeEvent,
30
34
  logger,
@@ -32,30 +36,14 @@ export function createEventConnection({
32
36
  maxReconnectDelayMs,
33
37
  after,
34
38
  });
35
- let cursor = after ?? null;
36
- let socket;
37
- let timer;
38
- let stopped = false;
39
- let attempt = 0;
40
- let authenticated = false;
39
+ let cursor = after ?? null,
40
+ socket;
41
+ let stopped = false,
42
+ authenticated = false;
41
43
  let processing = Promise.resolve();
42
44
  const { ready, settle: settleReady } = createReadyState();
43
-
44
- function report(error) {
45
- try {
46
- onError(error);
47
- } catch {}
48
- }
49
-
50
- function scheduleReconnect(code) {
51
- if (stopped || !autoReconnect || code === 1000 || code === 1008) return;
52
- const delay = Math.min(retryDelayMs * 2 ** attempt, maxReconnectDelayMs);
53
- attempt += 1;
54
- logs.reconnectScheduled(code, delay, attempt, cursor);
55
- timer = setTimeout(connect, delay);
56
- timer.unref?.();
57
- }
58
-
45
+ const lifecycle = createEventConnectionState({ onState, onError, settleReady });
46
+ const tokenRequest = createTokenRequest(getAccessToken);
59
47
  const processEvent = createEventProcessor({
60
48
  getCursor: () => cursor,
61
49
  setCursor: (value) => {
@@ -66,20 +54,19 @@ export function createEventConnection({
66
54
  onEvent,
67
55
  logs,
68
56
  });
69
-
70
57
  async function connect() {
71
58
  if (stopped) return;
59
+ lifecycle.transition("connecting");
72
60
  authenticated = false;
73
61
  logs.started(cursor);
74
62
  let token;
75
63
  try {
76
- token = await getAccessToken();
64
+ token = await tokenRequest.read();
77
65
  } catch (error) {
78
66
  if (stopped) return;
79
67
  logs.tokenProviderFailed(error);
80
- report(error);
81
- settleReady(error);
82
- scheduleReconnect(1006);
68
+ if (!reconnect.schedule(1006, error)) lifecycle.fail(error);
69
+ else lifecycle.report(error);
83
70
  return;
84
71
  }
85
72
  if (stopped) return;
@@ -87,60 +74,74 @@ export function createEventConnection({
87
74
  const error = new TypeError("getAccessToken must return a non-empty bearer token");
88
75
  stopped = true;
89
76
  logs.invalidToken();
90
- report(error);
91
- settleReady(error);
77
+ lifecycle.fail(error);
92
78
  return;
93
79
  }
94
80
  try {
95
81
  socket = createWebSocketSession({
96
- url: socketUrl(baseUrl, cursor),
82
+ url: socketUrl(baseUrl, consumerId === undefined ? cursor : null, consumerId),
97
83
  token,
98
84
  WebSocketImpl,
99
85
  onAuthenticated: () => {
100
86
  authenticated = true;
101
- attempt = 0;
87
+ reconnect.reset();
88
+ lifecycle.transition("authenticated");
102
89
  logs.authenticated(cursor);
103
90
  settleReady();
104
91
  },
105
92
  onEvent: (event) => {
106
93
  processing = processing
107
- .then(() => processEvent(event))
94
+ .then(() => (stopped ? undefined : processEvent(event)))
108
95
  .catch((error) => {
109
96
  logs.eventFailed(event, error);
110
- report(error);
97
+ lifecycle.fail(error);
111
98
  stopped = true;
112
- settleReady(error);
113
99
  socket.close(1011, "event processing failed");
114
100
  });
115
101
  },
116
102
  onClose: (code) => {
117
103
  logs.closed(code, authenticated, cursor);
118
- if (!authenticated)
104
+ const reconnecting = reconnect.schedule(code);
105
+ if (!reconnecting) {
106
+ lifecycle.transition(code === 1000 ? "closed" : "failed", { closeCode: code });
119
107
  settleReady(new Error(`WebSocket authentication closed with code ${code}`));
120
- scheduleReconnect(code);
108
+ }
121
109
  },
122
110
  onError: (error) => {
123
111
  logs.socketFailed(error);
124
- report(error);
112
+ lifecycle.report(error);
125
113
  },
126
114
  });
127
115
  } catch (error) {
128
116
  stopped = true;
129
117
  logs.startFailed(error);
130
- report(error);
131
- settleReady(error);
118
+ lifecycle.fail(error);
132
119
  }
133
120
  }
134
-
121
+ const reconnect = createReconnectScheduler({
122
+ enabled: autoReconnect,
123
+ retryDelayMs,
124
+ maxReconnectDelayMs,
125
+ isStopped: () => stopped,
126
+ connect,
127
+ lifecycle,
128
+ logs,
129
+ getCursor: () => cursor,
130
+ });
135
131
  void connect();
136
132
  return {
137
133
  ready,
134
+ get state() {
135
+ return lifecycle.state;
136
+ },
138
137
  get cursor() {
139
138
  return cursor;
140
139
  },
141
140
  close() {
142
141
  stopped = true;
143
- if (timer) clearTimeout(timer);
142
+ tokenRequest.cancel();
143
+ reconnect.cancel();
144
+ lifecycle.transition("closed");
144
145
  logs.clientClosed(cursor);
145
146
  settleReady(new Error("WebSocket connection closed by the client"));
146
147
  socket?.close(1000, "client closed");
@@ -1,6 +1,6 @@
1
- import { isValidCursor } from "../websocket/cursor.mjs";
1
+ import isValidCursor from "../websocket/cursor.mjs";
2
2
 
3
- export function createEventProcessor({
3
+ function createEventProcessor({
4
4
  getCursor,
5
5
  setCursor,
6
6
  consumerId,
@@ -25,3 +25,5 @@ export function createEventProcessor({
25
25
  logs.eventCompleted(event?.event_type, eventCursor, consumerId !== undefined);
26
26
  };
27
27
  }
28
+
29
+ export default createEventProcessor;
@@ -0,0 +1,42 @@
1
+ function createReconnectScheduler({
2
+ enabled,
3
+ retryDelayMs,
4
+ maxReconnectDelayMs,
5
+ isStopped,
6
+ connect,
7
+ lifecycle,
8
+ logs,
9
+ getCursor,
10
+ }) {
11
+ let attempt = 0;
12
+ let timer;
13
+
14
+ function schedule(code, error) {
15
+ if (isStopped() || !enabled || [1000, 1002, 1003, 1007, 1008, 1009, 1010].includes(code))
16
+ return false;
17
+ if (timer !== undefined) return true;
18
+ const delay = Math.min(retryDelayMs * 2 ** attempt, maxReconnectDelayMs);
19
+ attempt += 1;
20
+ lifecycle.transition("reconnecting", { closeCode: code, retryDelayMs: delay, attempt, error });
21
+ logs.reconnectScheduled(code, delay, attempt, getCursor());
22
+ timer = setTimeout(() => {
23
+ timer = undefined;
24
+ connect();
25
+ }, delay);
26
+ timer.unref?.();
27
+ return true;
28
+ }
29
+
30
+ return {
31
+ schedule,
32
+ reset() {
33
+ attempt = 0;
34
+ },
35
+ cancel() {
36
+ if (timer) clearTimeout(timer);
37
+ timer = undefined;
38
+ },
39
+ };
40
+ }
41
+
42
+ export default createReconnectScheduler;
@@ -0,0 +1,32 @@
1
+ function createTokenRequest(getAccessToken, externalSignal) {
2
+ const controller = new AbortController();
3
+ const signal = externalSignal
4
+ ? AbortSignal.any([controller.signal, externalSignal])
5
+ : controller.signal;
6
+
7
+ function read() {
8
+ if (signal.aborted) return Promise.reject(signal.reason);
9
+ let token;
10
+ try {
11
+ token = getAccessToken({ signal });
12
+ } catch (error) {
13
+ if (signal.aborted) return Promise.reject(signal.reason);
14
+ throw error;
15
+ }
16
+ if (signal.aborted) return Promise.reject(signal.reason);
17
+ if (token === null || typeof token !== "object" || typeof token.then !== "function")
18
+ return token;
19
+ let onAbort;
20
+ const aborted = new Promise((_, reject) => {
21
+ onAbort = () => reject(signal.reason);
22
+ signal.addEventListener("abort", onAbort, { once: true });
23
+ });
24
+ return Promise.race([token, aborted]).finally(() =>
25
+ signal.removeEventListener("abort", onAbort),
26
+ );
27
+ }
28
+
29
+ return { read, cancel: () => controller.abort() };
30
+ }
31
+
32
+ export default createTokenRequest;
@@ -1,4 +1,4 @@
1
- export function createReadyState() {
1
+ function createReadyState() {
2
2
  let settled = false;
3
3
  let resolveReady;
4
4
  let rejectReady;
@@ -17,3 +17,5 @@ export function createReadyState() {
17
17
 
18
18
  return { ready, settle };
19
19
  }
20
+
21
+ export default createReadyState;
@@ -1,4 +1,4 @@
1
- export function normalizeBaseUrl(value) {
1
+ function normalizeBaseUrl(value) {
2
2
  let url;
3
3
  try {
4
4
  url = new URL(value);
@@ -11,3 +11,5 @@ export function normalizeBaseUrl(value) {
11
11
  }
12
12
  return url.origin;
13
13
  }
14
+
15
+ export default normalizeBaseUrl;
@@ -1,5 +1,6 @@
1
- import { MailApiError } from "./api/error.mjs";
2
- import { normalizeBaseUrl } from "./transport/base-url.mjs";
1
+ import MailApiError from "./api/error.mjs";
2
+ import normalizeBaseUrl from "./transport/base-url.mjs";
3
+ import createTokenRequest from "./event/token-request.mjs";
3
4
 
4
5
  const defaultTimeoutMs = 15_000;
5
6
  const noOperation = () => {};
@@ -23,7 +24,7 @@ async function errorPayload(response) {
23
24
  }
24
25
  }
25
26
 
26
- export function createTransport({
27
+ function createTransport({
27
28
  baseUrl,
28
29
  getAccessToken,
29
30
  fetchImpl = globalThis.fetch,
@@ -57,9 +58,13 @@ export function createTransport({
57
58
  const method = String(options.method ?? "GET").toUpperCase();
58
59
  const startedAt = Date.now();
59
60
  logger.debug("Mail API request started", { method });
61
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
62
+ const signal = options.signal
63
+ ? AbortSignal.any([options.signal, timeoutSignal])
64
+ : timeoutSignal;
60
65
  let token;
61
66
  try {
62
- token = await getAccessToken();
67
+ token = await createTokenRequest(getAccessToken, signal).read();
63
68
  } catch (error) {
64
69
  logger.error("Mail API access token provider failed", {
65
70
  method,
@@ -86,10 +91,6 @@ export function createTransport({
86
91
  headers.set("content-type", "application/json");
87
92
  }
88
93
 
89
- const timeoutSignal = AbortSignal.timeout(timeoutMs);
90
- const signal = options.signal
91
- ? AbortSignal.any([options.signal, timeoutSignal])
92
- : timeoutSignal;
93
94
  let response;
94
95
  try {
95
96
  response = await fetchImpl(url, { ...options, method, headers, body: requestBody, signal });
@@ -131,3 +132,5 @@ export function createTransport({
131
132
 
132
133
  return { request, requestJson, baseUrl: apiOrigin };
133
134
  }
135
+
136
+ export default createTransport;
@@ -1,6 +1,9 @@
1
- export function socketUrl(baseUrl, cursor) {
1
+ function socketUrl(baseUrl, cursor, consumerId) {
2
2
  const url = new URL("/ws", baseUrl);
3
3
  url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
4
4
  if (cursor !== null) url.searchParams.set("after", cursor);
5
+ if (consumerId !== undefined) url.searchParams.set("consumer_id", consumerId);
5
6
  return url.toString();
6
7
  }
8
+
9
+ export default socketUrl;
@@ -1,7 +1,9 @@
1
1
  const maxSnowflakeCursor = 18_446_744_073_709_551_615n;
2
2
  const decimalCursorPattern = /^(0|[1-9]\d{0,19})$/;
3
3
 
4
- export function isValidCursor(value) {
4
+ function isValidCursor(value) {
5
5
  if (typeof value !== "string" || !decimalCursorPattern.test(value)) return false;
6
6
  return BigInt(value) <= maxSnowflakeCursor;
7
7
  }
8
+
9
+ export default isValidCursor;
@@ -1,7 +1,9 @@
1
- export function eventData(value) {
1
+ function eventData(value) {
2
2
  const data = value?.data ?? value;
3
3
  if (typeof data === "string") return data;
4
4
  if (ArrayBuffer.isView(data)) return new TextDecoder().decode(data);
5
5
  if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
6
6
  throw new TypeError("WebSocket frame must contain JSON text");
7
7
  }
8
+
9
+ export default eventData;
@@ -1,4 +1,4 @@
1
- export function subscribe(socket, name, handler) {
1
+ function subscribe(socket, name, handler) {
2
2
  if (typeof socket.addEventListener === "function") {
3
3
  socket.addEventListener(name, handler);
4
4
  return () => socket.removeEventListener?.(name, handler);
@@ -9,3 +9,5 @@ export function subscribe(socket, name, handler) {
9
9
  }
10
10
  throw new TypeError("WebSocket must support event listeners");
11
11
  }
12
+
13
+ export default subscribe;
@@ -1,10 +1,11 @@
1
- import { isValidCursor } from "./cursor.mjs";
1
+ import isValidCursor from "./cursor.mjs";
2
2
 
3
- export function validateEventOptions({
3
+ function validateEventOptions({
4
4
  getAccessToken,
5
5
  WebSocketImpl,
6
6
  onEvent,
7
7
  onError,
8
+ onState,
8
9
  consumerId,
9
10
  acknowledgeEvent,
10
11
  logger,
@@ -18,6 +19,7 @@ export function validateEventOptions({
18
19
  throw new TypeError("WebSocketImpl must be a constructor");
19
20
  if (typeof onEvent !== "function") throw new TypeError("onEvent must be a function");
20
21
  if (typeof onError !== "function") throw new TypeError("onError must be a function");
22
+ if (typeof onState !== "function") throw new TypeError("onState must be a function");
21
23
  if (
22
24
  logger !== undefined &&
23
25
  (typeof logger?.debug !== "function" ||
@@ -41,4 +43,9 @@ export function validateEventOptions({
41
43
  if (after !== undefined && !isValidCursor(after)) {
42
44
  throw new TypeError("after must be a decimal Snowflake cursor");
43
45
  }
46
+ if (after !== undefined && consumerId !== undefined) {
47
+ throw new TypeError("after and consumerId cannot be used together");
48
+ }
44
49
  }
50
+
51
+ export default validateEventOptions;
@@ -1,7 +1,7 @@
1
- import { eventData } from "./frames.mjs";
2
- import { subscribe } from "./listeners.mjs";
1
+ import eventData from "./frames.mjs";
2
+ import subscribe from "./listeners.mjs";
3
3
 
4
- export function createWebSocketSession({
4
+ function createWebSocketSession({
5
5
  url,
6
6
  token,
7
7
  WebSocketImpl,
@@ -16,7 +16,13 @@ export function createWebSocketSession({
16
16
  socket.send(JSON.stringify({ type: "authenticate", token }));
17
17
  });
18
18
  subscribe(socket, "message", (value, isBinary = false) => {
19
- if (isBinary) {
19
+ const data = value?.data;
20
+ if (
21
+ isBinary ||
22
+ (typeof Blob !== "undefined" && data instanceof Blob) ||
23
+ data instanceof ArrayBuffer ||
24
+ ArrayBuffer.isView(data)
25
+ ) {
20
26
  onError(new TypeError("WebSocket frames must use JSON text"));
21
27
  socket.close(1002, "JSON text required");
22
28
  return;
@@ -47,3 +53,5 @@ export function createWebSocketSession({
47
53
  );
48
54
  return socket;
49
55
  }
56
+
57
+ export default createWebSocketSession;