@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/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
|
@@ -0,0 +1,148 @@
|
|
|
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 = () => {};
|
|
7
|
+
|
|
8
|
+
export function createEventConnection({
|
|
9
|
+
baseUrl,
|
|
10
|
+
getAccessToken,
|
|
11
|
+
acknowledgeEvent,
|
|
12
|
+
WebSocketImpl = globalThis.WebSocket,
|
|
13
|
+
after,
|
|
14
|
+
consumerId,
|
|
15
|
+
onEvent,
|
|
16
|
+
onError = noop,
|
|
17
|
+
autoReconnect = true,
|
|
18
|
+
retryDelayMs = 500,
|
|
19
|
+
maxReconnectDelayMs = 30_000,
|
|
20
|
+
} = {}) {
|
|
21
|
+
const options = {
|
|
22
|
+
getAccessToken,
|
|
23
|
+
WebSocketImpl,
|
|
24
|
+
onEvent,
|
|
25
|
+
onError,
|
|
26
|
+
consumerId,
|
|
27
|
+
acknowledgeEvent,
|
|
28
|
+
retryDelayMs,
|
|
29
|
+
maxReconnectDelayMs,
|
|
30
|
+
after,
|
|
31
|
+
};
|
|
32
|
+
validateEventOptions(options);
|
|
33
|
+
let cursor = after ?? null;
|
|
34
|
+
let socket;
|
|
35
|
+
let timer;
|
|
36
|
+
let stopped = false;
|
|
37
|
+
let attempt = 0;
|
|
38
|
+
let authenticated = false;
|
|
39
|
+
let initialSettled = false;
|
|
40
|
+
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);
|
|
48
|
+
|
|
49
|
+
function report(error) {
|
|
50
|
+
try {
|
|
51
|
+
onError(error);
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function settleReady(error) {
|
|
56
|
+
if (initialSettled) return;
|
|
57
|
+
initialSettled = true;
|
|
58
|
+
if (error) rejectReady(error);
|
|
59
|
+
else resolveReady();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function scheduleReconnect(code) {
|
|
63
|
+
if (stopped || !autoReconnect || code === 1000 || code === 1008) return;
|
|
64
|
+
const delay = Math.min(retryDelayMs * 2 ** attempt, maxReconnectDelayMs);
|
|
65
|
+
attempt += 1;
|
|
66
|
+
timer = setTimeout(connect, delay);
|
|
67
|
+
timer.unref?.();
|
|
68
|
+
}
|
|
69
|
+
|
|
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
|
+
}
|
|
80
|
+
|
|
81
|
+
async function connect() {
|
|
82
|
+
if (stopped) return;
|
|
83
|
+
authenticated = false;
|
|
84
|
+
let token;
|
|
85
|
+
try {
|
|
86
|
+
token = await getAccessToken();
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (stopped) return;
|
|
89
|
+
report(error);
|
|
90
|
+
settleReady(error);
|
|
91
|
+
scheduleReconnect(1006);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (stopped) return;
|
|
95
|
+
if (typeof token !== "string" || token.length === 0) {
|
|
96
|
+
const error = new TypeError("getAccessToken must return a non-empty bearer token");
|
|
97
|
+
stopped = true;
|
|
98
|
+
report(error);
|
|
99
|
+
settleReady(error);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
socket = createWebSocketSession({
|
|
104
|
+
url: socketUrl(baseUrl, cursor),
|
|
105
|
+
token,
|
|
106
|
+
WebSocketImpl,
|
|
107
|
+
onAuthenticated: () => {
|
|
108
|
+
authenticated = true;
|
|
109
|
+
attempt = 0;
|
|
110
|
+
settleReady();
|
|
111
|
+
},
|
|
112
|
+
onEvent: (event) => {
|
|
113
|
+
processing = processing
|
|
114
|
+
.then(() => processEvent(event))
|
|
115
|
+
.catch((error) => {
|
|
116
|
+
report(error);
|
|
117
|
+
stopped = true;
|
|
118
|
+
socket.close(1011, "event processing failed");
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
onClose: (code) => {
|
|
122
|
+
if (!authenticated)
|
|
123
|
+
settleReady(new Error(`WebSocket authentication closed with code ${code}`));
|
|
124
|
+
scheduleReconnect(code);
|
|
125
|
+
},
|
|
126
|
+
onError: report,
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
stopped = true;
|
|
130
|
+
report(error);
|
|
131
|
+
settleReady(error);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
void connect();
|
|
136
|
+
return {
|
|
137
|
+
ready,
|
|
138
|
+
get cursor() {
|
|
139
|
+
return cursor;
|
|
140
|
+
},
|
|
141
|
+
close() {
|
|
142
|
+
stopped = true;
|
|
143
|
+
if (timer) clearTimeout(timer);
|
|
144
|
+
settleReady(new Error("WebSocket connection closed by the client"));
|
|
145
|
+
socket?.close(1000, "client closed");
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function normalizeBaseUrl(value) {
|
|
2
|
+
let url;
|
|
3
|
+
try {
|
|
4
|
+
url = new URL(value);
|
|
5
|
+
} catch {
|
|
6
|
+
throw new TypeError("baseUrl must be a valid URL");
|
|
7
|
+
}
|
|
8
|
+
if (!/^https?:$/.test(url.protocol)) throw new TypeError("baseUrl must use HTTP or HTTPS");
|
|
9
|
+
if (url.pathname !== "/" || url.username || url.password || url.search || url.hash) {
|
|
10
|
+
throw new TypeError("baseUrl must be an HTTP origin without credentials or extra components");
|
|
11
|
+
}
|
|
12
|
+
return url.origin;
|
|
13
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { MailApiError } from "./api/error.mjs";
|
|
2
|
+
import { normalizeBaseUrl } from "./transport/base-url.mjs";
|
|
3
|
+
|
|
4
|
+
const defaultTimeoutMs = 15_000;
|
|
5
|
+
const noOperation = () => {};
|
|
6
|
+
const silentLogger = { debug: noOperation, warn: noOperation, error: noOperation };
|
|
7
|
+
|
|
8
|
+
function isPlainObject(value) {
|
|
9
|
+
if (value === null || typeof value !== "object") return false;
|
|
10
|
+
const prototype = Object.getPrototypeOf(value);
|
|
11
|
+
return prototype === Object.prototype || prototype === null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async function errorPayload(response) {
|
|
15
|
+
try {
|
|
16
|
+
return await response.clone().json();
|
|
17
|
+
} catch {
|
|
18
|
+
try {
|
|
19
|
+
return await response.clone().text();
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createTransport({
|
|
27
|
+
baseUrl,
|
|
28
|
+
getAccessToken,
|
|
29
|
+
fetchImpl = globalThis.fetch,
|
|
30
|
+
timeoutMs = defaultTimeoutMs,
|
|
31
|
+
logger = silentLogger,
|
|
32
|
+
} = {}) {
|
|
33
|
+
const apiOrigin = normalizeBaseUrl(baseUrl);
|
|
34
|
+
if (typeof getAccessToken !== "function") {
|
|
35
|
+
throw new TypeError("getAccessToken must be a function");
|
|
36
|
+
}
|
|
37
|
+
if (typeof fetchImpl !== "function") throw new TypeError("fetchImpl must be a function");
|
|
38
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) {
|
|
39
|
+
throw new TypeError("timeoutMs must be a positive safe integer");
|
|
40
|
+
}
|
|
41
|
+
if (
|
|
42
|
+
typeof logger?.debug !== "function" ||
|
|
43
|
+
typeof logger?.warn !== "function" ||
|
|
44
|
+
typeof logger?.error !== "function"
|
|
45
|
+
) {
|
|
46
|
+
throw new TypeError("logger must provide debug, warn, and error methods");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function request(path, options = {}) {
|
|
50
|
+
if (typeof path !== "string" || path.length === 0) {
|
|
51
|
+
throw new TypeError("path must be a non-empty string");
|
|
52
|
+
}
|
|
53
|
+
const url = new URL(path, `${apiOrigin}/`);
|
|
54
|
+
if (url.origin !== apiOrigin) throw new TypeError("path must use the configured API origin");
|
|
55
|
+
|
|
56
|
+
const token = await getAccessToken();
|
|
57
|
+
if (typeof token !== "string" || token.length === 0) {
|
|
58
|
+
throw new TypeError("getAccessToken must return a non-empty bearer token");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const headers = new Headers(options.headers);
|
|
62
|
+
headers.set("accept", "application/json");
|
|
63
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
64
|
+
const body = options.body;
|
|
65
|
+
const isJsonBody = isPlainObject(body);
|
|
66
|
+
const requestBody = isJsonBody ? JSON.stringify(body) : body;
|
|
67
|
+
if (isJsonBody && !headers.has("content-type")) {
|
|
68
|
+
headers.set("content-type", "application/json");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
72
|
+
const signal = options.signal
|
|
73
|
+
? AbortSignal.any([options.signal, timeoutSignal])
|
|
74
|
+
: timeoutSignal;
|
|
75
|
+
const method = String(options.method ?? "GET").toUpperCase();
|
|
76
|
+
let response;
|
|
77
|
+
try {
|
|
78
|
+
response = await fetchImpl(url, { ...options, method, headers, body: requestBody, signal });
|
|
79
|
+
} catch (error) {
|
|
80
|
+
logger.error("Mail API request failed", { method, errorName: error?.name ?? "Error" });
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
if (!response.ok) {
|
|
84
|
+
const error = new MailApiError(
|
|
85
|
+
response.status,
|
|
86
|
+
await errorPayload(response),
|
|
87
|
+
response.headers,
|
|
88
|
+
);
|
|
89
|
+
logger.warn("Mail API request failed", {
|
|
90
|
+
method,
|
|
91
|
+
status: error.status,
|
|
92
|
+
code: error.code,
|
|
93
|
+
requestId: error.requestId,
|
|
94
|
+
});
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
logger.debug("Mail API request completed", {
|
|
98
|
+
method,
|
|
99
|
+
status: response.status,
|
|
100
|
+
requestId: response.headers.get("x-request-id"),
|
|
101
|
+
});
|
|
102
|
+
return response;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function requestJson(path, options) {
|
|
106
|
+
return (await request(path, options)).json();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return { request, requestJson, baseUrl: apiOrigin };
|
|
110
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
const maxSnowflakeCursor = 18_446_744_073_709_551_615n;
|
|
2
|
+
const decimalCursorPattern = /^(0|[1-9]\d{0,19})$/;
|
|
3
|
+
|
|
4
|
+
export function isValidCursor(value) {
|
|
5
|
+
if (typeof value !== "string" || !decimalCursorPattern.test(value)) return false;
|
|
6
|
+
return BigInt(value) <= maxSnowflakeCursor;
|
|
7
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function eventData(value) {
|
|
2
|
+
const data = value?.data ?? value;
|
|
3
|
+
if (typeof data === "string") return data;
|
|
4
|
+
if (ArrayBuffer.isView(data)) return new TextDecoder().decode(data);
|
|
5
|
+
if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
|
|
6
|
+
throw new TypeError("WebSocket frame must contain JSON text");
|
|
7
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function subscribe(socket, name, handler) {
|
|
2
|
+
if (typeof socket.addEventListener === "function") {
|
|
3
|
+
socket.addEventListener(name, handler);
|
|
4
|
+
return () => socket.removeEventListener?.(name, handler);
|
|
5
|
+
}
|
|
6
|
+
if (typeof socket.on === "function") {
|
|
7
|
+
socket.on(name, handler);
|
|
8
|
+
return () => socket.off?.(name, handler);
|
|
9
|
+
}
|
|
10
|
+
throw new TypeError("WebSocket must support event listeners");
|
|
11
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { isValidCursor } from "./cursor.mjs";
|
|
2
|
+
|
|
3
|
+
export function validateEventOptions({
|
|
4
|
+
getAccessToken,
|
|
5
|
+
WebSocketImpl,
|
|
6
|
+
onEvent,
|
|
7
|
+
onError,
|
|
8
|
+
consumerId,
|
|
9
|
+
acknowledgeEvent,
|
|
10
|
+
retryDelayMs,
|
|
11
|
+
maxReconnectDelayMs,
|
|
12
|
+
after,
|
|
13
|
+
}) {
|
|
14
|
+
if (typeof getAccessToken !== "function")
|
|
15
|
+
throw new TypeError("getAccessToken must be a function");
|
|
16
|
+
if (typeof WebSocketImpl !== "function")
|
|
17
|
+
throw new TypeError("WebSocketImpl must be a constructor");
|
|
18
|
+
if (typeof onEvent !== "function") throw new TypeError("onEvent must be a function");
|
|
19
|
+
if (typeof onError !== "function") throw new TypeError("onError must be a function");
|
|
20
|
+
if (consumerId !== undefined && (typeof consumerId !== "string" || consumerId.length === 0)) {
|
|
21
|
+
throw new TypeError("consumerId must be a non-empty string");
|
|
22
|
+
}
|
|
23
|
+
if (consumerId !== undefined && typeof acknowledgeEvent !== "function") {
|
|
24
|
+
throw new TypeError("acknowledgeEvent must be a function when consumerId is set");
|
|
25
|
+
}
|
|
26
|
+
if (!Number.isSafeInteger(retryDelayMs) || retryDelayMs < 0) {
|
|
27
|
+
throw new TypeError("retryDelayMs must be a non-negative safe integer");
|
|
28
|
+
}
|
|
29
|
+
if (!Number.isSafeInteger(maxReconnectDelayMs) || maxReconnectDelayMs < retryDelayMs) {
|
|
30
|
+
throw new TypeError("maxReconnectDelayMs must be a safe integer at least retryDelayMs");
|
|
31
|
+
}
|
|
32
|
+
if (after !== undefined && !isValidCursor(after)) {
|
|
33
|
+
throw new TypeError("after must be a decimal Snowflake cursor");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { eventData } from "./frames.mjs";
|
|
2
|
+
import { subscribe } from "./listeners.mjs";
|
|
3
|
+
|
|
4
|
+
export function createWebSocketSession({
|
|
5
|
+
url,
|
|
6
|
+
token,
|
|
7
|
+
WebSocketImpl,
|
|
8
|
+
onAuthenticated,
|
|
9
|
+
onEvent,
|
|
10
|
+
onClose,
|
|
11
|
+
onError,
|
|
12
|
+
}) {
|
|
13
|
+
const socket = new WebSocketImpl(url);
|
|
14
|
+
let authenticated = false;
|
|
15
|
+
subscribe(socket, "open", () => {
|
|
16
|
+
socket.send(JSON.stringify({ type: "authenticate", token }));
|
|
17
|
+
});
|
|
18
|
+
subscribe(socket, "message", (value, isBinary = false) => {
|
|
19
|
+
if (isBinary) {
|
|
20
|
+
onError(new TypeError("WebSocket frames must use JSON text"));
|
|
21
|
+
socket.close(1002, "JSON text required");
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
let message;
|
|
25
|
+
try {
|
|
26
|
+
message = JSON.parse(eventData(value));
|
|
27
|
+
} catch (error) {
|
|
28
|
+
onError(error);
|
|
29
|
+
socket.close(1002, "invalid JSON frame");
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (!authenticated) {
|
|
33
|
+
if (message?.type === "authenticated") {
|
|
34
|
+
authenticated = true;
|
|
35
|
+
onAuthenticated();
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
onError(new Error("mail-server did not acknowledge WebSocket authentication"));
|
|
39
|
+
socket.close(1008, "authentication required");
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (message?.type !== "authenticated") onEvent(message);
|
|
43
|
+
});
|
|
44
|
+
subscribe(socket, "close", (event) => onClose(event?.code ?? 1006));
|
|
45
|
+
subscribe(socket, "error", (error) =>
|
|
46
|
+
onError(error instanceof Error ? error : new Error("WebSocket error")),
|
|
47
|
+
);
|
|
48
|
+
return socket;
|
|
49
|
+
}
|