@eliware/mail-client 0.0.0-stage → 15.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/package.json CHANGED
@@ -1,6 +1,112 @@
1
1
  {
2
2
  "name": "@eliware/mail-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "15.0.1",
4
+ "type": "module",
5
+ "description": "Mail client library for the Eliware mail platform.",
6
+ "keywords": [
7
+ "mail",
8
+ "email",
9
+ "client",
10
+ "library",
11
+ "api"
12
+ ],
13
+ "private": false,
14
+ "publishConfig": {
15
+ "access": "public",
16
+ "provenance": true
17
+ },
18
+ "main": "./src/index.mjs",
19
+ "files": [
20
+ "src/",
21
+ "docs/",
22
+ "README.md",
23
+ "AGENTS.md",
24
+ "LICENSE",
25
+ "RELEASE_NOTES.md",
26
+ "examples/",
27
+ "specs/",
28
+ "package.json"
29
+ ],
30
+ "scripts": {
31
+ "test": "eliware-test",
32
+ "smoke": "node examples/mail-client-smoke.mjs",
33
+ "lint": "eliware-test --lint",
34
+ "audit": "eliware-test --audit",
35
+ "format": "eliware-test --format",
36
+ "format:check": "eliware-test --format-check",
37
+ "typecheck": "tsc --project tsconfig.json",
38
+ "pack": "eliware-test --pack"
39
+ },
40
+ "engines": {
41
+ "node": ">=26"
42
+ },
43
+ "dependencies": {
44
+ "@eliware/log": "^15.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "@eliware/test": "^15.0.1",
48
+ "typescript": "^7.0.2"
49
+ },
50
+ "jest": {
51
+ "testEnvironment": "node",
52
+ "testMatch": [
53
+ "**/tests/**/*.test.mjs"
54
+ ],
55
+ "collectCoverageFrom": [
56
+ "src/**/*.mjs"
57
+ ],
58
+ "coverageReporters": [
59
+ "text",
60
+ "json-summary"
61
+ ],
62
+ "coverageThreshold": {
63
+ "global": {
64
+ "branches": 100,
65
+ "functions": 100,
66
+ "lines": 100,
67
+ "statements": 100
68
+ }
69
+ }
70
+ },
71
+ "prettier": {
72
+ "printWidth": 100,
73
+ "tabWidth": 2,
74
+ "useTabs": false,
75
+ "semi": true,
76
+ "singleQuote": false,
77
+ "quoteProps": "as-needed",
78
+ "jsxSingleQuote": false,
79
+ "trailingComma": "all",
80
+ "bracketSpacing": true,
81
+ "bracketSameLine": false,
82
+ "arrowParens": "always",
83
+ "proseWrap": "preserve",
84
+ "endOfLine": "lf"
85
+ },
86
+ "author": "Eliware <eliware@eliware.org>",
87
+ "license": "MIT",
88
+ "repository": {
89
+ "type": "git",
90
+ "url": "git+https://github.com/eliware/mail-client.git"
91
+ },
92
+ "homepage": "https://github.com/eliware/mail-client#readme",
93
+ "bugs": {
94
+ "url": "https://github.com/eliware/mail-client/issues"
95
+ },
96
+ "eliware": {
97
+ "id": "E-1361",
98
+ "apply": [
99
+ "general",
100
+ "library",
101
+ "npm-published"
102
+ ]
103
+ },
104
+ "types": "./src/index.d.ts",
105
+ "exports": {
106
+ ".": {
107
+ "types": "./src/index.d.ts",
108
+ "browser": "./src/index.browser.mjs",
109
+ "import": "./src/index.mjs"
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,3 @@
1
+ # Specifications
2
+
3
+ - [Repository directives](directives.yaml)
@@ -0,0 +1,76 @@
1
+ version: "15.0"
2
+ description: Requirements for the shared Eliware mail API client library.
3
+ directives:
4
+ - id: E-1361.0
5
+ dos:
6
+ - Provide HTTP API and WebSocket clients for Node.js and browser applications.
7
+ - Publish the native ESM package as `@eliware/mail-client` with TypeScript declarations.
8
+ - Keep API calls, responses, attachments, and events aligned with mail-server contracts.
9
+ - Keep this package focused on mail API calls and client-side event handling.
10
+ - Keep EliD OAuth sign-in in mail-web and its separate identity client.
11
+ - Build and publish this package before any consumer rewrite starts.
12
+ donts:
13
+ - Do not connect to SMTP, MariaDB, RabbitMQ, or shared file storage.
14
+ - Do not depend on `@eliware/elid-client` or run OAuth flows.
15
+ - Do not rewrite mail-cli, mail-discord, or mail-web in this repository.
16
+
17
+ - id: E-1361.1
18
+ dos:
19
+ - Support mail-server routes for reads, searches, updates, sends, deletes, and send actions.
20
+ - Save and find inbound and sent Discord links through authenticated mail-server routes.
21
+ - Preserve API envelopes, request IDs, headers, and attachment metadata.
22
+ - Return typed errors for failed responses and keep available request IDs.
23
+ - Apply request timeouts and accept caller-provided Fetch implementations.
24
+ - Retry send requests only when they include a stable idempotency key.
25
+ - Accept an async token provider so hosts can refresh credentials before requests.
26
+ - Request browser tokens through `POST /api/auth/token` and keep the response envelope.
27
+ donts:
28
+ - Do not reshape API response bodies without documenting the change.
29
+ - Do not retry a send without a stable idempotency key.
30
+
31
+ - id: E-1361.2
32
+ dos:
33
+ - Use separate static API keys for mail-discord and mail-web server deployments.
34
+ - Allow separate long-lived API keys for every mail-cli installation.
35
+ - Store mail-discord and mail-web API keys in Kubernetes secrets.
36
+ - Send host-provided long-lived API tokens as bearer credentials for trusted Node.js clients.
37
+ - Support long-lived tokens for mail-cli HTTP requests without WebSocket access.
38
+ - Support long-lived tokens for mail-discord HTTP and WebSocket access.
39
+ - Support mail-web server requests that get short-lived browser tokens.
40
+ - Return the browser token, token type, and lifetime from the token response.
41
+ - Use short-lived browser tokens for direct browser HTTP requests to mail-server.
42
+ - Use the browser token for HTTP bearer requests and WebSocket authentication.
43
+ - Let browser clients request new short-lived tokens through the host token provider.
44
+ - Keep the mail-web long-lived token on its server and outside browser code.
45
+ - Give Eli full access to every domain and mailbox as the only user.
46
+ donts:
47
+ - Do not expose long-lived API tokens to browser code.
48
+ - Do not add multi-user access rules or per-user mailbox scopes.
49
+ - Do not store browser tokens in durable browser storage.
50
+
51
+ - id: E-1361.3
52
+ dos:
53
+ - Authenticate WebSocket sessions after the browser opens each connection.
54
+ - Send `{"type":"authenticate","token":"..."}` as the first WebSocket message.
55
+ - Wait for `{"type":"authenticated"}` before delivering events to callers.
56
+ - Support different mail-server and mail-web domains without tokens in WebSocket URLs.
57
+ - Reconnect safely and continue events from the last acknowledged cursor.
58
+ - Retry WebSocket setup after token provider failures when automatic reconnect is enabled.
59
+ - Let stable consumer IDs acknowledge processed event cursors through the HTTP API.
60
+ - Move durable cursors only after handlers and server acknowledgements succeed.
61
+ - Tolerate repeated events and refresh current data through the HTTP API after notifications.
62
+ - Let callers process events without RabbitMQ payloads as a client contract.
63
+ donts:
64
+ - Do not put bearer tokens in WebSocket URLs or query strings.
65
+ - Do not mark a WebSocket session authenticated before the server accepts its first message.
66
+ - Do not use event notifications as complete message data.
67
+
68
+ - id: E-1361.4
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.
72
+ - Omit Node-only logging imports from the browser entry.
73
+ - Log request methods, response statuses, error names, and available request IDs.
74
+ donts:
75
+ - Do not log tokens, message bodies, attachment contents, or full request URLs.
76
+ - Do not require logging from browser clients.
@@ -0,0 +1,2 @@
1
+ export { MailApiError } from "./mail/api/error.mjs";
2
+ export { createMailClient } from "./mail/client.mjs";
package/src/index.d.ts ADDED
@@ -0,0 +1,171 @@
1
+ export type QueryValue =
2
+ string | number | boolean | readonly (string | number)[] | null | undefined;
3
+ export type Query = Record<string, QueryValue>;
4
+
5
+ export interface JsonEnvelope<T = unknown> {
6
+ data: T;
7
+ request_id: string;
8
+ }
9
+
10
+ export interface MailLogger {
11
+ debug(message: string, metadata?: Record<string, unknown>): unknown;
12
+ warn(message: string, metadata?: Record<string, unknown>): unknown;
13
+ error(message: string, metadata?: Record<string, unknown>): unknown;
14
+ }
15
+
16
+ export interface WebSocketFactory {
17
+ new (url: string): WebSocket;
18
+ }
19
+
20
+ export interface MailClientOptions {
21
+ baseUrl: string;
22
+ getAccessToken: () => string | Promise<string>;
23
+ fetchImpl?: typeof fetch;
24
+ WebSocketImpl?: WebSocketFactory;
25
+ timeoutMs?: number;
26
+ logger?: MailLogger;
27
+ }
28
+
29
+ export interface MailEvent {
30
+ event_id: string;
31
+ cursor?: string;
32
+ event_type: string;
33
+ occurred_at?: string;
34
+ payload: unknown;
35
+ }
36
+
37
+ export interface EventConnectionOptions {
38
+ after?: string;
39
+ consumerId?: string;
40
+ onEvent(event: MailEvent): void | Promise<void>;
41
+ onError?(error: Error): void;
42
+ autoReconnect?: boolean;
43
+ retryDelayMs?: number;
44
+ maxReconnectDelayMs?: number;
45
+ WebSocketImpl?: WebSocketFactory;
46
+ }
47
+
48
+ export interface EventConnection {
49
+ readonly ready: Promise<void>;
50
+ readonly cursor: string | null;
51
+ close(): void;
52
+ }
53
+
54
+ export interface MailSendRequest {
55
+ from?: string;
56
+ to?: string | string[];
57
+ cc?: string | string[];
58
+ bcc?: string | string[];
59
+ subject?: string;
60
+ body?: string;
61
+ html?: string;
62
+ attachments?: unknown[];
63
+ idempotencyKey?: string;
64
+ replyToMessageId?: string;
65
+ replyMode?: "reply" | "reply-all" | "forward";
66
+ forwardMessageId?: string;
67
+ [field: string]: unknown;
68
+ }
69
+
70
+ export interface DiscordLink {
71
+ discord_channel_id: string;
72
+ discord_message_id: string;
73
+ }
74
+
75
+ export interface DiscordLinkSaveInput {
76
+ discordChannelId: string;
77
+ discordMessageId: string;
78
+ }
79
+
80
+ export interface InboundDiscordLinkSaveResult {
81
+ message_id: string;
82
+ discord_links: DiscordLink[];
83
+ }
84
+
85
+ export interface SentDiscordLinkSaveResult {
86
+ outbound_id: string;
87
+ discord_links: DiscordLink[];
88
+ }
89
+
90
+ export interface DiscordMailLookupResult {
91
+ mail_kind: "inbound" | "sent";
92
+ mail_id: string;
93
+ }
94
+
95
+ export interface MailClient {
96
+ request(path: string, options?: RequestInit): Promise<Response>;
97
+ requestJson<T = unknown>(path: string, options?: RequestInit): Promise<T>;
98
+ auth: {
99
+ requestBrowserToken(): Promise<
100
+ JsonEnvelope<{
101
+ access_token: string;
102
+ token_type: "Bearer";
103
+ expires_in: number;
104
+ }>
105
+ >;
106
+ };
107
+ status(): Promise<JsonEnvelope<unknown>>;
108
+ inbox: { list(filters?: Query): Promise<JsonEnvelope<unknown>> };
109
+ messages: {
110
+ list(filters?: Query): Promise<JsonEnvelope<unknown>>;
111
+ unreadCount(): Promise<JsonEnvelope<unknown>>;
112
+ get(id: string | number): Promise<JsonEnvelope<unknown>>;
113
+ headers(id: string | number): Promise<JsonEnvelope<unknown>>;
114
+ thread(id: string | number): Promise<JsonEnvelope<unknown>>;
115
+ update(id: string | number, changes: Record<string, unknown>): Promise<JsonEnvelope<unknown>>;
116
+ delete(id: string | number): Promise<JsonEnvelope<unknown>>;
117
+ saveDiscordLink(
118
+ id: string | number,
119
+ link: DiscordLinkSaveInput,
120
+ ): Promise<JsonEnvelope<InboundDiscordLinkSaveResult>>;
121
+ };
122
+ search(query: string): Promise<JsonEnvelope<unknown>>;
123
+ sent: {
124
+ list(filters?: Query): Promise<JsonEnvelope<unknown>>;
125
+ get(id: string | number): Promise<JsonEnvelope<unknown>>;
126
+ status(id: string | number): Promise<JsonEnvelope<unknown>>;
127
+ retry(id: string | number): Promise<JsonEnvelope<unknown>>;
128
+ cancel(id: string | number): Promise<JsonEnvelope<unknown>>;
129
+ delete(id: string | number): Promise<JsonEnvelope<unknown>>;
130
+ retryUncertain(
131
+ id: string | number,
132
+ options: { deliveryId: string; confirmDuplicateRisk: true },
133
+ ): Promise<JsonEnvelope<unknown>>;
134
+ saveDiscordLink(
135
+ id: string | number,
136
+ link: DiscordLinkSaveInput,
137
+ ): Promise<JsonEnvelope<SentDiscordLinkSaveResult>>;
138
+ };
139
+ discordLinks: {
140
+ find(
141
+ discordChannelId: string,
142
+ discordMessageId: string,
143
+ ): Promise<JsonEnvelope<DiscordMailLookupResult>>;
144
+ };
145
+ domains: {
146
+ list(): Promise<JsonEnvelope<unknown>>;
147
+ create(domain: string): Promise<JsonEnvelope<unknown>>;
148
+ delete(domain: string): Promise<JsonEnvelope<unknown>>;
149
+ };
150
+ send(message: MailSendRequest): Promise<JsonEnvelope<unknown>>;
151
+ sendMultipart(formData: FormData): Promise<JsonEnvelope<unknown>>;
152
+ attachments: { download(id: string | number): Promise<Response> };
153
+ events: {
154
+ read(options?: {
155
+ after?: string;
156
+ consumerId?: string;
157
+ limit?: number;
158
+ }): Promise<JsonEnvelope<unknown>>;
159
+ acknowledge(consumerId: string, cursor: string): Promise<JsonEnvelope<unknown>>;
160
+ };
161
+ connectEvents(options: EventConnectionOptions): EventConnection;
162
+ }
163
+
164
+ export class MailApiError extends Error {
165
+ readonly status: number;
166
+ readonly code: string;
167
+ readonly requestId: string | null;
168
+ readonly payload: unknown;
169
+ }
170
+
171
+ export function createMailClient(options: MailClientOptions): MailClient;
package/src/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import defaultLogger from "@eliware/log";
2
+ import { createMailClient as createClient } from "./mail/client.mjs";
3
+
4
+ export function createMailClient(options) {
5
+ return createClient({ ...options, logger: options?.logger ?? defaultLogger });
6
+ }
7
+
8
+ export { MailApiError } from "./mail/api/error.mjs";
@@ -0,0 +1,11 @@
1
+ export class MailApiError extends Error {
2
+ constructor(status, payload, headers) {
3
+ const apiError = payload?.error;
4
+ super(apiError?.message ?? `Mail API request failed with HTTP ${status}`);
5
+ this.name = "MailApiError";
6
+ this.status = status;
7
+ this.code = apiError?.code ?? "MAIL_API_ERROR";
8
+ this.requestId = payload?.request_id ?? headers?.get?.("x-request-id") ?? null;
9
+ this.payload = payload;
10
+ }
11
+ }
@@ -0,0 +1,145 @@
1
+ function withQuery(path, values = {}) {
2
+ const query = new URLSearchParams();
3
+ for (const [key, value] of Object.entries(values)) {
4
+ if (value === undefined || value === null) continue;
5
+ if (Array.isArray(value)) {
6
+ for (const item of value) query.append(key, String(item));
7
+ } else {
8
+ query.set(key, String(value));
9
+ }
10
+ }
11
+ const suffix = query.toString();
12
+ return suffix ? `${path}?${suffix}` : path;
13
+ }
14
+
15
+ function itemPath(collection, id, suffix = "") {
16
+ if (id === undefined || id === null || String(id).length === 0) {
17
+ throw new TypeError("id must be a non-empty string or number");
18
+ }
19
+ return `/api/${collection}/${encodeURIComponent(String(id))}${suffix}`;
20
+ }
21
+
22
+ const maxDiscordSnowflake = 18_446_744_073_709_551_615n;
23
+
24
+ function validateDiscordIds(channelId, messageId) {
25
+ for (const [name, value] of [
26
+ ["discordChannelId", channelId],
27
+ ["discordMessageId", messageId],
28
+ ]) {
29
+ if (
30
+ typeof value !== "string" ||
31
+ !/^[1-9]\d{0,19}$/u.test(value) ||
32
+ BigInt(value) > maxDiscordSnowflake
33
+ ) {
34
+ throw new TypeError(`${name} must be a valid Discord Snowflake ID`);
35
+ }
36
+ }
37
+ }
38
+
39
+ export function createApiMethods({ request, requestJson }) {
40
+ const json = (method, path, body) =>
41
+ requestJson(path, { method, ...(body === undefined ? {} : { body }) });
42
+ const messages = {
43
+ list: (filters) => requestJson(withQuery("/api/messages", filters)),
44
+ unreadCount: () => requestJson("/api/messages/unread-count"),
45
+ get: (id) => requestJson(itemPath("messages", id)),
46
+ headers: (id) => requestJson(itemPath("messages", id, "/headers")),
47
+ thread: (id) => requestJson(itemPath("messages", id, "/thread")),
48
+ update: (id, changes) => json("PATCH", itemPath("messages", id), changes),
49
+ delete: (id) => json("DELETE", itemPath("messages", id)),
50
+ saveDiscordLink: (id, { discordChannelId, discordMessageId } = {}) => {
51
+ validateDiscordIds(discordChannelId, discordMessageId);
52
+ return json("PUT", itemPath("messages", id, "/discord-links"), {
53
+ discord_channel_id: discordChannelId,
54
+ discord_message_id: discordMessageId,
55
+ });
56
+ },
57
+ };
58
+ const sent = {
59
+ list: (filters) => requestJson(withQuery("/api/sent", filters)),
60
+ get: (id) => requestJson(itemPath("sent", id)),
61
+ status: (id) => requestJson(itemPath("sent", id, "/status")),
62
+ retry: (id) => json("POST", itemPath("sent", id, "/retry")),
63
+ cancel: (id) => json("POST", itemPath("sent", id, "/cancel")),
64
+ delete: (id) => json("DELETE", itemPath("sent", id)),
65
+ retryUncertain: (id, { deliveryId, confirmDuplicateRisk } = {}) => {
66
+ if (confirmDuplicateRisk !== true) {
67
+ throw new TypeError("confirmDuplicateRisk must be true for uncertain delivery retries");
68
+ }
69
+ if (typeof deliveryId !== "string" || deliveryId.length === 0) {
70
+ throw new TypeError("deliveryId must be a non-empty string");
71
+ }
72
+ return json("POST", itemPath("sent", id, "/retry-uncertain"), {
73
+ delivery_id: deliveryId,
74
+ confirm_duplicate_risk: true,
75
+ });
76
+ },
77
+ saveDiscordLink: (id, { discordChannelId, discordMessageId } = {}) => {
78
+ validateDiscordIds(discordChannelId, discordMessageId);
79
+ return json("PUT", itemPath("sent", id, "/discord-links"), {
80
+ discord_channel_id: discordChannelId,
81
+ discord_message_id: discordMessageId,
82
+ });
83
+ },
84
+ };
85
+ const discordLinks = {
86
+ find: (discordChannelId, discordMessageId) => {
87
+ validateDiscordIds(discordChannelId, discordMessageId);
88
+ return requestJson(
89
+ withQuery("/api/discord-links", {
90
+ discord_channel_id: discordChannelId,
91
+ discord_message_id: discordMessageId,
92
+ }),
93
+ );
94
+ },
95
+ };
96
+ const events = {
97
+ read: ({ after, consumerId, limit } = {}) => {
98
+ if (after != null && consumerId != null) {
99
+ throw new TypeError("after and consumerId cannot be used together");
100
+ }
101
+ return requestJson(
102
+ withQuery("/api/events", {
103
+ after,
104
+ consumer_id: consumerId,
105
+ limit,
106
+ }),
107
+ );
108
+ },
109
+ acknowledge: (consumerId, cursor) => {
110
+ if (typeof consumerId !== "string" || consumerId.length === 0) {
111
+ throw new TypeError("consumerId must be a non-empty string");
112
+ }
113
+ if (typeof cursor !== "string" || cursor.length === 0) {
114
+ throw new TypeError("cursor must be a non-empty string");
115
+ }
116
+ return json("POST", "/api/events/ack", { consumer_id: consumerId, cursor });
117
+ },
118
+ };
119
+
120
+ return {
121
+ request,
122
+ requestJson,
123
+ auth: {
124
+ requestBrowserToken: () => json("POST", "/api/auth/token"),
125
+ },
126
+ status: () => requestJson("/api/status"),
127
+ inbox: { list: (filters) => requestJson(withQuery("/api/inbox", filters)) },
128
+ messages,
129
+ search: (query) => requestJson(withQuery("/api/search", { q: query })),
130
+ sent,
131
+ discordLinks,
132
+ domains: {
133
+ list: () => requestJson("/api/domains"),
134
+ create: (domain) => json("POST", "/api/domains", { domain }),
135
+ delete: (domain) => json("DELETE", itemPath("domains", domain)),
136
+ },
137
+ send: (message) => json("POST", "/api/send", message),
138
+ sendMultipart: (formData) =>
139
+ requestJson("/api/send-multipart", { method: "POST", body: formData }),
140
+ attachments: {
141
+ download: (id) => request(itemPath("attachments", id)),
142
+ },
143
+ events,
144
+ };
145
+ }
@@ -0,0 +1,21 @@
1
+ import { createApiMethods } from "./api/methods.mjs";
2
+ import { createEventConnection } from "./event-connection.mjs";
3
+ import { createTransport } from "./transport.mjs";
4
+
5
+ export function createMailClient(options = {}) {
6
+ const transport = createTransport(options);
7
+ const api = createApiMethods(transport);
8
+ return {
9
+ ...api,
10
+ connectEvents(eventOptions) {
11
+ const settings = eventOptions ?? {};
12
+ return createEventConnection({
13
+ ...settings,
14
+ baseUrl: transport.baseUrl,
15
+ getAccessToken: options.getAccessToken,
16
+ WebSocketImpl: settings.WebSocketImpl ?? options.WebSocketImpl,
17
+ acknowledgeEvent: api.events.acknowledge,
18
+ });
19
+ },
20
+ };
21
+ }