@doist/todoist-sdk 14.1.0 → 14.2.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/README.md CHANGED
@@ -125,12 +125,57 @@ const refreshed = await refreshAuthToken({
125
125
  > refresh. For public clients (`tokenEndpointAuthMethod: 'none'`), omit
126
126
  > `clientSecret` when calling `refreshAuthToken`.
127
127
 
128
+ ### Keeping Proxy Support and Response Decompression
129
+
130
+ On Node, the SDK's default transport reads the proxy environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) and decodes compressed response bodies. Supplying a `customFetch` replaces that transport, so a custom implementation that still wants both can borrow it with `getDefaultTransport`:
131
+
132
+ ```typescript
133
+ import { type CustomFetch, getDefaultTransport, TodoistApi } from '@doist/todoist-sdk'
134
+
135
+ const customFetch: CustomFetch = async (url, options) => {
136
+ const transport = await getDefaultTransport()
137
+ // undici's `fetch` and the global one are the same call at runtime but
138
+ // carry different types, so settle on one signature.
139
+ const fetchImpl = (transport?.fetch ?? fetch) as typeof fetch
140
+
141
+ const response = await fetchImpl(url, {
142
+ ...options,
143
+ headers: {
144
+ ...(options?.headers as Record<string, string> | undefined),
145
+ 'x-my-header': 'value',
146
+ },
147
+ // `dispatcher` is a Node fetch option that the DOM types don't declare.
148
+ dispatcher: transport?.dispatcher,
149
+ } as RequestInit)
150
+
151
+ // `CustomFetchResponse` wants plain-object headers, not a `Headers`.
152
+ const headers: Record<string, string> = {}
153
+ response.headers.forEach((value, key) => {
154
+ headers[key] = value
155
+ })
156
+
157
+ return {
158
+ ok: response.ok,
159
+ status: response.status,
160
+ statusText: response.statusText,
161
+ headers,
162
+ text: () => response.text(),
163
+ json: () => response.json(),
164
+ arrayBuffer: () => response.arrayBuffer(),
165
+ }
166
+ }
167
+
168
+ const api = new TodoistApi('YOURTOKEN', { customFetch })
169
+ ```
170
+
171
+ `getDefaultTransport` returns the dispatcher and the `fetch` it must be used with as a single value, and both halves have to be used together. The dispatcher decompresses the response body itself, so pairing it with a `fetch` from a different undici build — including the runtime's global `fetch` on Node 26 — decodes the body twice and the request fails mid-stream with `terminated`. A `fetch` of `undefined` means the global `fetch` is the correct partner; the whole value is `undefined` outside Node, where no dispatcher applies.
172
+
128
173
  ### Important Notes
129
174
 
130
175
  - All existing transforms (snake_case ↔ camelCase) work automatically with custom fetch
131
176
  - Retry logic and error handling are preserved
132
177
  - File uploads work with custom fetch implementations
133
- - The custom fetch function should handle FormData for multipart uploads
178
+ - File upload bodies are a `Blob`, or a `ReadableStream` when uploading from a stream — a custom fetch must pass them through unchanged
134
179
  - Timeout parameter is optional and up to your custom implementation
135
180
 
136
181
  ## Development and Testing
package/dist/cjs/index.js CHANGED
@@ -14,10 +14,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.getDefaultDispatcher = void 0;
17
+ exports.getDefaultTransport = exports.getDefaultDispatcher = void 0;
18
18
  __exportStar(require("./todoist-api"), exports);
19
19
  __exportStar(require("./authentication"), exports);
20
20
  __exportStar(require("./types"), exports);
21
21
  __exportStar(require("./utils"), exports);
22
22
  var http_dispatcher_1 = require("./transport/http-dispatcher");
23
23
  Object.defineProperty(exports, "getDefaultDispatcher", { enumerable: true, get: function () { return http_dispatcher_1.getDefaultDispatcher; } });
24
+ Object.defineProperty(exports, "getDefaultTransport", { enumerable: true, get: function () { return http_dispatcher_1.getDefaultTransport; } });
@@ -50,6 +50,23 @@ let defaultTransportPromise;
50
50
  * The default dispatcher and its paired `fetch`, as a single value so the two
51
51
  * are always read consistently. Resolves to `undefined` outside Node (browser/
52
52
  * edge), where callers use the global `fetch` with no dispatcher.
53
+ *
54
+ * Use this when supplying a `customFetch` that should still honour the proxy
55
+ * environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) and decode
56
+ * compressed responses the way the SDK does by default.
57
+ *
58
+ * Both halves must be used together. `dispatcher` decompresses the response
59
+ * body itself, so a `fetch` from a different undici build will try to decode
60
+ * it a second time and the request fails mid-stream with `terminated`. A
61
+ * `fetch` of `undefined` means the runtime's global `fetch` is the correct
62
+ * partner for this dispatcher.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const transport = await getDefaultTransport()
67
+ * const fetchImpl = transport?.fetch ?? fetch
68
+ * const response = await fetchImpl(url, { ...options, dispatcher: transport?.dispatcher })
69
+ * ```
53
70
  */
54
71
  function getDefaultTransport() {
55
72
  if (!isNodeEnvironment()) {
@@ -69,6 +86,14 @@ function getDefaultTransport() {
69
86
  }
70
87
  return defaultTransportPromise;
71
88
  }
89
+ /**
90
+ * The default dispatcher on its own.
91
+ *
92
+ * @deprecated Use {@link getDefaultTransport} instead, which returns this
93
+ * dispatcher together with the `fetch` it must be used with. Attaching this
94
+ * dispatcher to the runtime's global `fetch` decodes compressed responses
95
+ * twice on Node 26 and the request fails with `terminated`.
96
+ */
72
97
  async function getDefaultDispatcher() {
73
98
  var _a;
74
99
  return (_a = (await getDefaultTransport())) === null || _a === void 0 ? void 0 : _a.dispatcher;
@@ -32,8 +32,29 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
36
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
37
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
38
+ var m = o[Symbol.asyncIterator], i;
39
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
40
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
41
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
42
+ };
43
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
44
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
45
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
46
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
47
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
48
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
49
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
50
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
51
+ function fulfill(value) { resume("next", value); }
52
+ function reject(value) { resume("throw", value); }
53
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
54
+ };
35
55
  Object.defineProperty(exports, "__esModule", { value: true });
36
56
  exports.uploadMultipartFile = uploadMultipartFile;
57
+ const uuid_1 = require("uuid");
37
58
  const fetch_with_retry_1 = require("../transport/fetch-with-retry");
38
59
  const case_conversion_1 = require("./case-conversion");
39
60
  /**
@@ -59,6 +80,116 @@ function getContentTypeFromFileName(fileName) {
59
80
  return 'application/octet-stream';
60
81
  }
61
82
  }
83
+ /**
84
+ * Escapes a value for use inside a quoted `Content-Disposition` parameter,
85
+ * where a raw quote would end the value early and a raw CR or LF would end the
86
+ * header. Note that a lone CR needs escaping too, not just CRLF pairs.
87
+ *
88
+ * This is the same escaping the platform's own `FormData` encoder applies, so
89
+ * servers see exactly what they would from any browser or from undici.
90
+ */
91
+ function escapeDispositionValue(value) {
92
+ return value.replace(/"/g, '%22').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
93
+ }
94
+ /**
95
+ * Lays out a `multipart/form-data` payload around a single file part, as the
96
+ * text that goes before and after the file content. Keeping the file content
97
+ * out of it lets the same layout serve both a `Blob` body and a streamed one.
98
+ */
99
+ function layOutMultipart(args) {
100
+ const { fileName, fileContentType, additionalFields } = args;
101
+ const boundary = `----todoist-sdk-${(0, uuid_1.v4)()}`;
102
+ const head = `--${boundary}\r\n` +
103
+ `Content-Disposition: form-data; name="file"; filename="${escapeDispositionValue(fileName)}"\r\n` +
104
+ `Content-Type: ${fileContentType}\r\n\r\n`;
105
+ let tail = '\r\n';
106
+ for (const [key, value] of Object.entries(additionalFields)) {
107
+ if (value !== undefined && value !== null) {
108
+ tail +=
109
+ `--${boundary}\r\n` +
110
+ `Content-Disposition: form-data; name="${escapeDispositionValue(key)}"\r\n\r\n` +
111
+ `${value.toString()}\r\n`;
112
+ }
113
+ }
114
+ tail += `--${boundary}--\r\n`;
115
+ return { boundary, head, tail };
116
+ }
117
+ /**
118
+ * Wraps a Node readable stream as a `multipart/form-data` request body.
119
+ *
120
+ * The result is a web `ReadableStream`, which both the runtime's `fetch` and
121
+ * undici's own accept — unlike a Node stream or a `FormData`, either of which
122
+ * only works with one particular client. The file is never buffered, so the
123
+ * request is sent with `Transfer-Encoding: chunked`.
124
+ */
125
+ function streamMultipartBody(file, parts) {
126
+ const encoder = new TextEncoder();
127
+ function chunks() {
128
+ return __asyncGenerator(this, arguments, function* chunks_1() {
129
+ var _a, e_1, _b, _c;
130
+ yield yield __await(encoder.encode(parts.head));
131
+ try {
132
+ for (var _d = true, file_1 = __asyncValues(file), file_1_1; file_1_1 = yield __await(file_1.next()), _a = file_1_1.done, !_a; _d = true) {
133
+ _c = file_1_1.value;
134
+ _d = false;
135
+ const chunk = _c;
136
+ yield yield __await(typeof chunk === 'string' ? encoder.encode(chunk) : new Uint8Array(chunk));
137
+ }
138
+ }
139
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
140
+ finally {
141
+ try {
142
+ if (!_d && !_a && (_b = file_1.return)) yield __await(_b.call(file_1));
143
+ }
144
+ finally { if (e_1) throw e_1.error; }
145
+ }
146
+ yield yield __await(encoder.encode(parts.tail));
147
+ });
148
+ }
149
+ const iterator = chunks();
150
+ // Driven by hand rather than with `ReadableStream.from`, which is absent
151
+ // from this project's DOM lib types and is still missing in some browsers,
152
+ // or `Readable.toWeb`, which would drag a Node-only import into a module
153
+ // that browsers also load.
154
+ return new ReadableStream({
155
+ async pull(controller) {
156
+ const { value, done } = await iterator.next();
157
+ if (done) {
158
+ controller.close();
159
+ return;
160
+ }
161
+ controller.enqueue(value);
162
+ },
163
+ async cancel(reason) {
164
+ var _a;
165
+ await ((_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator, reason));
166
+ },
167
+ });
168
+ }
169
+ /**
170
+ * Builds the request body for a multipart upload.
171
+ *
172
+ * Deliberately avoids `FormData`. A `FormData` body is only encoded by the
173
+ * `fetch` that owns that `FormData` class — undici brands its own — so a body
174
+ * built from the global `FormData` and sent through undici's `fetch`, or the
175
+ * reverse, is stringified to the literal `"[object FormData]"` and the upload
176
+ * silently carries no file. The `form-data` package fares worse: neither
177
+ * `fetch` accepts it as a body at all. `Blob` and `ReadableStream` carry no
178
+ * such brand and work with whichever `fetch` dispatches the request,
179
+ * including a caller-supplied `customFetch`.
180
+ */
181
+ function buildMultipartBody(args) {
182
+ const { file, fileName, fileContentType, additionalFields } = args;
183
+ const parts = layOutMultipart({ fileName, fileContentType, additionalFields });
184
+ const contentType = `multipart/form-data; boundary=${parts.boundary}`;
185
+ if (file instanceof Blob) {
186
+ // A Blob keeps its length, so the request gets a Content-Length and
187
+ // stays replayable if it has to be retried. File-backed Blobs (from
188
+ // `fs.openAsBlob`) stay lazy here, so nothing is read into memory.
189
+ return { body: new Blob([parts.head, file, parts.tail]), contentType, isStreamed: false };
190
+ }
191
+ return { body: streamMultipartBody(file, parts), contentType, isStreamed: true };
192
+ }
62
193
  /**
63
194
  * Uploads a file using multipart/form-data.
64
195
  *
@@ -111,69 +242,52 @@ async function uploadMultipartFile(args) {
111
242
  if (requestId) {
112
243
  headers['X-Request-Id'] = requestId;
113
244
  }
245
+ // Resolve the file to something every `fetch` accepts as a body part: a
246
+ // Blob where the size is known up front, or a Node stream that gets piped
247
+ // through untouched.
248
+ let filePart;
249
+ let resolvedFileName;
114
250
  if (file instanceof Blob) {
115
- // Browser path: use native FormData
116
- const form = new globalThis.FormData();
117
- const resolvedFileName = fileName || (file instanceof File ? file.name : undefined) || 'upload';
118
- form.append('file', file, resolvedFileName);
119
- for (const [key, value] of Object.entries(additionalFields)) {
120
- if (value !== undefined && value !== null) {
121
- form.append(key, value.toString());
122
- }
251
+ filePart = file;
252
+ resolvedFileName = fileName || (file instanceof File ? file.name : undefined) || 'upload';
253
+ }
254
+ else if (typeof file === 'string') {
255
+ // File path: Node-only, so import lazily to keep browser bundles clean.
256
+ const [fsModule, pathModule] = await Promise.all([Promise.resolve().then(() => __importStar(require('fs'))), Promise.resolve().then(() => __importStar(require('path')))]);
257
+ resolvedFileName = fileName || pathModule.basename(file);
258
+ // `openAsBlob` reads the file lazily, so a large upload is not pulled
259
+ // into memory, and the resulting body still has a known length.
260
+ filePart = await fsModule.openAsBlob(file);
261
+ }
262
+ else if (Buffer.isBuffer(file)) {
263
+ if (!fileName) {
264
+ throw new Error('fileName is required when uploading from a Buffer');
123
265
  }
124
- // Don't set Content-Type — let fetch set it with the correct multipart boundary
125
- body = form;
266
+ resolvedFileName = fileName;
267
+ filePart = new Blob([
268
+ new Uint8Array(file.buffer, file.byteOffset, file.byteLength),
269
+ ]);
126
270
  }
127
271
  else {
128
- // Node path: dynamically import Node-only modules
129
- const [FormDataModule, fsModule, pathModule] = await Promise.all([
130
- Promise.resolve().then(() => __importStar(require('form-data'))),
131
- Promise.resolve().then(() => __importStar(require('fs'))),
132
- Promise.resolve().then(() => __importStar(require('path'))),
133
- ]);
134
- const FormData = FormDataModule.default;
135
- const form = new FormData();
136
- if (typeof file === 'string') {
137
- // File path - create read stream
138
- const resolvedFileName = fileName || pathModule.basename(file);
139
- form.append('file', fsModule.createReadStream(file), resolvedFileName);
140
- }
141
- else if (Buffer.isBuffer(file)) {
142
- // Buffer - require fileName
143
- if (!fileName) {
144
- throw new Error('fileName is required when uploading from a Buffer');
145
- }
146
- const contentType = getContentTypeFromFileName(fileName);
147
- form.append('file', file, {
148
- filename: fileName,
149
- contentType: contentType,
150
- });
151
- }
152
- else {
153
- // Stream - require fileName
154
- if (!fileName) {
155
- throw new Error('fileName is required when uploading from a stream');
156
- }
157
- form.append('file', file, fileName);
272
+ if (!fileName) {
273
+ throw new Error('fileName is required when uploading from a stream');
158
274
  }
159
- for (const [key, value] of Object.entries(additionalFields)) {
160
- if (value !== undefined && value !== null) {
161
- form.append(key, value.toString());
162
- }
163
- }
164
- Object.assign(headers, form.getHeaders());
165
- body = form;
275
+ resolvedFileName = fileName;
276
+ filePart = file;
166
277
  }
167
- // Make the request using fetch
168
- const response = await (0, fetch_with_retry_1.fetchWithRetry)({
169
- url,
170
- options: {
171
- method: 'POST',
172
- body,
173
- headers,
174
- timeout: 30000, // 30 second timeout for file uploads
175
- },
176
- customFetch,
278
+ const multipart = buildMultipartBody({
279
+ file: filePart,
280
+ fileName: resolvedFileName,
281
+ fileContentType: (filePart instanceof Blob ? filePart.type : undefined) ||
282
+ getContentTypeFromFileName(resolvedFileName),
283
+ additionalFields,
177
284
  });
285
+ // The boundary is ours, so Content-Type has to be set explicitly — `fetch`
286
+ // only fills it in for a `FormData` body.
287
+ headers['Content-Type'] = multipart.contentType;
288
+ body = multipart.body;
289
+ // Make the request using fetch
290
+ const response = await (0, fetch_with_retry_1.fetchWithRetry)(Object.assign(Object.assign({ url, options: Object.assign({ method: 'POST', body,
291
+ headers, timeout: 30000 }, (multipart.isStreamed ? { duplex: 'half' } : {})) }, (multipart.isStreamed ? { retryConfig: { retries: 0 } } : {})), { customFetch }));
178
292
  return (0, case_conversion_1.camelCaseKeys)(response.data);
179
293
  }
package/dist/esm/index.js CHANGED
@@ -2,4 +2,4 @@ export * from './todoist-api.js';
2
2
  export * from './authentication.js';
3
3
  export * from './types/index.js';
4
4
  export * from './utils/index.js';
5
- export { getDefaultDispatcher } from './transport/http-dispatcher.js';
5
+ export { getDefaultDispatcher, getDefaultTransport } from './transport/http-dispatcher.js';
@@ -10,6 +10,23 @@ let defaultTransportPromise;
10
10
  * The default dispatcher and its paired `fetch`, as a single value so the two
11
11
  * are always read consistently. Resolves to `undefined` outside Node (browser/
12
12
  * edge), where callers use the global `fetch` with no dispatcher.
13
+ *
14
+ * Use this when supplying a `customFetch` that should still honour the proxy
15
+ * environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) and decode
16
+ * compressed responses the way the SDK does by default.
17
+ *
18
+ * Both halves must be used together. `dispatcher` decompresses the response
19
+ * body itself, so a `fetch` from a different undici build will try to decode
20
+ * it a second time and the request fails mid-stream with `terminated`. A
21
+ * `fetch` of `undefined` means the runtime's global `fetch` is the correct
22
+ * partner for this dispatcher.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const transport = await getDefaultTransport()
27
+ * const fetchImpl = transport?.fetch ?? fetch
28
+ * const response = await fetchImpl(url, { ...options, dispatcher: transport?.dispatcher })
29
+ * ```
13
30
  */
14
31
  export function getDefaultTransport() {
15
32
  if (!isNodeEnvironment()) {
@@ -29,6 +46,14 @@ export function getDefaultTransport() {
29
46
  }
30
47
  return defaultTransportPromise;
31
48
  }
49
+ /**
50
+ * The default dispatcher on its own.
51
+ *
52
+ * @deprecated Use {@link getDefaultTransport} instead, which returns this
53
+ * dispatcher together with the `fetch` it must be used with. Attaching this
54
+ * dispatcher to the runtime's global `fetch` decodes compressed responses
55
+ * twice on Node 26 and the request fails with `terminated`.
56
+ */
32
57
  export async function getDefaultDispatcher() {
33
58
  var _a;
34
59
  return (_a = (await getDefaultTransport())) === null || _a === void 0 ? void 0 : _a.dispatcher;
@@ -1,3 +1,24 @@
1
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
2
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
3
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4
+ var m = o[Symbol.asyncIterator], i;
5
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
7
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
8
+ };
9
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
10
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
11
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
12
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
13
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
14
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
15
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
16
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
17
+ function fulfill(value) { resume("next", value); }
18
+ function reject(value) { resume("throw", value); }
19
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
20
+ };
21
+ import { v4 as uuidv4 } from 'uuid';
1
22
  import { fetchWithRetry } from '../transport/fetch-with-retry.js';
2
23
  import { camelCaseKeys } from './case-conversion.js';
3
24
  /**
@@ -23,6 +44,116 @@ function getContentTypeFromFileName(fileName) {
23
44
  return 'application/octet-stream';
24
45
  }
25
46
  }
47
+ /**
48
+ * Escapes a value for use inside a quoted `Content-Disposition` parameter,
49
+ * where a raw quote would end the value early and a raw CR or LF would end the
50
+ * header. Note that a lone CR needs escaping too, not just CRLF pairs.
51
+ *
52
+ * This is the same escaping the platform's own `FormData` encoder applies, so
53
+ * servers see exactly what they would from any browser or from undici.
54
+ */
55
+ function escapeDispositionValue(value) {
56
+ return value.replace(/"/g, '%22').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
57
+ }
58
+ /**
59
+ * Lays out a `multipart/form-data` payload around a single file part, as the
60
+ * text that goes before and after the file content. Keeping the file content
61
+ * out of it lets the same layout serve both a `Blob` body and a streamed one.
62
+ */
63
+ function layOutMultipart(args) {
64
+ const { fileName, fileContentType, additionalFields } = args;
65
+ const boundary = `----todoist-sdk-${uuidv4()}`;
66
+ const head = `--${boundary}\r\n` +
67
+ `Content-Disposition: form-data; name="file"; filename="${escapeDispositionValue(fileName)}"\r\n` +
68
+ `Content-Type: ${fileContentType}\r\n\r\n`;
69
+ let tail = '\r\n';
70
+ for (const [key, value] of Object.entries(additionalFields)) {
71
+ if (value !== undefined && value !== null) {
72
+ tail +=
73
+ `--${boundary}\r\n` +
74
+ `Content-Disposition: form-data; name="${escapeDispositionValue(key)}"\r\n\r\n` +
75
+ `${value.toString()}\r\n`;
76
+ }
77
+ }
78
+ tail += `--${boundary}--\r\n`;
79
+ return { boundary, head, tail };
80
+ }
81
+ /**
82
+ * Wraps a Node readable stream as a `multipart/form-data` request body.
83
+ *
84
+ * The result is a web `ReadableStream`, which both the runtime's `fetch` and
85
+ * undici's own accept — unlike a Node stream or a `FormData`, either of which
86
+ * only works with one particular client. The file is never buffered, so the
87
+ * request is sent with `Transfer-Encoding: chunked`.
88
+ */
89
+ function streamMultipartBody(file, parts) {
90
+ const encoder = new TextEncoder();
91
+ function chunks() {
92
+ return __asyncGenerator(this, arguments, function* chunks_1() {
93
+ var _a, e_1, _b, _c;
94
+ yield yield __await(encoder.encode(parts.head));
95
+ try {
96
+ for (var _d = true, file_1 = __asyncValues(file), file_1_1; file_1_1 = yield __await(file_1.next()), _a = file_1_1.done, !_a; _d = true) {
97
+ _c = file_1_1.value;
98
+ _d = false;
99
+ const chunk = _c;
100
+ yield yield __await(typeof chunk === 'string' ? encoder.encode(chunk) : new Uint8Array(chunk));
101
+ }
102
+ }
103
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
104
+ finally {
105
+ try {
106
+ if (!_d && !_a && (_b = file_1.return)) yield __await(_b.call(file_1));
107
+ }
108
+ finally { if (e_1) throw e_1.error; }
109
+ }
110
+ yield yield __await(encoder.encode(parts.tail));
111
+ });
112
+ }
113
+ const iterator = chunks();
114
+ // Driven by hand rather than with `ReadableStream.from`, which is absent
115
+ // from this project's DOM lib types and is still missing in some browsers,
116
+ // or `Readable.toWeb`, which would drag a Node-only import into a module
117
+ // that browsers also load.
118
+ return new ReadableStream({
119
+ async pull(controller) {
120
+ const { value, done } = await iterator.next();
121
+ if (done) {
122
+ controller.close();
123
+ return;
124
+ }
125
+ controller.enqueue(value);
126
+ },
127
+ async cancel(reason) {
128
+ var _a;
129
+ await ((_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator, reason));
130
+ },
131
+ });
132
+ }
133
+ /**
134
+ * Builds the request body for a multipart upload.
135
+ *
136
+ * Deliberately avoids `FormData`. A `FormData` body is only encoded by the
137
+ * `fetch` that owns that `FormData` class — undici brands its own — so a body
138
+ * built from the global `FormData` and sent through undici's `fetch`, or the
139
+ * reverse, is stringified to the literal `"[object FormData]"` and the upload
140
+ * silently carries no file. The `form-data` package fares worse: neither
141
+ * `fetch` accepts it as a body at all. `Blob` and `ReadableStream` carry no
142
+ * such brand and work with whichever `fetch` dispatches the request,
143
+ * including a caller-supplied `customFetch`.
144
+ */
145
+ function buildMultipartBody(args) {
146
+ const { file, fileName, fileContentType, additionalFields } = args;
147
+ const parts = layOutMultipart({ fileName, fileContentType, additionalFields });
148
+ const contentType = `multipart/form-data; boundary=${parts.boundary}`;
149
+ if (file instanceof Blob) {
150
+ // A Blob keeps its length, so the request gets a Content-Length and
151
+ // stays replayable if it has to be retried. File-backed Blobs (from
152
+ // `fs.openAsBlob`) stay lazy here, so nothing is read into memory.
153
+ return { body: new Blob([parts.head, file, parts.tail]), contentType, isStreamed: false };
154
+ }
155
+ return { body: streamMultipartBody(file, parts), contentType, isStreamed: true };
156
+ }
26
157
  /**
27
158
  * Uploads a file using multipart/form-data.
28
159
  *
@@ -75,69 +206,52 @@ export async function uploadMultipartFile(args) {
75
206
  if (requestId) {
76
207
  headers['X-Request-Id'] = requestId;
77
208
  }
209
+ // Resolve the file to something every `fetch` accepts as a body part: a
210
+ // Blob where the size is known up front, or a Node stream that gets piped
211
+ // through untouched.
212
+ let filePart;
213
+ let resolvedFileName;
78
214
  if (file instanceof Blob) {
79
- // Browser path: use native FormData
80
- const form = new globalThis.FormData();
81
- const resolvedFileName = fileName || (file instanceof File ? file.name : undefined) || 'upload';
82
- form.append('file', file, resolvedFileName);
83
- for (const [key, value] of Object.entries(additionalFields)) {
84
- if (value !== undefined && value !== null) {
85
- form.append(key, value.toString());
86
- }
215
+ filePart = file;
216
+ resolvedFileName = fileName || (file instanceof File ? file.name : undefined) || 'upload';
217
+ }
218
+ else if (typeof file === 'string') {
219
+ // File path: Node-only, so import lazily to keep browser bundles clean.
220
+ const [fsModule, pathModule] = await Promise.all([import('fs'), import('path')]);
221
+ resolvedFileName = fileName || pathModule.basename(file);
222
+ // `openAsBlob` reads the file lazily, so a large upload is not pulled
223
+ // into memory, and the resulting body still has a known length.
224
+ filePart = await fsModule.openAsBlob(file);
225
+ }
226
+ else if (Buffer.isBuffer(file)) {
227
+ if (!fileName) {
228
+ throw new Error('fileName is required when uploading from a Buffer');
87
229
  }
88
- // Don't set Content-Type — let fetch set it with the correct multipart boundary
89
- body = form;
230
+ resolvedFileName = fileName;
231
+ filePart = new Blob([
232
+ new Uint8Array(file.buffer, file.byteOffset, file.byteLength),
233
+ ]);
90
234
  }
91
235
  else {
92
- // Node path: dynamically import Node-only modules
93
- const [FormDataModule, fsModule, pathModule] = await Promise.all([
94
- import('form-data'),
95
- import('fs'),
96
- import('path'),
97
- ]);
98
- const FormData = FormDataModule.default;
99
- const form = new FormData();
100
- if (typeof file === 'string') {
101
- // File path - create read stream
102
- const resolvedFileName = fileName || pathModule.basename(file);
103
- form.append('file', fsModule.createReadStream(file), resolvedFileName);
104
- }
105
- else if (Buffer.isBuffer(file)) {
106
- // Buffer - require fileName
107
- if (!fileName) {
108
- throw new Error('fileName is required when uploading from a Buffer');
109
- }
110
- const contentType = getContentTypeFromFileName(fileName);
111
- form.append('file', file, {
112
- filename: fileName,
113
- contentType: contentType,
114
- });
115
- }
116
- else {
117
- // Stream - require fileName
118
- if (!fileName) {
119
- throw new Error('fileName is required when uploading from a stream');
120
- }
121
- form.append('file', file, fileName);
236
+ if (!fileName) {
237
+ throw new Error('fileName is required when uploading from a stream');
122
238
  }
123
- for (const [key, value] of Object.entries(additionalFields)) {
124
- if (value !== undefined && value !== null) {
125
- form.append(key, value.toString());
126
- }
127
- }
128
- Object.assign(headers, form.getHeaders());
129
- body = form;
239
+ resolvedFileName = fileName;
240
+ filePart = file;
130
241
  }
131
- // Make the request using fetch
132
- const response = await fetchWithRetry({
133
- url,
134
- options: {
135
- method: 'POST',
136
- body,
137
- headers,
138
- timeout: 30000, // 30 second timeout for file uploads
139
- },
140
- customFetch,
242
+ const multipart = buildMultipartBody({
243
+ file: filePart,
244
+ fileName: resolvedFileName,
245
+ fileContentType: (filePart instanceof Blob ? filePart.type : undefined) ||
246
+ getContentTypeFromFileName(resolvedFileName),
247
+ additionalFields,
141
248
  });
249
+ // The boundary is ours, so Content-Type has to be set explicitly — `fetch`
250
+ // only fills it in for a `FormData` body.
251
+ headers['Content-Type'] = multipart.contentType;
252
+ body = multipart.body;
253
+ // Make the request using fetch
254
+ const response = await fetchWithRetry(Object.assign(Object.assign({ url, options: Object.assign({ method: 'POST', body,
255
+ headers, timeout: 30000 }, (multipart.isStreamed ? { duplex: 'half' } : {})) }, (multipart.isStreamed ? { retryConfig: { retries: 0 } } : {})), { customFetch }));
142
256
  return camelCaseKeys(response.data);
143
257
  }
@@ -2,4 +2,5 @@ export * from './todoist-api.js';
2
2
  export * from './authentication.js';
3
3
  export * from './types/index.js';
4
4
  export * from './utils/index.js';
5
- export { getDefaultDispatcher } from './transport/http-dispatcher.js';
5
+ export { getDefaultDispatcher, getDefaultTransport } from './transport/http-dispatcher.js';
6
+ export type { DefaultTransport } from './transport/http-dispatcher.js';
@@ -7,7 +7,7 @@ type UndiciFetch = typeof import('undici').fetch;
7
7
  * never observe a dispatcher paired with a mismatched `fetch` — see
8
8
  * {@link getDefaultFetch} for why the pairing matters.
9
9
  */
10
- type DefaultTransport = {
10
+ export type DefaultTransport = {
11
11
  dispatcher: Dispatcher;
12
12
  fetch: UndiciFetch | undefined;
13
13
  };
@@ -15,8 +15,33 @@ type DefaultTransport = {
15
15
  * The default dispatcher and its paired `fetch`, as a single value so the two
16
16
  * are always read consistently. Resolves to `undefined` outside Node (browser/
17
17
  * edge), where callers use the global `fetch` with no dispatcher.
18
+ *
19
+ * Use this when supplying a `customFetch` that should still honour the proxy
20
+ * environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) and decode
21
+ * compressed responses the way the SDK does by default.
22
+ *
23
+ * Both halves must be used together. `dispatcher` decompresses the response
24
+ * body itself, so a `fetch` from a different undici build will try to decode
25
+ * it a second time and the request fails mid-stream with `terminated`. A
26
+ * `fetch` of `undefined` means the runtime's global `fetch` is the correct
27
+ * partner for this dispatcher.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const transport = await getDefaultTransport()
32
+ * const fetchImpl = transport?.fetch ?? fetch
33
+ * const response = await fetchImpl(url, { ...options, dispatcher: transport?.dispatcher })
34
+ * ```
18
35
  */
19
36
  export declare function getDefaultTransport(): Promise<DefaultTransport | undefined>;
37
+ /**
38
+ * The default dispatcher on its own.
39
+ *
40
+ * @deprecated Use {@link getDefaultTransport} instead, which returns this
41
+ * dispatcher together with the `fetch` it must be used with. Attaching this
42
+ * dispatcher to the runtime's global `fetch` decodes compressed responses
43
+ * twice on Node 26 and the request fails with `terminated`.
44
+ */
20
45
  export declare function getDefaultDispatcher(): Promise<Dispatcher | undefined>;
21
46
  /**
22
47
  * The `fetch` implementation that must be used with the default dispatcher.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doist/todoist-sdk",
3
- "version": "14.1.0",
3
+ "version": "14.2.0",
4
4
  "description": "The official TypeScript SDK for the Todoist REST API.",
5
5
  "author": "Doist developers",
6
6
  "repository": "https://github.com/Doist/todoist-sdk-typescript",
@@ -53,9 +53,8 @@
53
53
  "dependencies": {
54
54
  "camelcase": "6.3.0",
55
55
  "emoji-regex": "10.6.0",
56
- "form-data": "4.0.6",
57
56
  "ts-custom-error": "^3.2.0",
58
- "undici": "7.24.8",
57
+ "undici": "^7.29.0",
59
58
  "uuid": "11.1.1",
60
59
  "zod": "4.3.6"
61
60
  },