@eliware/mail-client 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +48 -0
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/RELEASE_NOTES.md +12 -0
- package/docs/README.md +8 -0
- package/docs/api.md +183 -0
- package/docs/usage.md +171 -0
- package/examples/README.md +15 -0
- package/examples/basic.mjs +9 -0
- package/examples/mail-client-smoke.mjs +69 -0
- package/package.json +110 -4
- package/specs/README.md +3 -0
- package/specs/directives.yaml +76 -0
- package/src/index.browser.mjs +2 -0
- package/src/index.d.ts +171 -0
- package/src/index.mjs +8 -0
- package/src/mail/api/error.mjs +11 -0
- package/src/mail/api/methods.mjs +145 -0
- package/src/mail/client.mjs +21 -0
- package/src/mail/event-connection.mjs +148 -0
- package/src/mail/transport/base-url.mjs +13 -0
- package/src/mail/transport.mjs +110 -0
- package/src/mail/websocket/address.mjs +6 -0
- package/src/mail/websocket/cursor.mjs +7 -0
- package/src/mail/websocket/frames.mjs +7 -0
- package/src/mail/websocket/listeners.mjs +11 -0
- package/src/mail/websocket/options.mjs +35 -0
- package/src/mail/websocket/session.mjs +49 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# AGENTS.md
|
|
2
|
+
|
|
3
|
+
## Project
|
|
4
|
+
|
|
5
|
+
Build the shared mail-server API client library for Eliware.
|
|
6
|
+
|
|
7
|
+
## Scope and boundaries
|
|
8
|
+
|
|
9
|
+
Use specs/directives.yaml for repository scope and limits.
|
|
10
|
+
|
|
11
|
+
## Layout
|
|
12
|
+
|
|
13
|
+
Use README.md and specs/README.md to find maintained files.
|
|
14
|
+
|
|
15
|
+
## Development
|
|
16
|
+
|
|
17
|
+
Give each source and test module one cohesive purpose.
|
|
18
|
+
|
|
19
|
+
## Validation
|
|
20
|
+
|
|
21
|
+
Use Node.js 26 or later and native ESM for maintained JavaScript modules.
|
|
22
|
+
Run npm test for aggregate validation.
|
|
23
|
+
Run npm run lint for lint checks.
|
|
24
|
+
Run npm run audit for dependency checks.
|
|
25
|
+
Run npm run format to format files.
|
|
26
|
+
Run npm run format:check to check formatting.
|
|
27
|
+
|
|
28
|
+
Run npm run typecheck to check the TypeScript declaration.
|
|
29
|
+
|
|
30
|
+
## Security
|
|
31
|
+
|
|
32
|
+
Keep credentials, secret values, private data, and runtime state out of Git.
|
|
33
|
+
|
|
34
|
+
## Changes
|
|
35
|
+
|
|
36
|
+
Keep each document in the repository that owns its content.
|
|
37
|
+
|
|
38
|
+
## Library
|
|
39
|
+
|
|
40
|
+
Run focused tests first during development.
|
|
41
|
+
Run one test file with `npm test -- tests/path/to/example.test.mjs`.
|
|
42
|
+
Run multiple test files with `npm test -- tests/path/to/first.test.mjs tests/path/to/second.test.mjs`.
|
|
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
|
|
47
|
+
|
|
48
|
+
Run `npm run pack` to check package contents. Follow approved release steps before publication.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eliware
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,101 @@
|
|
|
1
|
-
#
|
|
1
|
+
# [](https://discord.gg/M6aTR9eTwN)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## @eliware/mail-client [](https://www.npmjs.com/package/@eliware/mail-client) [](https://github.com/eliware/mail-client/blob/main/LICENSE) [](https://github.com/eliware/mail-client/actions/workflows/ci.yaml)
|
|
4
|
+
|
|
5
|
+
Mail client library for the Eliware mail platform.
|
|
6
|
+
|
|
7
|
+
## Table of Contents
|
|
8
|
+
|
|
9
|
+
- [Features](#features)
|
|
10
|
+
- [Requirements](#requirements)
|
|
11
|
+
- [Setup](#setup)
|
|
12
|
+
- [Usage](#usage)
|
|
13
|
+
- [Development](#development)
|
|
14
|
+
- [Testing](#testing)
|
|
15
|
+
- [Troubleshooting](#troubleshooting)
|
|
16
|
+
- [Security](#security)
|
|
17
|
+
- [API](#api)
|
|
18
|
+
- [Packaging](#packaging)
|
|
19
|
+
- [Examples](#examples)
|
|
20
|
+
- [Support](#support)
|
|
21
|
+
- [Links](#links)
|
|
22
|
+
- [License](#license)
|
|
23
|
+
|
|
24
|
+
## Features
|
|
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.
|
|
28
|
+
|
|
29
|
+
## Requirements
|
|
30
|
+
|
|
31
|
+
Use Node.js 26 or later. Browser applications require Fetch, Headers, AbortSignal, and URL APIs.
|
|
32
|
+
|
|
33
|
+
## Setup
|
|
34
|
+
|
|
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.
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
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.
|
|
43
|
+
|
|
44
|
+
## Development
|
|
45
|
+
|
|
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.
|
|
49
|
+
|
|
50
|
+
## Testing
|
|
51
|
+
|
|
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.
|
|
56
|
+
|
|
57
|
+
## Troubleshooting
|
|
58
|
+
|
|
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.
|
|
61
|
+
|
|
62
|
+
## Security
|
|
63
|
+
|
|
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.
|
|
67
|
+
|
|
68
|
+
## API
|
|
69
|
+
|
|
70
|
+
Read the [API reference](docs/api.md) for client options, methods, events, logging, and errors.
|
|
71
|
+
|
|
72
|
+
## Packaging
|
|
73
|
+
|
|
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.
|
|
77
|
+
|
|
78
|
+
## Examples
|
|
79
|
+
|
|
80
|
+
Read [examples/README.md](examples/README.md) for prerequisites, commands, and expected output.
|
|
81
|
+
|
|
82
|
+
## Support
|
|
83
|
+
|
|
84
|
+
For help, questions, or to chat with the author and community, visit:
|
|
85
|
+
|
|
86
|
+
[](https://discord.gg/M6aTR9eTwN)[](https://discord.gg/M6aTR9eTwN)
|
|
87
|
+
|
|
88
|
+
**[eliware.org on Discord](https://discord.gg/M6aTR9eTwN)**
|
|
89
|
+
|
|
90
|
+
## Links
|
|
91
|
+
|
|
92
|
+
- [Home Page](https://eliware.org)
|
|
93
|
+
- [GitHub Org](https://github.com/eliware)
|
|
94
|
+
- [GitHub Repo](https://github.com/eliware/mail-client)
|
|
95
|
+
- [Bug Reports](https://github.com/eliware/mail-client/issues)
|
|
96
|
+
- [npm](https://www.npmjs.com/package/@eliware/mail-client)
|
|
97
|
+
- [Discord](https://discord.gg/M6aTR9eTwN)
|
|
98
|
+
|
|
99
|
+
## License
|
|
100
|
+
|
|
101
|
+
[MIT © Eliware](LICENSE)
|
package/RELEASE_NOTES.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Release Notes
|
|
2
|
+
|
|
3
|
+
## 15.0.1 — 2026-10-29
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Add an authenticated HTTP client for the mail-server API.
|
|
8
|
+
- Add methods for message lists, domains, lookups, sends, attachments, and event cursors.
|
|
9
|
+
- Add WebSocket authentication, event handling, replay cursors, and reconnect support.
|
|
10
|
+
- Add Node.js structured logging through `@eliware/log` and a browser-safe entry.
|
|
11
|
+
- Add TypeScript declarations, API documentation, tests, and a local smoke check.
|
|
12
|
+
- Keep OAuth sign-in and consumer migrations outside this package.
|
package/docs/README.md
ADDED
package/docs/api.md
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# API reference
|
|
2
|
+
|
|
3
|
+
The package root exports `createMailClient` and `MailApiError`. The TypeScript declarations live in the package and describe these exports.
|
|
4
|
+
|
|
5
|
+
## Create a client
|
|
6
|
+
|
|
7
|
+
Call `createMailClient(options)` to create an HTTP and WebSocket client.
|
|
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. |
|
|
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.
|
|
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.
|
|
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.
|
|
23
|
+
|
|
24
|
+
## HTTP request methods
|
|
25
|
+
|
|
26
|
+
### `request(path, options)`
|
|
27
|
+
|
|
28
|
+
Send an authenticated HTTP request and receive its native `Response`.
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
const response = await mail.request("/api/status");
|
|
32
|
+
const envelope = await response.json();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The client sets `Accept: application/json` and `Authorization: Bearer <token>`. It uppercases the HTTP method. It serializes plain object bodies as JSON and sets the JSON content type when needed. It passes these body types through unchanged: strings, `FormData`, `Blob`, `URLSearchParams`, and byte arrays.
|
|
36
|
+
|
|
37
|
+
The client throws `MailApiError` for every non-2xx response. Use the native response from a 2xx call for binary data, streaming, and headers.
|
|
38
|
+
|
|
39
|
+
### `requestJson(path, options)`
|
|
40
|
+
|
|
41
|
+
Send an authenticated HTTP request and return the parsed JSON body. The method does not unwrap the server envelope.
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
const envelope = await mail.requestJson("/api/status");
|
|
45
|
+
console.log(envelope.data, envelope.request_id);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Use `request()` when a route returns a body that is not JSON. Use `requestJson()` only when the route returns JSON.
|
|
49
|
+
|
|
50
|
+
## JSON response shape
|
|
51
|
+
|
|
52
|
+
A 2xx JSON route returns the mail-server envelope:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{
|
|
56
|
+
"data": {},
|
|
57
|
+
"request_id": "request-id"
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The client keeps the envelope unchanged. Common data fields include `messages` for message lists, `results` for query results, and `readiness.ready` for status. Read the route response for its complete data shape.
|
|
62
|
+
|
|
63
|
+
## API methods
|
|
64
|
+
|
|
65
|
+
All methods in this table return the complete JSON envelope, except `attachments.download()`, which returns a native `Response`.
|
|
66
|
+
|
|
67
|
+
| Method | Route | Notes |
|
|
68
|
+
| ----------------------------------------- | -------------------------------------- | ------------------------------------------------------------ |
|
|
69
|
+
| `auth.requestBrowserToken()` | `POST /api/auth/token` | Requests a short-lived browser token. |
|
|
70
|
+
| `status()` | `GET /api/status` | Returns API and dependency state. |
|
|
71
|
+
| `inbox.list(filters)` | `GET /api/inbox` | Lists inbound messages. |
|
|
72
|
+
| `messages.list(filters)` | `GET /api/messages` | Lists messages. |
|
|
73
|
+
| `messages.unreadCount()` | `GET /api/messages/unread-count` | Returns the unread count. |
|
|
74
|
+
| `messages.get(id)` | `GET /api/messages/{id}` | Reads a message and attachment metadata. |
|
|
75
|
+
| `messages.headers(id)` | `GET /api/messages/{id}/headers` | Reads message headers. |
|
|
76
|
+
| `messages.thread(id)` | `GET /api/messages/{id}/thread` | Reads the message conversation. |
|
|
77
|
+
| `messages.update(id, changes)` | `PATCH /api/messages/{id}` | Changes only the supplied message fields. |
|
|
78
|
+
| `messages.delete(id)` | `DELETE /api/messages/{id}` | Deletes a message. |
|
|
79
|
+
| `messages.saveDiscordLink(id, link)` | `PUT /api/messages/{id}/discord-links` | Saves an inbound message link. |
|
|
80
|
+
| `search(query)` | `GET /api/search?q={query}` | Finds matching inbound and sent messages. |
|
|
81
|
+
| `sent.list(filters)` | `GET /api/sent` | Lists sent messages. |
|
|
82
|
+
| `sent.get(id)` | `GET /api/sent/{id}` | Reads a sent message, attachments, deliveries, and attempts. |
|
|
83
|
+
| `sent.status(id)` | `GET /api/sent/{id}/status` | Reads status, deliveries, and attempts. |
|
|
84
|
+
| `sent.retry(id)` | `POST /api/sent/{id}/retry` | Retries eligible sends. |
|
|
85
|
+
| `sent.cancel(id)` | `POST /api/sent/{id}/cancel` | Cancels eligible sends. |
|
|
86
|
+
| `sent.retryUncertain(id, options)` | `POST /api/sent/{id}/retry-uncertain` | Requires duplicate-risk confirmation. |
|
|
87
|
+
| `sent.delete(id)` | `DELETE /api/sent/{id}` | Deletes a sent message record. |
|
|
88
|
+
| `sent.saveDiscordLink(id, link)` | `PUT /api/sent/{id}/discord-links` | Saves a sent message link. |
|
|
89
|
+
| `discordLinks.find(channelId, messageId)` | `GET /api/discord-links` | Finds a mail record by its Discord link. |
|
|
90
|
+
| `domains.list()` | `GET /api/domains` | Lists managed domains. |
|
|
91
|
+
| `domains.create(domain)` | `POST /api/domains` | Adds a managed domain. |
|
|
92
|
+
| `domains.delete(domain)` | `DELETE /api/domains/{domain}` | Removes a managed domain. |
|
|
93
|
+
| `send(message)` | `POST /api/send` | Queues a JSON send request. |
|
|
94
|
+
| `sendMultipart(formData)` | `POST /api/send-multipart` | Queues a multipart send request. |
|
|
95
|
+
| `attachments.download(id)` | `GET /api/attachments/{id}` | Returns attachment bytes and response headers. |
|
|
96
|
+
| `events.read(options)` | `GET /api/events` | Reads event records after an optional cursor. |
|
|
97
|
+
| `events.acknowledge(consumerId, cursor)` | `POST /api/events/ack` | Saves a durable consumer cursor. |
|
|
98
|
+
|
|
99
|
+
Pass a non-empty ID to methods that read or change one item. The client converts path IDs to strings and URL-encodes them.
|
|
100
|
+
|
|
101
|
+
Pass `discordChannelId` and `discordMessageId` as decimal Discord Snowflake strings to each `saveDiscordLink()` method. The client rejects zero, non-decimal, and out-of-range IDs before it sends a request. A save method returns `data.message_id` or `data.outbound_id`, plus the Discord links in `data.discord_links`. The `discordLinks.find()` method returns `data.mail_kind` and `data.mail_id`. These methods preserve standard `MailApiError` failures.
|
|
102
|
+
|
|
103
|
+
## List filters
|
|
104
|
+
|
|
105
|
+
Pass filter objects to `inbox.list()`, `messages.list()`, `sent.list()`, and `events.read()`. The client omits `null` and `undefined` values. It encodes array values as repeated query parameters.
|
|
106
|
+
|
|
107
|
+
Inbound routes accept filters such as `limit`, `before`, `after`, `query`, `folder`, `domain`, `address`, `from`, and `to`. Sent routes accept `limit`, `before`, `after`, `query`, `from`, and `to`. Mail-server validates, caps, or ignores filters according to its API contract.
|
|
108
|
+
|
|
109
|
+
`events.read()` returns `data.events`, `data.next_cursor`, and `data.has_more`. It maps `consumerId` to the `consumer_id` query parameter. It rejects calls that include both `after` and `consumerId`.
|
|
110
|
+
|
|
111
|
+
The event acknowledgement method maps `consumerId` to `consumer_id` in its JSON body. Pass a stable consumer ID and a decimal cursor string.
|
|
112
|
+
|
|
113
|
+
## Send data
|
|
114
|
+
|
|
115
|
+
Pass a JSON object to `send()`. Common fields include `from`, `to`, `cc`, `bcc`, `subject`, `body`, `html`, `attachments`, `idempotencyKey`, `replyToMessageId`, `replyMode`, and `forwardMessageId`.
|
|
116
|
+
|
|
117
|
+
Use `replyMode` values `reply`, `reply-all`, or `forward` with the matching source-message field. Mail-server decides which send actions the caller may use and which sender addresses it accepts.
|
|
118
|
+
|
|
119
|
+
The library does not retry any request. Include a stable idempotency key when the application retries a send after an uncertain network result. `sent.retryUncertain()` also requires `{ deliveryId, confirmDuplicateRisk: true }`.
|
|
120
|
+
|
|
121
|
+
For file uploads, create a native `FormData` object and call `sendMultipart(formData)`. Append fields accepted by the mail-server multipart route. Do not set the multipart content type manually.
|
|
122
|
+
|
|
123
|
+
## Attachments
|
|
124
|
+
|
|
125
|
+
Call `attachments.download(id)` to receive a `Response`. Use `response.body` to process large files as a stream. Use `response.arrayBuffer()` for a complete in-memory byte buffer. Read the response headers for metadata supplied by mail-server.
|
|
126
|
+
|
|
127
|
+
## Errors
|
|
128
|
+
|
|
129
|
+
`MailApiError` extends `Error` and represents a non-success HTTP response. It exposes these properties:
|
|
130
|
+
|
|
131
|
+
| Property | Description |
|
|
132
|
+
| ----------- | ----------------------------------------------------------------- |
|
|
133
|
+
| `status` | HTTP response status. |
|
|
134
|
+
| `code` | API error code or `MAIL_API_ERROR` when no code exists. |
|
|
135
|
+
| `requestId` | Request ID from the error envelope or `x-request-id` header. |
|
|
136
|
+
| `payload` | Parsed JSON, response text, or `null` if the body cannot be read. |
|
|
137
|
+
|
|
138
|
+
The error message uses the API error message when available. Network errors and token-provider errors pass through without conversion to `MailApiError`. Timeouts and caller cancellations use the platform error types.
|
|
139
|
+
|
|
140
|
+
## WebSocket event methods
|
|
141
|
+
|
|
142
|
+
### `connectEvents(options)`
|
|
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.
|
|
145
|
+
|
|
146
|
+
After the socket opens, the client sends this JSON frame as its first message:
|
|
147
|
+
|
|
148
|
+
```json
|
|
149
|
+
{ "type": "authenticate", "token": "<bearer-token>" }
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
The client waits for this server frame before it delivers events:
|
|
153
|
+
|
|
154
|
+
```json
|
|
155
|
+
{ "type": "authenticated" }
|
|
156
|
+
```
|
|
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
|
+
| `after` | Live edge | Starts event replay after a decimal cursor. |
|
|
163
|
+
| `consumerId` | None | Enables server-side cursor acknowledgements. |
|
|
164
|
+
| `autoReconnect` | `true` | Reconnects after unexpected closure. |
|
|
165
|
+
| `retryDelayMs` | `500` | Sets the first reconnect wait interval. |
|
|
166
|
+
| `maxReconnectDelayMs` | `30000` | Sets the longest reconnect wait interval. |
|
|
167
|
+
| `WebSocketImpl` | Client option | Overrides the WebSocket constructor for this connection. |
|
|
168
|
+
|
|
169
|
+
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.
|
|
170
|
+
|
|
171
|
+
The server accepts cursors from `0` through the maximum Snowflake ID. It requires decimal strings without leading zeroes, except for `0` itself.
|
|
172
|
+
|
|
173
|
+
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.
|
|
174
|
+
|
|
175
|
+
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.
|
|
176
|
+
|
|
177
|
+
The event has `event_id`, `cursor`, `event_type`, `occurred_at`, and `payload` fields. Event payloads signal that data changed. Read complete message data through HTTP methods.
|
|
178
|
+
|
|
179
|
+
## Runtime logging
|
|
180
|
+
|
|
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
|
+
|
|
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.
|
package/docs/usage.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# Usage guide
|
|
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.
|
|
4
|
+
|
|
5
|
+
## Install the package
|
|
6
|
+
|
|
7
|
+
After the npm release, install the package in the application that calls mail-server:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @eliware/mail-client
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Node.js requires Fetch, Headers, AbortSignal, URL, and WebSocket APIs. Node.js 26 provides these APIs. Browser applications require these same APIs.
|
|
14
|
+
|
|
15
|
+
## Credentials
|
|
16
|
+
|
|
17
|
+
Use a long-lived API token in trusted Node.js applications. Keep a different token for each application or CLI installation. Store server tokens in Kubernetes secrets or a separate secret store.
|
|
18
|
+
|
|
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
|
+
|
|
21
|
+
EliD sign-in belongs to mail-web. This package does not run OAuth flows and does not depend on `@eliware/elid-client`.
|
|
22
|
+
|
|
23
|
+
## Create a Node.js client
|
|
24
|
+
|
|
25
|
+
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
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { createMailClient } from "@eliware/mail-client";
|
|
29
|
+
|
|
30
|
+
const mail = createMailClient({
|
|
31
|
+
baseUrl: process.env.MAIL_API_URL,
|
|
32
|
+
getAccessToken: () => process.env.MAIL_API_TOKEN,
|
|
33
|
+
timeoutMs: 30_000,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const inbox = await mail.inbox.list({ limit: 20 });
|
|
37
|
+
console.log(inbox.data.messages);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Give each mail-cli installation its own token. Use a separate token for mail-discord. Keep both tokens on the server.
|
|
41
|
+
|
|
42
|
+
## Give mail-web a browser token
|
|
43
|
+
|
|
44
|
+
Create a server-side client with the `MAIL_WEB_API_TOKEN` value. Call the token method after the user signs in to mail-web. Return only the short-lived token and its expiry to browser code.
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
const mailServer = createMailClient({
|
|
48
|
+
baseUrl: process.env.MAIL_API_URL,
|
|
49
|
+
getAccessToken: () => process.env.MAIL_WEB_API_TOKEN,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const tokenResponse = await mailServer.auth.requestBrowserToken();
|
|
53
|
+
const token = tokenResponse.data.access_token;
|
|
54
|
+
const expiresIn = tokenResponse.data.expires_in;
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Keep the browser token in memory. Do not put the long-lived server token in browser code. Do not store the browser token in browser storage.
|
|
58
|
+
|
|
59
|
+
Create a browser client with a token provider that returns the current short-lived token:
|
|
60
|
+
|
|
61
|
+
```js
|
|
62
|
+
const browserMail = createMailClient({
|
|
63
|
+
baseUrl: "https://mail.example.test",
|
|
64
|
+
getAccessToken: () => session.getMailAccessToken(),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const inbox = await browserMail.inbox.list({ limit: 20 });
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The browser calls mail-server directly. Configure mail-server to allow the mail-web site address in `MAIL_ALLOWED_ORIGINS`. The browser sends its site address with cross-origin HTTP and WebSocket requests.
|
|
71
|
+
|
|
72
|
+
Refresh a browser token before it expires. The client asks the token provider for a token before each HTTP call and each WebSocket reconnect. The host application handles sign-in, token refresh, and session storage.
|
|
73
|
+
|
|
74
|
+
## Read and change mail
|
|
75
|
+
|
|
76
|
+
Use named methods for common routes. JSON methods return the complete server envelope.
|
|
77
|
+
|
|
78
|
+
```js
|
|
79
|
+
const message = await mail.messages.get("123456789");
|
|
80
|
+
await mail.messages.update("123456789", { read: true });
|
|
81
|
+
const results = await mail.search("invoice");
|
|
82
|
+
const sent = await mail.send({
|
|
83
|
+
to: "eli@example.test",
|
|
84
|
+
subject: "Hello",
|
|
85
|
+
body: "Hi",
|
|
86
|
+
idempotencyKey: "message-request-123",
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Read `message.data` for message data. Keep `request_id` to match a client failure to a server log.
|
|
91
|
+
|
|
92
|
+
Use `sendMultipart(formData)` to send attachments as multipart data. Build a native `FormData` object and append the same fields that mail-server accepts. Let Fetch set the multipart content type and boundary.
|
|
93
|
+
|
|
94
|
+
Use `attachments.download(id)` to receive an attachment as a native `Response`. Read the body as a stream or bytes. Use response headers for the file name, media type, length, checksum, and request ID when the server provides them.
|
|
95
|
+
|
|
96
|
+
Use `request(path, options)` for a different route or a response that is not JSON. Use `requestJson(path, options)` for an unmodified JSON response. The client does not retry requests. Add an idempotency key to send data when the application requires safe retries.
|
|
97
|
+
|
|
98
|
+
## Receive mail events
|
|
99
|
+
|
|
100
|
+
Call `connectEvents()` with an event handler. The client opens `/ws`, sends the bearer token in the first JSON frame, and waits for the server acknowledgement before it delivers events.
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
const events = browserMail.connectEvents({
|
|
104
|
+
onEvent: async (event) => {
|
|
105
|
+
if (event.event_type === "message.created") {
|
|
106
|
+
const message = await browserMail.messages.get(event.payload.message_id);
|
|
107
|
+
renderMessage(message.data);
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
onError: (error) => logger.error("Mail event connection failed", { error }),
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
await events.ready;
|
|
114
|
+
```
|
|
115
|
+
|
|
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.
|
|
117
|
+
|
|
118
|
+
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
|
+
|
|
120
|
+
## Process durable events
|
|
121
|
+
|
|
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.
|
|
123
|
+
|
|
124
|
+
```js
|
|
125
|
+
const events = browserMail.connectEvents({
|
|
126
|
+
consumerId: "mail-discord-production",
|
|
127
|
+
after: savedCursor,
|
|
128
|
+
onEvent: handleEvent,
|
|
129
|
+
onError: reportEventError,
|
|
130
|
+
});
|
|
131
|
+
```
|
|
132
|
+
|
|
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.
|
|
134
|
+
|
|
135
|
+
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
|
+
|
|
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.
|
|
138
|
+
|
|
139
|
+
## Report errors
|
|
140
|
+
|
|
141
|
+
The client throws `MailApiError` for every non-success HTTP response. The error exposes `status`, `code`, `requestId`, and `payload`. The request ID comes from the error envelope or the `x-request-id` response header.
|
|
142
|
+
|
|
143
|
+
The `payload` field contains the parsed JSON error body, plain response text, or `null` when the response body cannot be read. Network errors and token-provider errors pass through from their source. A timeout uses the platform `TimeoutError`. A caller abort uses the platform `AbortError`.
|
|
144
|
+
|
|
145
|
+
Use `onError` for WebSocket, event-handler, and event-acknowledgement failures. Catch those failures in the host application when it needs to show status or retry work.
|
|
146
|
+
|
|
147
|
+
## Configure logging
|
|
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.
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
const mail = createMailClient({
|
|
153
|
+
baseUrl: process.env.MAIL_API_URL,
|
|
154
|
+
getAccessToken: () => process.env.MAIL_API_TOKEN,
|
|
155
|
+
logger: applicationLogger,
|
|
156
|
+
});
|
|
157
|
+
```
|
|
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.
|
|
160
|
+
|
|
161
|
+
## Validate a checkout
|
|
162
|
+
|
|
163
|
+
Run these commands from the package root:
|
|
164
|
+
|
|
165
|
+
```sh
|
|
166
|
+
npm ci
|
|
167
|
+
npm test
|
|
168
|
+
npm run typecheck
|
|
169
|
+
npm run smoke
|
|
170
|
+
npm run pack
|
|
171
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Examples
|
|
2
|
+
|
|
3
|
+
The [basic example](basic.mjs) sends an authenticated request to the mail API status route.
|
|
4
|
+
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
Use Node.js 26 or later. Set `MAIL_API_URL` and `MAIL_API_TOKEN` in the local environment. Do not commit credentials.
|
|
8
|
+
|
|
9
|
+
## Command
|
|
10
|
+
|
|
11
|
+
Run `node examples/basic.mjs` from the repository root.
|
|
12
|
+
|
|
13
|
+
## Expected result
|
|
14
|
+
|
|
15
|
+
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.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createMailClient } from "../src/index.mjs";
|
|
2
|
+
|
|
3
|
+
const mail = createMailClient({
|
|
4
|
+
baseUrl: process.env.MAIL_API_URL ?? "https://mail.example.test",
|
|
5
|
+
getAccessToken: () => process.env.MAIL_API_TOKEN ?? "replace-with-a-local-token",
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
const response = await mail.request("/api/status");
|
|
9
|
+
console.log(await response.json());
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { createMailClient } from "../src/index.browser.mjs";
|
|
4
|
+
|
|
5
|
+
class SmokeSocket {
|
|
6
|
+
static current;
|
|
7
|
+
constructor(url) {
|
|
8
|
+
this.url = url;
|
|
9
|
+
this.listeners = new Map();
|
|
10
|
+
this.sent = [];
|
|
11
|
+
SmokeSocket.current = this;
|
|
12
|
+
queueMicrotask(() => this.emit("open"));
|
|
13
|
+
}
|
|
14
|
+
addEventListener(name, callback) {
|
|
15
|
+
this.listeners.set(name, callback);
|
|
16
|
+
}
|
|
17
|
+
send(frame) {
|
|
18
|
+
this.sent.push(frame);
|
|
19
|
+
queueMicrotask(() => {
|
|
20
|
+
this.emit("message", { data: JSON.stringify({ type: "authenticated" }) });
|
|
21
|
+
this.emit("message", {
|
|
22
|
+
data: JSON.stringify({ event_id: "123", cursor: "123", event_type: "message.created" }),
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
close() {}
|
|
27
|
+
emit(name, value) {
|
|
28
|
+
this.listeners.get(name)?.(value);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const server = createServer(async (request, response) => {
|
|
33
|
+
assert.equal(request.headers.authorization, "Bearer temporary-token");
|
|
34
|
+
if (request.url === "/api/auth/token") {
|
|
35
|
+
response.end(
|
|
36
|
+
JSON.stringify({ data: { access_token: "temporary-token" }, request_id: "smoke-1" }),
|
|
37
|
+
);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
response.end(JSON.stringify({ data: { ok: true }, request_id: "smoke-2" }));
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
44
|
+
try {
|
|
45
|
+
const { port } = server.address();
|
|
46
|
+
const client = createMailClient({
|
|
47
|
+
baseUrl: `http://127.0.0.1:${port}`,
|
|
48
|
+
getAccessToken: () => "temporary-token",
|
|
49
|
+
WebSocketImpl: SmokeSocket,
|
|
50
|
+
});
|
|
51
|
+
const token = await client.auth.requestBrowserToken();
|
|
52
|
+
assert.equal(token.data.access_token, "temporary-token");
|
|
53
|
+
const status = await client.status();
|
|
54
|
+
assert.equal(status.data.ok, true);
|
|
55
|
+
const seen = [];
|
|
56
|
+
const events = client.connectEvents({ onEvent: (event) => seen.push(event.event_id) });
|
|
57
|
+
await events.ready;
|
|
58
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
59
|
+
assert.deepEqual(seen, ["123"]);
|
|
60
|
+
const authFrame = JSON.parse(SmokeSocket.current.sent[0]);
|
|
61
|
+
assert.equal(authFrame.type, "authenticate");
|
|
62
|
+
assert.equal(typeof authFrame.token, "string");
|
|
63
|
+
events.close();
|
|
64
|
+
process.stdout.write("mail-client smoke check passed\n");
|
|
65
|
+
} finally {
|
|
66
|
+
await new Promise((resolve, reject) =>
|
|
67
|
+
server.close((error) => (error ? reject(error) : resolve())),
|
|
68
|
+
);
|
|
69
|
+
}
|