@eliware/mail-client 0.0.1 → 15.0.2

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
@@ -2,11 +2,11 @@
2
2
 
3
3
  ## Project
4
4
 
5
- Build the shared mail-server API client library for Eliware.
5
+ See README.md for the repository purpose, owner, scope, and boundaries.
6
6
 
7
7
  ## Scope and boundaries
8
8
 
9
- Use specs/directives.yaml for repository scope and limits.
9
+ Keep repository requirements in specs/directives.yaml.
10
10
 
11
11
  ## Layout
12
12
 
@@ -33,7 +33,7 @@ Keep credentials, secret values, private data, and runtime state out of Git.
33
33
 
34
34
  ## Changes
35
35
 
36
- Keep each document in the repository that owns its content.
36
+ Keep each document in the repository that owns its content. Update its nearest index when you add a document.
37
37
 
38
38
  ## Library
39
39
 
package/README.md CHANGED
@@ -23,8 +23,7 @@ Mail client library for the Eliware mail platform.
23
23
 
24
24
  ## Features
25
25
 
26
- Call the mail-server HTTP API and receive WebSocket events from Node.js and browser applications.
27
- Provide bearer tokens through the host application and keep API responses available to callers.
26
+ Call the mail-server API from Node.js and browser applications. Receive WebSocket events and preserve server response envelopes.
28
27
 
29
28
  ## Requirements
30
29
 
@@ -32,48 +31,36 @@ Use Node.js 26 or later. Browser applications require Fetch, Headers, AbortSigna
32
31
 
33
32
  ## Setup
34
33
 
35
- After the npm release, install the package with `npm install @eliware/mail-client`.
36
- Set the mail API URL and a bearer-token provider in the host application.
37
- Read the [usage guide](docs/usage.md) for configuration details.
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.
38
35
 
39
36
  ## Usage
40
37
 
41
- Read the [usage guide](docs/usage.md) and [release notes](RELEASE_NOTES.md).
42
- The [basic example](examples/README.md) requests mail API status.
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).
43
39
 
44
40
  ## Development
45
41
 
46
- Read [AGENTS.md](AGENTS.md) before changing files.
47
- Read the [documentation index](docs/README.md) and [specifications index](specs/README.md) for package guidance.
48
- Run `npm ci` to install locked dependencies.
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.
49
43
 
50
44
  ## Testing
51
45
 
52
- Run `npm test` for aggregate checks.
53
- Run `npm run smoke` for a local HTTP and WebSocket check.
54
- Run `npm run typecheck` to check TypeScript declarations.
55
- Run `npm run pack` to check package contents.
46
+ Run `npm test` for aggregate checks. Run `npm run smoke` for an HTTP and WebSocket check.
56
47
 
57
48
  ## Troubleshooting
58
49
 
59
- Check the API URL, bearer-token provider, and network access when a request fails.
60
- Read the [API reference](docs/api.md) for errors and response details.
50
+ Read the [troubleshooting guide](docs/troubleshooting.md) for common API and connection problems.
61
51
 
62
52
  ## Security
63
53
 
64
- Keep API keys and temporary credentials in approved secret stores.
65
- Do not log bearer tokens.
66
- Do not expose static API keys to browser code.
54
+ Keep long-lived API tokens in server-side secret stores. Do not expose them to browser code or logs.
67
55
 
68
56
  ## API
69
57
 
70
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.
71
60
 
72
61
  ## Packaging
73
62
 
74
- Use the npm publication workflow with provenance.
75
- Use version tags that match `package.json`.
76
- Follow approved release steps before you publish a tag.
63
+ Follow approved release steps before you publish a version. Read [release notes](RELEASE_NOTES.md) for package changes.
77
64
 
78
65
  ## Examples
79
66
 
package/RELEASE_NOTES.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Release Notes
2
2
 
3
+ ## 15.0.2 — 2026-10-30
4
+
5
+ ### Added
6
+
7
+ - Add timestamped JSON logs through `@eliware/log` for HTTP and WebSocket requests.
8
+ - Add debug-level lifecycle records controlled by `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL`.
9
+ - Add an end-user troubleshooting guide for authentication, browser access, WebSocket events, and logs.
10
+
11
+ ### Changed
12
+
13
+ - Set the package version to 15.0.2.
14
+ - Replace the direct `@eliware/common` dependency with `@eliware/log`.
15
+ - Update locked dependencies and align the README and contributor guidance with repository conventions.
16
+ - Resolve request paths that start with `//` on the configured API address.
17
+ - Keep browser logging silent by default and allow injected loggers for HTTP and WebSocket calls.
18
+
19
+ ### Fixed
20
+
21
+ - Resolve the WebSocket readiness promise when event processing fails.
22
+
3
23
  ## 15.0.1 — 2026-10-29
4
24
 
5
25
  ### Added
package/docs/README.md CHANGED
@@ -6,3 +6,4 @@ 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
+ - [Troubleshooting](troubleshooting.md)
package/docs/api.md CHANGED
@@ -15,7 +15,7 @@ Call `createMailClient(options)` to create an HTTP and WebSocket client.
15
15
  | `timeoutMs` | No | `15000` | Sets the timeout for each HTTP request. |
16
16
  | `logger` | No | Node.js: `@eliware/log`, browser: silent | Supplies `debug`, `warn`, and `error` methods. |
17
17
 
18
- Use an HTTP or HTTPS base address without a path, query, fragment, user name, or password. The client rejects request paths that resolve to a different address.
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
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.
21
21
 
@@ -159,6 +159,7 @@ The client waits for this server frame before it delivers events:
159
159
  | --------------------- | ------------- | --------------------------------------------------------------------------- |
160
160
  | `onEvent(event)` | Required | Processes one JSON event. A returned promise delays cursor acknowledgement. |
161
161
  | `onError(error)` | No operation | Receives socket, handler, and acknowledgement errors. |
162
+ | `logger` | Client logger | Overrides the logger for this event connection. |
162
163
  | `after` | Live edge | Starts event replay after a decimal cursor. |
163
164
  | `consumerId` | None | Enables server-side cursor acknowledgements. |
164
165
  | `autoReconnect` | `true` | Reconnects after unexpected closure. |
@@ -178,6 +179,6 @@ The event has `event_id`, `cursor`, `event_type`, `occurred_at`, and `payload` f
178
179
 
179
180
  ## Runtime logging
180
181
 
181
- The Node.js entry uses `@eliware/log` by default. 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.
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.
182
183
 
183
- The client logs HTTP methods, response statuses, error names, and request IDs. It does not log bearer tokens, message bodies, attachment bytes, or full request addresses.
184
+ 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,33 @@
1
+ # Troubleshooting
2
+
3
+ Use this guide to find common mail-server API and WebSocket connection problems.
4
+
5
+ ## HTTP authentication fails
6
+
7
+ Check that the token provider returns a valid bearer token for every request. Mail-client calls the provider before each HTTP request.
8
+
9
+ For browser requests, request a new short-lived token through the signed-in host application. Keep long-lived API tokens on the server.
10
+
11
+ Read the `MailApiError` status, code, and request ID. Use the request ID to find the matching mail-server log record.
12
+
13
+ ## Browser requests fail
14
+
15
+ Check that mail-server allows the exact browser site address. Include the scheme and port from the browser address.
16
+
17
+ Allow the browser site address for both HTTP and WebSocket access. Check the browser network panel for CORS details.
18
+
19
+ ## WebSocket events are missing
20
+
21
+ Wait for `connection.ready` before treating the connection as authenticated. The server must send `{"type":"authenticated"}` before it sends events.
22
+
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
+
25
+ Check the `onError` callback for socket, event handler, or acknowledgement failures. Event handlers must succeed before mail-client acknowledges their cursor.
26
+
27
+ ## Debug logs are missing
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.
30
+
31
+ The browser entry stays silent by default. Pass a logger with `debug`, `warn`, and `error` methods to receive browser-side records.
32
+
33
+ Mail-client omits tokens, message bodies, attachment bytes, event payloads, and complete request addresses from its own records.
package/docs/usage.md CHANGED
@@ -146,7 +146,7 @@ Use `onError` for WebSocket, event-handler, and event-acknowledgement failures.
146
146
 
147
147
  ## Configure logging
148
148
 
149
- The Node.js entry uses `@eliware/log` by default. Pass a logger with `debug`, `warn`, and `error` methods to use the host logger.
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.
150
150
 
151
151
  ```js
152
152
  const mail = createMailClient({
@@ -156,7 +156,7 @@ const mail = createMailClient({
156
156
  });
157
157
  ```
158
158
 
159
- The browser entry has a silent logger by default and imports no Node-only logger. The client logs HTTP methods, response statuses, error names, and request IDs. It does not log tokens, message bodies, attachment bytes, or full request addresses.
159
+ The browser entry has a silent logger by default and imports no Node-only logger. The client logs HTTP methods, response statuses, durations, error names, request IDs, and WebSocket lifecycle details. It does not log tokens, message bodies, attachment bytes, event payloads, or full request addresses.
160
160
 
161
161
  ## Validate a checkout
162
162
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eliware/mail-client",
3
- "version": "0.0.1",
3
+ "version": "15.0.2",
4
4
  "type": "module",
5
5
  "description": "Mail client library for the Eliware mail platform.",
6
6
  "keywords": [
@@ -41,7 +41,7 @@
41
41
  "node": ">=26"
42
42
  },
43
43
  "dependencies": {
44
- "@eliware/log": "^15.0.0"
44
+ "@eliware/log": "^15.0.1"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@eliware/test": "^15.0.1",
@@ -67,10 +67,13 @@ directives:
67
67
 
68
68
  - id: E-1361.4
69
69
  dos:
70
- - Use `@eliware/log` for structured logs in the Node.js package entry.
71
- - Accept an injected logger with `debug`, `warn`, and `error` methods.
70
+ - Use `@eliware/log` directly for timestamped JSON logs in the Node.js package entry.
71
+ - Set the default log level through `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL`.
72
+ - Accept an injected logger with `debug`, `warn`, and `error` methods for HTTP and WebSocket
73
+ events.
72
74
  - Omit Node-only logging imports from the browser entry.
73
75
  - Log request methods, response statuses, error names, and available request IDs.
74
76
  donts:
75
- - Do not log tokens, message bodies, attachment contents, or full request URLs.
77
+ - Do not log tokens, message bodies, attachment contents, event payloads, or full request
78
+ URLs.
76
79
  - Do not require logging from browser clients.
package/src/index.d.ts CHANGED
@@ -43,6 +43,7 @@ export interface EventConnectionOptions {
43
43
  retryDelayMs?: number;
44
44
  maxReconnectDelayMs?: number;
45
45
  WebSocketImpl?: WebSocketFactory;
46
+ logger?: MailLogger;
46
47
  }
47
48
 
48
49
  export interface EventConnection {
package/src/index.mjs CHANGED
@@ -1,6 +1,13 @@
1
- import defaultLogger from "@eliware/log";
1
+ import { createLogger } from "@eliware/log";
2
2
  import { createMailClient as createClient } from "./mail/client.mjs";
3
3
 
4
+ const defaultLogger = createLogger({
5
+ level: process.env.MAIL_CLIENT_LOG_LEVEL ?? process.env.LOG_LEVEL ?? "info",
6
+ format: "json",
7
+ timestamp: true,
8
+ keys: ["token", "access_token", "authorization", "body", "payload", "attachments"],
9
+ });
10
+
4
11
  export function createMailClient(options) {
5
12
  return createClient({ ...options, logger: options?.logger ?? defaultLogger });
6
13
  }
@@ -1,5 +1,5 @@
1
1
  import { createApiMethods } from "./api/methods.mjs";
2
- import { createEventConnection } from "./event-connection.mjs";
2
+ import { createEventConnection } from "./event/connection.mjs";
3
3
  import { createTransport } from "./transport.mjs";
4
4
 
5
5
  export function createMailClient(options = {}) {
@@ -15,6 +15,7 @@ export function createMailClient(options = {}) {
15
15
  getAccessToken: options.getAccessToken,
16
16
  WebSocketImpl: settings.WebSocketImpl ?? options.WebSocketImpl,
17
17
  acknowledgeEvent: api.events.acknowledge,
18
+ logger: settings.logger ?? options.logger,
18
19
  });
19
20
  },
20
21
  };
@@ -0,0 +1,71 @@
1
+ const noop = () => {};
2
+ const silentLogger = { debug: noop, warn: noop, error: noop };
3
+
4
+ function errorName(error) {
5
+ return typeof error?.name === "string" ? error.name : "Error";
6
+ }
7
+
8
+ export function createEventConnectionLogger(logger = silentLogger) {
9
+ function write(level, message, metadata) {
10
+ try {
11
+ logger[level](message, metadata);
12
+ } catch {}
13
+ }
14
+
15
+ return {
16
+ started(cursor) {
17
+ write("debug", "Mail event connection started", { cursor });
18
+ },
19
+ tokenProviderFailed(error) {
20
+ write("error", "Mail event token provider failed", { errorName: errorName(error) });
21
+ },
22
+ invalidToken() {
23
+ write("error", "Mail event token provider returned an invalid token", {
24
+ errorName: "TypeError",
25
+ });
26
+ },
27
+ reconnectScheduled(closeCode, delay, attempt, cursor) {
28
+ write("warn", "Mail event connection reconnect scheduled", {
29
+ closeCode,
30
+ delayMs: delay,
31
+ attempt,
32
+ cursor,
33
+ });
34
+ },
35
+ eventSkipped(cursor) {
36
+ write("debug", "Mail event skipped because its cursor was already handled", { cursor });
37
+ },
38
+ eventStarted(eventType, cursor) {
39
+ write("debug", "Mail event handling started", { eventType, cursor });
40
+ },
41
+ eventCompleted(eventType, cursor, acknowledged) {
42
+ write("debug", "Mail event handling completed", { eventType, cursor, acknowledged });
43
+ },
44
+ authenticated(cursor) {
45
+ write("debug", "Mail event connection authenticated", { cursor });
46
+ },
47
+ eventFailed(event, error) {
48
+ write("error", "Mail event handling failed", {
49
+ eventType: event?.event_type,
50
+ cursor: event?.cursor ?? event?.event_id,
51
+ errorName: errorName(error),
52
+ });
53
+ },
54
+ closed(closeCode, authenticated, cursor) {
55
+ write(authenticated ? "debug" : "warn", "Mail event connection closed", {
56
+ closeCode,
57
+ authenticated,
58
+ cursor,
59
+ });
60
+ },
61
+ socketFailed(error) {
62
+ write("error", "Mail event socket failed", { errorName: errorName(error) });
63
+ },
64
+ startFailed(error) {
65
+ write("error", "Mail event connection failed to start", { errorName: errorName(error) });
66
+ },
67
+ clientClosed(cursor) {
68
+ write("debug", "Mail event connection closed by client", { cursor });
69
+ },
70
+ };
71
+ }
@@ -1,9 +1,9 @@
1
- import { createWebSocketSession } from "./websocket/session.mjs";
2
- import { socketUrl } from "./websocket/address.mjs";
3
- import { isValidCursor } from "./websocket/cursor.mjs";
4
- import { validateEventOptions } from "./websocket/options.mjs";
5
-
6
- const noop = () => {};
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
7
 
8
8
  export function createEventConnection({
9
9
  baseUrl,
@@ -13,38 +13,33 @@ export function createEventConnection({
13
13
  after,
14
14
  consumerId,
15
15
  onEvent,
16
- onError = noop,
16
+ onError = () => {},
17
17
  autoReconnect = true,
18
18
  retryDelayMs = 500,
19
19
  maxReconnectDelayMs = 30_000,
20
+ logger,
20
21
  } = {}) {
21
- const options = {
22
+ const logs = createEventConnectionLogger(logger);
23
+ validateEventOptions({
22
24
  getAccessToken,
23
25
  WebSocketImpl,
24
26
  onEvent,
25
27
  onError,
26
28
  consumerId,
27
29
  acknowledgeEvent,
30
+ logger,
28
31
  retryDelayMs,
29
32
  maxReconnectDelayMs,
30
33
  after,
31
- };
32
- validateEventOptions(options);
34
+ });
33
35
  let cursor = after ?? null;
34
36
  let socket;
35
37
  let timer;
36
38
  let stopped = false;
37
39
  let attempt = 0;
38
40
  let authenticated = false;
39
- let initialSettled = false;
40
41
  let processing = Promise.resolve();
41
- let resolveReady;
42
- let rejectReady;
43
- const ready = new Promise((resolve, reject) => {
44
- resolveReady = resolve;
45
- rejectReady = reject;
46
- });
47
- void ready.catch(noop);
42
+ const { ready, settle: settleReady } = createReadyState();
48
43
 
49
44
  function report(error) {
50
45
  try {
@@ -52,40 +47,36 @@ export function createEventConnection({
52
47
  } catch {}
53
48
  }
54
49
 
55
- function settleReady(error) {
56
- if (initialSettled) return;
57
- initialSettled = true;
58
- if (error) rejectReady(error);
59
- else resolveReady();
60
- }
61
-
62
50
  function scheduleReconnect(code) {
63
51
  if (stopped || !autoReconnect || code === 1000 || code === 1008) return;
64
52
  const delay = Math.min(retryDelayMs * 2 ** attempt, maxReconnectDelayMs);
65
53
  attempt += 1;
54
+ logs.reconnectScheduled(code, delay, attempt, cursor);
66
55
  timer = setTimeout(connect, delay);
67
56
  timer.unref?.();
68
57
  }
69
58
 
70
- async function processEvent(event) {
71
- const eventCursor = event.cursor ?? event.event_id;
72
- if (!isValidCursor(eventCursor)) {
73
- throw new TypeError("event cursor must be a decimal Snowflake cursor");
74
- }
75
- if (cursor !== null && BigInt(eventCursor) <= BigInt(cursor)) return;
76
- await onEvent(event);
77
- if (consumerId !== undefined) await acknowledgeEvent(consumerId, eventCursor);
78
- cursor = eventCursor;
79
- }
59
+ const processEvent = createEventProcessor({
60
+ getCursor: () => cursor,
61
+ setCursor: (value) => {
62
+ cursor = value;
63
+ },
64
+ consumerId,
65
+ acknowledgeEvent,
66
+ onEvent,
67
+ logs,
68
+ });
80
69
 
81
70
  async function connect() {
82
71
  if (stopped) return;
83
72
  authenticated = false;
73
+ logs.started(cursor);
84
74
  let token;
85
75
  try {
86
76
  token = await getAccessToken();
87
77
  } catch (error) {
88
78
  if (stopped) return;
79
+ logs.tokenProviderFailed(error);
89
80
  report(error);
90
81
  settleReady(error);
91
82
  scheduleReconnect(1006);
@@ -95,6 +86,7 @@ export function createEventConnection({
95
86
  if (typeof token !== "string" || token.length === 0) {
96
87
  const error = new TypeError("getAccessToken must return a non-empty bearer token");
97
88
  stopped = true;
89
+ logs.invalidToken();
98
90
  report(error);
99
91
  settleReady(error);
100
92
  return;
@@ -107,26 +99,34 @@ export function createEventConnection({
107
99
  onAuthenticated: () => {
108
100
  authenticated = true;
109
101
  attempt = 0;
102
+ logs.authenticated(cursor);
110
103
  settleReady();
111
104
  },
112
105
  onEvent: (event) => {
113
106
  processing = processing
114
107
  .then(() => processEvent(event))
115
108
  .catch((error) => {
109
+ logs.eventFailed(event, error);
116
110
  report(error);
117
111
  stopped = true;
112
+ settleReady(error);
118
113
  socket.close(1011, "event processing failed");
119
114
  });
120
115
  },
121
116
  onClose: (code) => {
117
+ logs.closed(code, authenticated, cursor);
122
118
  if (!authenticated)
123
119
  settleReady(new Error(`WebSocket authentication closed with code ${code}`));
124
120
  scheduleReconnect(code);
125
121
  },
126
- onError: report,
122
+ onError: (error) => {
123
+ logs.socketFailed(error);
124
+ report(error);
125
+ },
127
126
  });
128
127
  } catch (error) {
129
128
  stopped = true;
129
+ logs.startFailed(error);
130
130
  report(error);
131
131
  settleReady(error);
132
132
  }
@@ -141,6 +141,7 @@ export function createEventConnection({
141
141
  close() {
142
142
  stopped = true;
143
143
  if (timer) clearTimeout(timer);
144
+ logs.clientClosed(cursor);
144
145
  settleReady(new Error("WebSocket connection closed by the client"));
145
146
  socket?.close(1000, "client closed");
146
147
  },
@@ -0,0 +1,27 @@
1
+ import { isValidCursor } from "../websocket/cursor.mjs";
2
+
3
+ export function createEventProcessor({
4
+ getCursor,
5
+ setCursor,
6
+ consumerId,
7
+ acknowledgeEvent,
8
+ onEvent,
9
+ logs,
10
+ }) {
11
+ return async function processEvent(event) {
12
+ const eventCursor = event.cursor ?? event.event_id;
13
+ if (!isValidCursor(eventCursor)) {
14
+ throw new TypeError("event cursor must be a decimal Snowflake cursor");
15
+ }
16
+ const cursor = getCursor();
17
+ if (cursor !== null && BigInt(eventCursor) <= BigInt(cursor)) {
18
+ logs.eventSkipped(eventCursor);
19
+ return;
20
+ }
21
+ logs.eventStarted(event?.event_type, eventCursor);
22
+ await onEvent(event);
23
+ if (consumerId !== undefined) await acknowledgeEvent(consumerId, eventCursor);
24
+ setCursor(eventCursor);
25
+ logs.eventCompleted(event?.event_type, eventCursor, consumerId !== undefined);
26
+ };
27
+ }
@@ -0,0 +1,19 @@
1
+ export function createReadyState() {
2
+ let settled = false;
3
+ let resolveReady;
4
+ let rejectReady;
5
+ const ready = new Promise((resolve, reject) => {
6
+ resolveReady = resolve;
7
+ rejectReady = reject;
8
+ });
9
+ void ready.catch(() => {});
10
+
11
+ function settle(error) {
12
+ if (settled) return;
13
+ settled = true;
14
+ if (error) rejectReady(error);
15
+ else resolveReady();
16
+ }
17
+
18
+ return { ready, settle };
19
+ }
@@ -50,11 +50,29 @@ export function createTransport({
50
50
  if (typeof path !== "string" || path.length === 0) {
51
51
  throw new TypeError("path must be a non-empty string");
52
52
  }
53
- const url = new URL(path, `${apiOrigin}/`);
53
+ const requestPath = path.startsWith("//") ? path.replace(/^\/+/, "/") : path;
54
+ const url = new URL(requestPath, `${apiOrigin}/`);
54
55
  if (url.origin !== apiOrigin) throw new TypeError("path must use the configured API origin");
55
56
 
56
- const token = await getAccessToken();
57
+ const method = String(options.method ?? "GET").toUpperCase();
58
+ const startedAt = Date.now();
59
+ logger.debug("Mail API request started", { method });
60
+ let token;
61
+ try {
62
+ token = await getAccessToken();
63
+ } catch (error) {
64
+ logger.error("Mail API access token provider failed", {
65
+ method,
66
+ durationMs: Date.now() - startedAt,
67
+ errorName: typeof error?.name === "string" ? error.name : "Error",
68
+ });
69
+ throw error;
70
+ }
57
71
  if (typeof token !== "string" || token.length === 0) {
72
+ logger.error("Mail API access token provider returned an invalid token", {
73
+ method,
74
+ durationMs: Date.now() - startedAt,
75
+ });
58
76
  throw new TypeError("getAccessToken must return a non-empty bearer token");
59
77
  }
60
78
 
@@ -72,12 +90,15 @@ export function createTransport({
72
90
  const signal = options.signal
73
91
  ? AbortSignal.any([options.signal, timeoutSignal])
74
92
  : timeoutSignal;
75
- const method = String(options.method ?? "GET").toUpperCase();
76
93
  let response;
77
94
  try {
78
95
  response = await fetchImpl(url, { ...options, method, headers, body: requestBody, signal });
79
96
  } catch (error) {
80
- logger.error("Mail API request failed", { method, errorName: error?.name ?? "Error" });
97
+ logger.error("Mail API request failed", {
98
+ method,
99
+ durationMs: Date.now() - startedAt,
100
+ errorName: typeof error?.name === "string" ? error.name : "Error",
101
+ });
81
102
  throw error;
82
103
  }
83
104
  if (!response.ok) {
@@ -89,6 +110,7 @@ export function createTransport({
89
110
  logger.warn("Mail API request failed", {
90
111
  method,
91
112
  status: error.status,
113
+ durationMs: Date.now() - startedAt,
92
114
  code: error.code,
93
115
  requestId: error.requestId,
94
116
  });
@@ -97,6 +119,7 @@ export function createTransport({
97
119
  logger.debug("Mail API request completed", {
98
120
  method,
99
121
  status: response.status,
122
+ durationMs: Date.now() - startedAt,
100
123
  requestId: response.headers.get("x-request-id"),
101
124
  });
102
125
  return response;
@@ -7,6 +7,7 @@ export function validateEventOptions({
7
7
  onError,
8
8
  consumerId,
9
9
  acknowledgeEvent,
10
+ logger,
10
11
  retryDelayMs,
11
12
  maxReconnectDelayMs,
12
13
  after,
@@ -17,6 +18,14 @@ export function validateEventOptions({
17
18
  throw new TypeError("WebSocketImpl must be a constructor");
18
19
  if (typeof onEvent !== "function") throw new TypeError("onEvent must be a function");
19
20
  if (typeof onError !== "function") throw new TypeError("onError must be a function");
21
+ if (
22
+ logger !== undefined &&
23
+ (typeof logger?.debug !== "function" ||
24
+ typeof logger?.warn !== "function" ||
25
+ typeof logger?.error !== "function")
26
+ ) {
27
+ throw new TypeError("logger must provide debug, warn, and error methods");
28
+ }
20
29
  if (consumerId !== undefined && (typeof consumerId !== "string" || consumerId.length === 0)) {
21
30
  throw new TypeError("consumerId must be a non-empty string");
22
31
  }