@todoist/comms-sdk 0.0.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +182 -39
- package/dist/esm/authentication.js +247 -0
- package/dist/esm/clients/add-comment-helper.js +41 -0
- package/dist/esm/clients/attachments-client.js +99 -0
- package/dist/esm/clients/base-client.js +30 -0
- package/dist/esm/clients/channels-client.js +209 -0
- package/dist/esm/clients/comments-client.js +177 -0
- package/dist/esm/clients/conversation-messages-client.js +167 -0
- package/dist/esm/clients/conversations-client.js +281 -0
- package/dist/esm/clients/groups-client.js +170 -0
- package/dist/esm/clients/hooks-client.js +50 -0
- package/dist/esm/clients/inbox-client.js +186 -0
- package/dist/esm/clients/notify-audience.js +43 -0
- package/dist/esm/clients/reactions-client.js +96 -0
- package/dist/esm/clients/search-client.js +140 -0
- package/dist/esm/clients/threads-client.js +363 -0
- package/dist/esm/clients/users-client.js +368 -0
- package/dist/esm/clients/workspace-users-client.js +299 -0
- package/dist/esm/clients/workspaces-client.js +177 -0
- package/dist/esm/comms-api.js +67 -0
- package/dist/esm/consts/endpoints.js +31 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/migration.js +92 -0
- package/dist/esm/testUtils/msw-handlers.js +45 -0
- package/dist/esm/testUtils/msw-setup.js +32 -0
- package/dist/esm/testUtils/obsidian-fetch-adapter.js +50 -0
- package/dist/esm/testUtils/test-defaults.js +103 -0
- package/dist/esm/transport/fetch-with-retry.js +240 -0
- package/dist/esm/transport/http-client.js +53 -0
- package/dist/esm/transport/http-dispatcher.js +149 -0
- package/dist/esm/types/api-version.js +5 -0
- package/dist/esm/types/entities.js +508 -0
- package/dist/esm/types/enums.js +34 -0
- package/dist/esm/types/errors.js +82 -0
- package/dist/esm/types/http.js +1 -0
- package/dist/esm/types/index.js +6 -0
- package/dist/esm/types/requests.js +184 -0
- package/dist/esm/utils/case-conversion.js +47 -0
- package/dist/esm/utils/conversation-title.js +110 -0
- package/dist/esm/utils/headers.js +29 -0
- package/dist/esm/utils/index.js +5 -0
- package/dist/esm/utils/multipart-upload.js +198 -0
- package/dist/esm/utils/reply-recipients.js +111 -0
- package/dist/esm/utils/timestamp-conversion.js +54 -0
- package/dist/esm/utils/url-helpers.js +202 -0
- package/dist/esm/utils/uuidv7.js +170 -0
- package/dist/types/authentication.d.ts +183 -0
- package/dist/types/clients/add-comment-helper.d.ts +32 -0
- package/dist/types/clients/attachments-client.d.ts +55 -0
- package/dist/types/clients/base-client.d.ts +37 -0
- package/dist/types/clients/channels-client.d.ts +211 -0
- package/dist/types/clients/comments-client.d.ts +228 -0
- package/dist/types/clients/conversation-messages-client.d.ts +201 -0
- package/dist/types/clients/conversations-client.d.ts +366 -0
- package/dist/types/clients/groups-client.d.ts +148 -0
- package/dist/types/clients/hooks-client.d.ts +29 -0
- package/dist/types/clients/inbox-client.d.ts +478 -0
- package/dist/types/clients/notify-audience.d.ts +22 -0
- package/dist/types/clients/reactions-client.d.ts +57 -0
- package/dist/types/clients/search-client.d.ts +71 -0
- package/dist/types/clients/threads-client.d.ts +547 -0
- package/dist/types/clients/users-client.d.ts +280 -0
- package/dist/types/clients/workspace-users-client.d.ts +172 -0
- package/dist/types/clients/workspaces-client.d.ts +154 -0
- package/dist/types/comms-api.d.ts +73 -0
- package/dist/types/consts/endpoints.d.ts +27 -0
- package/dist/types/index.d.ts +21 -0
- package/dist/types/migration.d.ts +78 -0
- package/dist/types/testUtils/msw-handlers.d.ts +28 -0
- package/dist/types/testUtils/msw-setup.d.ts +1 -0
- package/dist/types/testUtils/obsidian-fetch-adapter.d.ts +29 -0
- package/dist/types/testUtils/test-defaults.d.ts +17 -0
- package/dist/types/transport/fetch-with-retry.d.ts +4 -0
- package/dist/types/transport/http-client.d.ts +14 -0
- package/dist/types/transport/http-dispatcher.d.ts +46 -0
- package/dist/types/types/api-version.d.ts +6 -0
- package/dist/types/types/entities.d.ts +3081 -0
- package/dist/types/types/enums.d.ts +55 -0
- package/dist/types/types/errors.d.ts +57 -0
- package/dist/types/types/http.d.ts +60 -0
- package/dist/types/types/index.d.ts +6 -0
- package/dist/types/types/requests.d.ts +604 -0
- package/dist/types/utils/case-conversion.d.ts +8 -0
- package/dist/types/utils/conversation-title.d.ts +84 -0
- package/dist/types/utils/headers.d.ts +13 -0
- package/dist/types/utils/index.d.ts +6 -0
- package/dist/types/utils/multipart-upload.d.ts +59 -0
- package/dist/types/utils/reply-recipients.d.ts +60 -0
- package/dist/types/utils/timestamp-conversion.d.ts +13 -0
- package/dist/types/utils/url-helpers.d.ts +129 -0
- package/dist/types/utils/uuidv7.d.ts +42 -0
- package/package.json +80 -8
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { CommsRequestError } from '../types/errors.js';
|
|
2
|
+
import { camelCaseKeys } from '../utils/case-conversion.js';
|
|
3
|
+
import { transformTimestamps } from '../utils/timestamp-conversion.js';
|
|
4
|
+
import { getDefaultTransport } from './http-dispatcher.js';
|
|
5
|
+
export async function fetchWithRetry(url, options, maxRetries = 3, customFetch) {
|
|
6
|
+
let lastError;
|
|
7
|
+
let attempt = 0;
|
|
8
|
+
for (; attempt <= maxRetries; attempt++) {
|
|
9
|
+
let clearTimeoutFn;
|
|
10
|
+
try {
|
|
11
|
+
let requestSignal = options.signal || undefined;
|
|
12
|
+
if (options.timeout && options.timeout > 0) {
|
|
13
|
+
const timeoutResult = createTimeoutSignal(options.timeout, requestSignal);
|
|
14
|
+
requestSignal = timeoutResult.signal;
|
|
15
|
+
clearTimeoutFn = timeoutResult.clear;
|
|
16
|
+
}
|
|
17
|
+
const response = customFetch
|
|
18
|
+
? await customFetch(url, options)
|
|
19
|
+
: await fetchWithDefaultTransport(url, options, requestSignal);
|
|
20
|
+
const responseText = await response.text();
|
|
21
|
+
let responseData;
|
|
22
|
+
try {
|
|
23
|
+
responseData = responseText ? JSON.parse(responseText) : undefined;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
responseData = responseText;
|
|
27
|
+
}
|
|
28
|
+
if (!response.ok) {
|
|
29
|
+
throw new CommsRequestError(`Request failed with status ${response.status}`, response.status, responseData);
|
|
30
|
+
}
|
|
31
|
+
const camelCased = camelCaseKeys(responseData);
|
|
32
|
+
const transformed = transformTimestamps(camelCased);
|
|
33
|
+
if (clearTimeoutFn) {
|
|
34
|
+
clearTimeoutFn();
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
data: transformed,
|
|
38
|
+
status: response.status,
|
|
39
|
+
headers: response.headers,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (clearTimeoutFn) {
|
|
44
|
+
clearTimeoutFn();
|
|
45
|
+
}
|
|
46
|
+
lastError = error instanceof Error ? error : new Error('Unknown error');
|
|
47
|
+
if (attempt < maxRetries && isNetworkError(lastError)) {
|
|
48
|
+
const delay = getRetryDelay(attempt + 1);
|
|
49
|
+
if (delay > 0) {
|
|
50
|
+
await sleep(delay);
|
|
51
|
+
}
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (lastError instanceof CommsRequestError) {
|
|
58
|
+
throw lastError;
|
|
59
|
+
}
|
|
60
|
+
throw new CommsRequestError(describeTransportFailure(lastError, attempt + 1), undefined, undefined, {
|
|
61
|
+
cause: lastError,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/** Causes reported before the rest of the chain is dropped. */
|
|
65
|
+
const CAUSE_CHAIN_LIMIT = 3;
|
|
66
|
+
/**
|
|
67
|
+
* Builds the message for a request that never produced a response.
|
|
68
|
+
*
|
|
69
|
+
* `fetch` reports every transport problem as the same `fetch failed`, and puts
|
|
70
|
+
* the reason a caller actually needs — `ENOTFOUND`, `ECONNRESET`, a TLS failure
|
|
71
|
+
* — in `cause`. Dropping that leaves an unattributable error in the logs, so
|
|
72
|
+
* unwrap the chain into the message and keep the original as `cause`.
|
|
73
|
+
*/
|
|
74
|
+
function describeTransportFailure(error, attempts) {
|
|
75
|
+
const base = error?.message ?? 'Request failed';
|
|
76
|
+
const cause = describeCauseChain(error);
|
|
77
|
+
const tries = attempts > 1 ? ` after ${attempts} attempts` : '';
|
|
78
|
+
return cause ? `${base} (${cause})${tries}` : `${base}${tries}`;
|
|
79
|
+
}
|
|
80
|
+
function describeCauseChain(error) {
|
|
81
|
+
const descriptions = [];
|
|
82
|
+
for (const cause of causeChain(error)) {
|
|
83
|
+
const description = describeCause(cause);
|
|
84
|
+
if (description) {
|
|
85
|
+
descriptions.push(description);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return descriptions.length > 0 ? descriptions.join(' <- ') : undefined;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Walks an error's `cause` chain, stopping at {@link CAUSE_CHAIN_LIMIT} and on
|
|
92
|
+
* a cycle. A failed connect can carry one error per address it tried; the first
|
|
93
|
+
* is representative and the rest repeat the same failure.
|
|
94
|
+
*/
|
|
95
|
+
function* causeChain(error) {
|
|
96
|
+
const seen = new Set();
|
|
97
|
+
let current = error?.cause;
|
|
98
|
+
let depth = 0;
|
|
99
|
+
while (current instanceof Error && !seen.has(current) && depth < CAUSE_CHAIN_LIMIT) {
|
|
100
|
+
seen.add(current);
|
|
101
|
+
depth++;
|
|
102
|
+
yield current;
|
|
103
|
+
const aggregated = current instanceof AggregateError ? current.errors[0] : undefined;
|
|
104
|
+
current = aggregated ?? current.cause;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function describeCause(error) {
|
|
108
|
+
const code = error.code;
|
|
109
|
+
return typeof code === 'string' && code.length > 0 ? `${code}: ${error.message}` : error.message;
|
|
110
|
+
}
|
|
111
|
+
async function fetchWithDefaultTransport(url, options, signal) {
|
|
112
|
+
// Read the dispatcher and its paired `fetch` as one value so they can never
|
|
113
|
+
// be mismatched. On Node, `fetch` is undici's own — paired with the
|
|
114
|
+
// dispatcher — so the request client and dispatcher stay on one undici
|
|
115
|
+
// version; otherwise the `decompress` interceptor terminates gzip responses
|
|
116
|
+
// when the global `fetch`'s bundled undici differs. Browser/edge (and Bun)
|
|
117
|
+
// have no paired `fetch` and fall back to the global one.
|
|
118
|
+
const transport = await getDefaultTransport();
|
|
119
|
+
// undici's `fetch` and the global `fetch` are the same function at runtime
|
|
120
|
+
// but carry different (undici vs DOM) `RequestInit`/`Response` types. Call
|
|
121
|
+
// through the global signature, which matches the global-typed `options`.
|
|
122
|
+
const fetchImpl = (transport?.fetch ?? fetch);
|
|
123
|
+
const response = transport?.dispatcher
|
|
124
|
+
? await fetchImpl(url, {
|
|
125
|
+
...options,
|
|
126
|
+
signal,
|
|
127
|
+
// @ts-expect-error - dispatcher is valid for Node.js fetch but not in TS types
|
|
128
|
+
dispatcher: transport.dispatcher,
|
|
129
|
+
})
|
|
130
|
+
: await fetchImpl(url, {
|
|
131
|
+
...options,
|
|
132
|
+
signal,
|
|
133
|
+
});
|
|
134
|
+
return convertResponseToCustomFetch(response);
|
|
135
|
+
}
|
|
136
|
+
async function sleep(ms) {
|
|
137
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
138
|
+
}
|
|
139
|
+
const timeoutErrorName = 'TimeoutError';
|
|
140
|
+
function createTimeoutError(timeoutMs) {
|
|
141
|
+
const error = new Error(`Request timeout after ${timeoutMs}ms`);
|
|
142
|
+
error.name = timeoutErrorName;
|
|
143
|
+
return error;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Transport-level failure codes worth another attempt: the request never got an
|
|
147
|
+
* answer, so nothing about the response argues against retrying. `UND_ERR_SOCKET`
|
|
148
|
+
* covers the HTTP/2 `GOAWAY` an edge proxy sends when it retires a pooled
|
|
149
|
+
* connection, which is otherwise indistinguishable from any other `fetch failed`.
|
|
150
|
+
*/
|
|
151
|
+
const NETWORK_ERROR_CODES = new Set([
|
|
152
|
+
'ECONNREFUSED',
|
|
153
|
+
'ECONNRESET',
|
|
154
|
+
'EAI_AGAIN',
|
|
155
|
+
'ENOTFOUND',
|
|
156
|
+
'EPIPE',
|
|
157
|
+
'ETIMEDOUT',
|
|
158
|
+
'UND_ERR_SOCKET',
|
|
159
|
+
]);
|
|
160
|
+
function isNetworkError(error) {
|
|
161
|
+
return (error.name === 'TypeError' ||
|
|
162
|
+
error.name === timeoutErrorName ||
|
|
163
|
+
error.message.toLowerCase().includes('network') ||
|
|
164
|
+
hasNetworkErrorCode(error));
|
|
165
|
+
}
|
|
166
|
+
function hasNetworkErrorCode(error) {
|
|
167
|
+
// The code can be on the error itself — a `customFetch` is free to reject
|
|
168
|
+
// with one directly — or on anything `fetch` wrapped to produce it.
|
|
169
|
+
if (hasRetryableCode(error)) {
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
for (const cause of causeChain(error)) {
|
|
173
|
+
if (hasRetryableCode(cause)) {
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
function hasRetryableCode(error) {
|
|
180
|
+
const code = error.code;
|
|
181
|
+
return typeof code === 'string' && NETWORK_ERROR_CODES.has(code);
|
|
182
|
+
}
|
|
183
|
+
/** First retry delay, doubling by {@link RETRY_DELAY_FACTOR} per attempt. */
|
|
184
|
+
const RETRY_BASE_DELAY_MS = 100;
|
|
185
|
+
const RETRY_DELAY_FACTOR = 4;
|
|
186
|
+
const RETRY_MAX_DELAY_MS = 2000;
|
|
187
|
+
/**
|
|
188
|
+
* How long to wait before retry `retryCount` (1-based).
|
|
189
|
+
*
|
|
190
|
+
* A retired connection takes a moment to be torn down and replaced, so retrying
|
|
191
|
+
* immediately just re-dispatches onto the socket that is going away and burns
|
|
192
|
+
* the whole retry budget inside a second. The delay grows so the later attempts
|
|
193
|
+
* land on a fresh connection, and carries jitter because one retirement hits
|
|
194
|
+
* every pooled connection at once: without it, every caller reconnects in step.
|
|
195
|
+
*/
|
|
196
|
+
function getRetryDelay(retryCount) {
|
|
197
|
+
const delay = Math.min(RETRY_BASE_DELAY_MS * RETRY_DELAY_FACTOR ** (retryCount - 1), RETRY_MAX_DELAY_MS);
|
|
198
|
+
return delay / 2 + Math.random() * (delay / 2);
|
|
199
|
+
}
|
|
200
|
+
function createTimeoutSignal(timeoutMs, existingSignal) {
|
|
201
|
+
const controller = new AbortController();
|
|
202
|
+
const timeoutId = setTimeout(() => {
|
|
203
|
+
controller.abort(createTimeoutError(timeoutMs));
|
|
204
|
+
}, timeoutMs);
|
|
205
|
+
let abortHandler;
|
|
206
|
+
function clear() {
|
|
207
|
+
clearTimeout(timeoutId);
|
|
208
|
+
if (existingSignal && abortHandler) {
|
|
209
|
+
existingSignal.removeEventListener('abort', abortHandler);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (existingSignal) {
|
|
213
|
+
if (existingSignal.aborted) {
|
|
214
|
+
clearTimeout(timeoutId);
|
|
215
|
+
controller.abort(existingSignal.reason);
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
abortHandler = () => {
|
|
219
|
+
clearTimeout(timeoutId);
|
|
220
|
+
controller.abort(existingSignal.reason);
|
|
221
|
+
};
|
|
222
|
+
existingSignal.addEventListener('abort', abortHandler, { once: true });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return { signal: controller.signal, clear };
|
|
226
|
+
}
|
|
227
|
+
function convertResponseToCustomFetch(response) {
|
|
228
|
+
const headers = {};
|
|
229
|
+
response.headers.forEach((value, key) => {
|
|
230
|
+
headers[key] = value;
|
|
231
|
+
});
|
|
232
|
+
return {
|
|
233
|
+
ok: response.ok,
|
|
234
|
+
status: response.status,
|
|
235
|
+
statusText: response.statusText,
|
|
236
|
+
headers,
|
|
237
|
+
text: () => response.clone().text(),
|
|
238
|
+
json: () => response.json(),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { snakeCaseKeys } from '../utils/case-conversion.js';
|
|
2
|
+
import { mergeHeaders, resolveCustomHeaders } from '../utils/headers.js';
|
|
3
|
+
import { fetchWithRetry } from './fetch-with-retry.js';
|
|
4
|
+
export function paramsSerializer(params) {
|
|
5
|
+
const qs = new URLSearchParams();
|
|
6
|
+
Object.keys(params).forEach((key) => {
|
|
7
|
+
const value = params[key];
|
|
8
|
+
if (value != null) {
|
|
9
|
+
if (Array.isArray(value)) {
|
|
10
|
+
qs.append(key, value.join(','));
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
qs.append(key, String(value));
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
return qs.toString();
|
|
18
|
+
}
|
|
19
|
+
const defaultHeaders = {
|
|
20
|
+
'Content-Type': 'application/json',
|
|
21
|
+
};
|
|
22
|
+
function getAuthHeader(apiToken) {
|
|
23
|
+
return `Bearer ${apiToken}`;
|
|
24
|
+
}
|
|
25
|
+
function getRequestConfiguration(baseURL, apiToken, requestId, customHeaders) {
|
|
26
|
+
const authHeader = apiToken ? { Authorization: getAuthHeader(apiToken) } : undefined;
|
|
27
|
+
const requestIdHeader = requestId ? { 'X-Request-Id': requestId } : undefined;
|
|
28
|
+
// Custom headers sit below auth and request id so they can never clobber them.
|
|
29
|
+
const headers = mergeHeaders(defaultHeaders, resolveCustomHeaders(customHeaders), authHeader, requestIdHeader);
|
|
30
|
+
return { baseURL, headers, timeout: 30000 };
|
|
31
|
+
}
|
|
32
|
+
export async function request(args) {
|
|
33
|
+
const { httpMethod, baseUri, relativePath, apiToken, payload, requestId, headers, customFetch, } = args;
|
|
34
|
+
const config = getRequestConfiguration(baseUri, apiToken, requestId, headers);
|
|
35
|
+
const url = new URL(relativePath, config.baseURL).toString();
|
|
36
|
+
const options = {
|
|
37
|
+
method: httpMethod,
|
|
38
|
+
headers: config.headers,
|
|
39
|
+
timeout: config.timeout,
|
|
40
|
+
};
|
|
41
|
+
if (httpMethod === 'GET' && payload) {
|
|
42
|
+
const searchParams = paramsSerializer(snakeCaseKeys(payload));
|
|
43
|
+
const urlWithParams = searchParams ? `${url}?${searchParams}` : url;
|
|
44
|
+
return fetchWithRetry(urlWithParams, options, 3, customFetch);
|
|
45
|
+
}
|
|
46
|
+
if (payload && httpMethod !== 'GET') {
|
|
47
|
+
options.body = JSON.stringify(snakeCaseKeys(payload));
|
|
48
|
+
}
|
|
49
|
+
return fetchWithRetry(url, options, 3, customFetch);
|
|
50
|
+
}
|
|
51
|
+
export function isSuccess(response) {
|
|
52
|
+
return response.status >= 200 && response.status < 300;
|
|
53
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
let defaultTransport;
|
|
2
|
+
let defaultTransportPromise;
|
|
3
|
+
/**
|
|
4
|
+
* The default dispatcher and its paired `fetch`, as a single value so the two
|
|
5
|
+
* are always read consistently. Resolves to `undefined` outside Node (browser/
|
|
6
|
+
* edge), where callers use the global `fetch` with no dispatcher.
|
|
7
|
+
*/
|
|
8
|
+
export async function getDefaultTransport() {
|
|
9
|
+
if (defaultTransport) {
|
|
10
|
+
return defaultTransport;
|
|
11
|
+
}
|
|
12
|
+
if (!defaultTransportPromise) {
|
|
13
|
+
defaultTransportPromise = createDefaultTransport()
|
|
14
|
+
.then((transport) => {
|
|
15
|
+
defaultTransport = transport;
|
|
16
|
+
return transport;
|
|
17
|
+
})
|
|
18
|
+
.catch((error) => {
|
|
19
|
+
defaultTransport = undefined;
|
|
20
|
+
defaultTransportPromise = undefined;
|
|
21
|
+
throw error;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
return defaultTransportPromise;
|
|
25
|
+
}
|
|
26
|
+
export async function getDefaultDispatcher() {
|
|
27
|
+
return (await getDefaultTransport())?.dispatcher;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Drains the default dispatcher's connection pool. CLIs and scripts should
|
|
31
|
+
* `await` this before exit so Node's event loop empties immediately instead
|
|
32
|
+
* of waiting ~4s on keep-alive. No-op in the browser branch.
|
|
33
|
+
*/
|
|
34
|
+
export async function closeDefaultDispatcher() {
|
|
35
|
+
// Clear the singleton *before* awaiting init, so any concurrent
|
|
36
|
+
// `getDefaultTransport()` after this point creates a fresh dispatcher
|
|
37
|
+
// instead of receiving a reference to the one we're about to close.
|
|
38
|
+
const initPromise = defaultTransportPromise;
|
|
39
|
+
defaultTransport = undefined;
|
|
40
|
+
defaultTransportPromise = undefined;
|
|
41
|
+
if (!initPromise)
|
|
42
|
+
return;
|
|
43
|
+
try {
|
|
44
|
+
const transport = await initPromise;
|
|
45
|
+
if (transport) {
|
|
46
|
+
await transport.dispatcher.close();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// init failed; nothing to close
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function resetDefaultDispatcherForTests() {
|
|
54
|
+
defaultTransport = undefined;
|
|
55
|
+
defaultTransportPromise = undefined;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The `fetch` implementation that must be used with the default dispatcher.
|
|
59
|
+
* Returns undici's own `fetch` on the full-undici Node path, or `undefined`
|
|
60
|
+
* (meaning: use the global `fetch`) in the browser/edge/Bun paths.
|
|
61
|
+
*
|
|
62
|
+
* Node's global `fetch` is backed by whatever undici version ships inside that
|
|
63
|
+
* Node release (6.x on Node 22 … 8.x on Node 26). Our dispatcher — and its
|
|
64
|
+
* `decompress` interceptor — comes from the npm `undici` package, which is a
|
|
65
|
+
* different version. Handing an npm-undici dispatcher to a mismatched built-in
|
|
66
|
+
* client makes gzip responses fail mid-stream with `terminated`. Sourcing
|
|
67
|
+
* `fetch` from the same npm `undici` keeps the whole request path on one
|
|
68
|
+
* version and removes the split.
|
|
69
|
+
*
|
|
70
|
+
* Only meaningful after {@link getDefaultTransport} has resolved, which is the
|
|
71
|
+
* one place that populates it.
|
|
72
|
+
*/
|
|
73
|
+
export function getDefaultFetch() {
|
|
74
|
+
return defaultTransport?.fetch;
|
|
75
|
+
}
|
|
76
|
+
function isNodeEnvironment() {
|
|
77
|
+
return typeof process !== 'undefined' && typeof process.versions?.node === 'string';
|
|
78
|
+
}
|
|
79
|
+
async function createDefaultTransport() {
|
|
80
|
+
if (!isNodeEnvironment()) {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
// Dynamic import so non-Node consumers (browser, edge runtimes) don't pull
|
|
84
|
+
// undici into their bundle. `isNodeEnvironment()` above already gated this
|
|
85
|
+
// branch, so undici is safe to load when we get here.
|
|
86
|
+
const { EnvHttpProxyAgent, interceptors, fetch: undiciFetch } = await import('undici');
|
|
87
|
+
// `EnvHttpProxyAgent` (with `allowH2`) and `interceptors.decompress()` both
|
|
88
|
+
// emit an ExperimentalWarning on first use, so build the whole dispatcher
|
|
89
|
+
// inside the suppression block.
|
|
90
|
+
return suppressExperimentalWarningsSync(() => {
|
|
91
|
+
// `allowH2: true` opts into HTTP/2 via ALPN; undici falls back to h1.1
|
|
92
|
+
// when the server doesn't negotiate h2. Without this flag undici
|
|
93
|
+
// defaults to h1.1 even when the server supports h2.
|
|
94
|
+
const agent = new EnvHttpProxyAgent({ allowH2: true });
|
|
95
|
+
// Some runtimes report `process.versions.node` (so `isNodeEnvironment()`
|
|
96
|
+
// passes) but ship only a partial undici: `interceptors.decompress` is
|
|
97
|
+
// absent and dispatchers have no `.compose`. Bun is the common case.
|
|
98
|
+
// There the proxy agent alone is enough — Bun's `fetch` decompresses
|
|
99
|
+
// gzip/deflate/br/zstd natively — so skip the interceptor instead of
|
|
100
|
+
// crashing on the missing API. Optional chaining also guards a runtime
|
|
101
|
+
// that omits the `interceptors` export entirely.
|
|
102
|
+
if (typeof interceptors?.decompress !== 'function') {
|
|
103
|
+
// Bun: pair the agent with the global `fetch` (undefined), which
|
|
104
|
+
// decompresses natively.
|
|
105
|
+
return { dispatcher: agent, fetch: undefined };
|
|
106
|
+
}
|
|
107
|
+
// `interceptors.decompress()` decodes gzip/deflate/br/zstd bodies. On
|
|
108
|
+
// Node 24+, attaching any custom dispatcher to global `fetch` strips
|
|
109
|
+
// `content-encoding` without actually decompressing the body.
|
|
110
|
+
// See https://github.com/todoist/todoist-cli/issues/318.
|
|
111
|
+
const decompress = interceptors.decompress();
|
|
112
|
+
// Pair undici's own `fetch` with this dispatcher so the request client
|
|
113
|
+
// and the dispatcher stay on one undici version (see `getDefaultFetch`).
|
|
114
|
+
// The global `fetch` is backed by a different, Node-bundled undici;
|
|
115
|
+
// mixing the two makes the decompress interceptor terminate gzip
|
|
116
|
+
// responses on some Node versions.
|
|
117
|
+
return { dispatcher: agent.compose(decompress), fetch: undiciFetch };
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
// `suppressExperimentalWarningsSync` is exported for direct unit testing —
|
|
121
|
+
// the integration path through `getDefaultDispatcher()` can't reliably
|
|
122
|
+
// exercise it because both the dispatcher singleton and undici's internal
|
|
123
|
+
// `warningEmitted` flag are once-per-process.
|
|
124
|
+
//
|
|
125
|
+
// `fn` must be synchronous so the override covers a single critical section
|
|
126
|
+
// (microseconds) — no unrelated `ExperimentalWarning` from elsewhere can
|
|
127
|
+
// interleave and be lost. We suppress every `ExperimentalWarning` rather than
|
|
128
|
+
// pattern-matching the message text: the message wording is an undici
|
|
129
|
+
// implementation detail (not a stable API), and the suppression window is
|
|
130
|
+
// narrow enough that a coarse type filter is safe.
|
|
131
|
+
export function suppressExperimentalWarningsSync(fn) {
|
|
132
|
+
const originalEmit = process.emitWarning;
|
|
133
|
+
process.emitWarning = ((warning, typeOrOptions, ...rest) => {
|
|
134
|
+
const type = typeof typeOrOptions === 'string'
|
|
135
|
+
? typeOrOptions
|
|
136
|
+
: typeof typeOrOptions === 'object' && typeOrOptions !== null
|
|
137
|
+
? typeOrOptions.type
|
|
138
|
+
: undefined;
|
|
139
|
+
if (type === 'ExperimentalWarning')
|
|
140
|
+
return;
|
|
141
|
+
originalEmit.call(process, warning, typeOrOptions, ...rest);
|
|
142
|
+
});
|
|
143
|
+
try {
|
|
144
|
+
return fn();
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
process.emitWarning = originalEmit;
|
|
148
|
+
}
|
|
149
|
+
}
|