@zero-server/sdk 0.9.1 → 0.9.3

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.
Files changed (128) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/body.d.ts +14 -0
  113. package/types/cli.d.ts +2 -0
  114. package/types/cluster.d.ts +75 -75
  115. package/types/env.d.ts +80 -80
  116. package/types/errors.d.ts +316 -316
  117. package/types/fetch.d.ts +43 -43
  118. package/types/grpc.d.ts +432 -432
  119. package/types/index.d.ts +384 -384
  120. package/types/lifecycle.d.ts +60 -60
  121. package/types/middleware.d.ts +320 -320
  122. package/types/observe.d.ts +304 -304
  123. package/types/orm.d.ts +1887 -1887
  124. package/types/request.d.ts +109 -109
  125. package/types/response.d.ts +157 -157
  126. package/types/router.d.ts +78 -78
  127. package/types/sse.d.ts +78 -78
  128. package/types/websocket.d.ts +126 -126
@@ -1,256 +1,256 @@
1
- /**
2
- * @module fetch
3
- * @description Minimal, zero-dependency server-side `fetch()` replacement.
4
- * Supports HTTP/HTTPS, JSON/URLSearchParams/Buffer/stream bodies,
5
- * download & upload progress callbacks, timeouts, and AbortSignal.
6
- */
7
- const http = require('http');
8
- const https = require('https');
9
- const { URL } = require('url');
10
-
11
- const STATUS_CODES = http.STATUS_CODES;
12
-
13
- /**
14
- * Perform an HTTP(S) request.
15
- *
16
- * @param {string} url - Absolute URL to fetch.
17
- * @param {object} [opts] - Configuration options.
18
- * @param {string} [opts.method='GET'] - HTTP method.
19
- * @param {object} [opts.headers] - Request headers.
20
- * @param {string|Buffer|object|ReadableStream} [opts.body] - Request body.
21
- * @param {number} [opts.timeout] - Request timeout in ms.
22
- * @param {AbortSignal} [opts.signal] - Abort signal for cancellation.
23
- * @param {import('http').Agent} [opts.agent] - Custom HTTP agent.
24
- * @param {Function} [opts.onDownloadProgress] - `({ loaded, total }) => void` download progress callback.
25
- * @param {Function} [opts.onUploadProgress] - `({ loaded, total }) => void` upload progress callback.
26
- * @param {boolean} [opts.rejectUnauthorized] - Reject connections with unverified certs (default: Node default `true`). TLS option — passed to `https.request()`.
27
- * @param {string|Buffer|Array} [opts.ca] - Override default CA certificates.
28
- * @param {string|Buffer} [opts.cert] - Client certificate (PEM) for mutual TLS.
29
- * @param {string|Buffer} [opts.key] - Private key (PEM) for mutual TLS.
30
- * @param {string|Buffer} [opts.pfx] - PFX / PKCS12 bundle (alternative to cert+key).
31
- * @param {string} [opts.passphrase] - Passphrase for the key or PFX.
32
- * @param {string} [opts.servername] - SNI server name override.
33
- * @param {string} [opts.ciphers] - Colon-separated cipher list.
34
- * @param {string} [opts.secureProtocol] - SSL/TLS protocol method name.
35
- * @param {string} [opts.minVersion] - Minimum TLS version (`'TLSv1.2'`, etc.).
36
- * @param {string} [opts.maxVersion] - Maximum TLS version.
37
- *
38
- * @returns {Promise<{ status: number, statusText: string, ok: boolean, secure: boolean, url: string, headers: object, arrayBuffer: Function, text: Function, json: Function }>} Resolves with a response object containing status info, headers, and body-reading helpers (`text()`, `json()`, `arrayBuffer()`).
39
- *
40
- * @example
41
- * const res = await fetch('https://api.example.com/data');
42
- * const body = await res.json();
43
- *
44
- * // POST with JSON body & timeout
45
- * const res2 = await fetch('https://api.example.com/items', {
46
- * method: 'POST',
47
- * body: { name: 'widget' },
48
- * timeout: 5000,
49
- * });
50
- */
51
- function miniFetch(url, opts = {})
52
- {
53
- return new Promise((resolve, reject) =>
54
- {
55
- try
56
- {
57
- const u = new URL(url);
58
- const lib = u.protocol === 'https:' ? https : http;
59
- const method = (opts.method || 'GET').toUpperCase();
60
- const headers = Object.assign({}, opts.headers || {});
61
-
62
- // Normalize body
63
- let body = opts.body;
64
- if (body && typeof body === 'object' && typeof body.toString === 'function' && body.constructor && body.constructor.name === 'URLSearchParams')
65
- {
66
- if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded';
67
- body = body.toString();
68
- }
69
- else if (body && typeof body === 'object' && !Buffer.isBuffer(body) && !(body instanceof ArrayBuffer) && !(body instanceof Uint8Array) && !(body && typeof body.pipe === 'function'))
70
- {
71
- if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/json';
72
- body = Buffer.from(JSON.stringify(body), 'utf8');
73
- }
74
- else if (body instanceof ArrayBuffer)
75
- {
76
- body = Buffer.from(body);
77
- }
78
- else if (body instanceof Uint8Array && !Buffer.isBuffer(body))
79
- {
80
- body = Buffer.from(body);
81
- }
82
-
83
- // Set Content-Length for known-size bodies
84
- if ((Buffer.isBuffer(body) || typeof body === 'string') && !headers['Content-Length'] && !headers['content-length'])
85
- {
86
- headers['Content-Length'] = String(Buffer.isBuffer(body) ? body.length : Buffer.byteLength(body));
87
- }
88
-
89
- const options = { method, headers };
90
- if (opts.agent) options.agent = opts.agent;
91
-
92
- // Pass through TLS options for HTTPS requests
93
- if (lib === https)
94
- {
95
- const tlsKeys = [
96
- 'rejectUnauthorized', 'ca', 'cert', 'key', 'pfx', 'passphrase',
97
- 'servername', 'ciphers', 'secureProtocol', 'minVersion', 'maxVersion'
98
- ];
99
- for (const k of tlsKeys)
100
- {
101
- if (opts[k] !== undefined) options[k] = opts[k];
102
- }
103
- }
104
-
105
- const req = lib.request(u, options, (res) =>
106
- {
107
- const chunks = [];
108
- let downloaded = 0;
109
- const total = parseInt(res.headers['content-length'] || '0', 10) || null;
110
-
111
- res.on('data', (c) =>
112
- {
113
- chunks.push(c);
114
- downloaded += c.length;
115
- if (typeof opts.onDownloadProgress === 'function')
116
- {
117
- try { opts.onDownloadProgress({ loaded: downloaded, total }); } catch (e) { }
118
- }
119
- });
120
-
121
- res.on('end', () =>
122
- {
123
- const buf = Buffer.concat(chunks);
124
- const status = res.statusCode;
125
- const rawHeaders = res.headers || {};
126
- const responseHeaders = {
127
- get(name)
128
- {
129
- if (!name) return undefined;
130
- const v = rawHeaders[name.toLowerCase()];
131
- return Array.isArray(v) ? v.join(', ') : v;
132
- },
133
- raw: rawHeaders,
134
- };
135
-
136
- resolve({
137
- status,
138
- statusText: STATUS_CODES[status] || '',
139
- ok: status >= 200 && status < 300,
140
- secure: u.protocol === 'https:',
141
- url: u.href,
142
- headers: responseHeaders,
143
- arrayBuffer: () => Promise.resolve(buf),
144
- text: () => Promise.resolve(buf.toString('utf8')),
145
- json: () =>
146
- {
147
- try { return Promise.resolve(JSON.parse(buf.toString('utf8'))); }
148
- catch (e) { return Promise.reject(e); }
149
- },
150
- });
151
- });
152
- });
153
-
154
- req.on('error', reject);
155
-
156
- // Timeout
157
- if (typeof opts.timeout === 'number' && opts.timeout > 0)
158
- {
159
- req.setTimeout(opts.timeout, () =>
160
- {
161
- const err = new Error('Request timed out');
162
- err.code = 'ETIMEOUT';
163
- req.destroy(err);
164
- });
165
- }
166
-
167
- // AbortSignal support
168
- let abortHandler;
169
- if (opts.signal)
170
- {
171
- if (opts.signal.aborted)
172
- {
173
- const err = new Error('Request aborted');
174
- err.name = 'AbortError';
175
- req.destroy(err);
176
- return;
177
- }
178
- abortHandler = () =>
179
- {
180
- const err = new Error('Request aborted');
181
- err.name = 'AbortError';
182
- req.destroy(err);
183
- };
184
- if (typeof opts.signal.addEventListener === 'function') opts.signal.addEventListener('abort', abortHandler);
185
- else if (typeof opts.signal.on === 'function') opts.signal.on('abort', abortHandler);
186
- }
187
-
188
- // Cleanup signal listener
189
- const cleanup = () =>
190
- {
191
- if (opts.signal && abortHandler)
192
- {
193
- try
194
- {
195
- if (typeof opts.signal.removeEventListener === 'function') opts.signal.removeEventListener('abort', abortHandler);
196
- else if (typeof opts.signal.off === 'function') opts.signal.off('abort', abortHandler);
197
- }
198
- catch (e) { }
199
- }
200
- };
201
- req.on('close', cleanup);
202
-
203
- // Write body
204
- if (body && typeof body.pipe === 'function')
205
- {
206
- let uploaded = 0;
207
- body.on('data', (chunk) =>
208
- {
209
- uploaded += chunk.length;
210
- if (typeof opts.onUploadProgress === 'function')
211
- {
212
- try { opts.onUploadProgress({ loaded: uploaded, total: headers['Content-Length'] ? Number(headers['Content-Length']) : null }); } catch (e) { }
213
- }
214
- });
215
- body.on('error', (err) => req.destroy(err));
216
- body.pipe(req);
217
- }
218
- else if (Buffer.isBuffer(body) || typeof body === 'string')
219
- {
220
- const buf = Buffer.isBuffer(body) ? body : Buffer.from(body);
221
- const total = buf.length;
222
- const CHUNK = 64 * 1024;
223
- let sent = 0;
224
-
225
- function writeNext()
226
- {
227
- if (sent >= total) { req.end(); return; }
228
- const slice = buf.slice(sent, Math.min(sent + CHUNK, total));
229
- const ok = req.write(slice, () =>
230
- {
231
- sent += slice.length;
232
- if (typeof opts.onUploadProgress === 'function')
233
- {
234
- try { opts.onUploadProgress({ loaded: sent, total }); } catch (e) { }
235
- }
236
- writeNext();
237
- });
238
- if (!ok) req.once('drain', writeNext);
239
- }
240
- writeNext();
241
- }
242
- else if (body == null)
243
- {
244
- req.end();
245
- }
246
- else
247
- {
248
- req.write(String(body));
249
- req.end();
250
- }
251
- }
252
- catch (e) { reject(e); }
253
- });
254
- }
255
-
256
- module.exports = miniFetch;
1
+ /**
2
+ * @module fetch
3
+ * @description Minimal, zero-dependency server-side `fetch()` replacement.
4
+ * Supports HTTP/HTTPS, JSON/URLSearchParams/Buffer/stream bodies,
5
+ * download & upload progress callbacks, timeouts, and AbortSignal.
6
+ */
7
+ const http = require('http');
8
+ const https = require('https');
9
+ const { URL } = require('url');
10
+
11
+ const STATUS_CODES = http.STATUS_CODES;
12
+
13
+ /**
14
+ * Perform an HTTP(S) request.
15
+ *
16
+ * @param {string} url - Absolute URL to fetch.
17
+ * @param {object} [opts] - Configuration options.
18
+ * @param {string} [opts.method='GET'] - HTTP method.
19
+ * @param {object} [opts.headers] - Request headers.
20
+ * @param {string|Buffer|object|ReadableStream} [opts.body] - Request body.
21
+ * @param {number} [opts.timeout] - Request timeout in ms.
22
+ * @param {AbortSignal} [opts.signal] - Abort signal for cancellation.
23
+ * @param {import('http').Agent} [opts.agent] - Custom HTTP agent.
24
+ * @param {Function} [opts.onDownloadProgress] - `({ loaded, total }) => void` download progress callback.
25
+ * @param {Function} [opts.onUploadProgress] - `({ loaded, total }) => void` upload progress callback.
26
+ * @param {boolean} [opts.rejectUnauthorized] - Reject connections with unverified certs (default: Node default `true`). TLS option — passed to `https.request()`.
27
+ * @param {string|Buffer|Array} [opts.ca] - Override default CA certificates.
28
+ * @param {string|Buffer} [opts.cert] - Client certificate (PEM) for mutual TLS.
29
+ * @param {string|Buffer} [opts.key] - Private key (PEM) for mutual TLS.
30
+ * @param {string|Buffer} [opts.pfx] - PFX / PKCS12 bundle (alternative to cert+key).
31
+ * @param {string} [opts.passphrase] - Passphrase for the key or PFX.
32
+ * @param {string} [opts.servername] - SNI server name override.
33
+ * @param {string} [opts.ciphers] - Colon-separated cipher list.
34
+ * @param {string} [opts.secureProtocol] - SSL/TLS protocol method name.
35
+ * @param {string} [opts.minVersion] - Minimum TLS version (`'TLSv1.2'`, etc.).
36
+ * @param {string} [opts.maxVersion] - Maximum TLS version.
37
+ *
38
+ * @returns {Promise<{ status: number, statusText: string, ok: boolean, secure: boolean, url: string, headers: object, arrayBuffer: Function, text: Function, json: Function }>} Resolves with a response object containing status info, headers, and body-reading helpers (`text()`, `json()`, `arrayBuffer()`).
39
+ *
40
+ * @example
41
+ * const res = await fetch('https://api.example.com/data');
42
+ * const body = await res.json();
43
+ *
44
+ * // POST with JSON body & timeout
45
+ * const res2 = await fetch('https://api.example.com/items', {
46
+ * method: 'POST',
47
+ * body: { name: 'widget' },
48
+ * timeout: 5000,
49
+ * });
50
+ */
51
+ function miniFetch(url, opts = {})
52
+ {
53
+ return new Promise((resolve, reject) =>
54
+ {
55
+ try
56
+ {
57
+ const u = new URL(url);
58
+ const lib = u.protocol === 'https:' ? https : http;
59
+ const method = (opts.method || 'GET').toUpperCase();
60
+ const headers = Object.assign({}, opts.headers || {});
61
+
62
+ // Normalize body
63
+ let body = opts.body;
64
+ if (body && typeof body === 'object' && typeof body.toString === 'function' && body.constructor && body.constructor.name === 'URLSearchParams')
65
+ {
66
+ if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded';
67
+ body = body.toString();
68
+ }
69
+ else if (body && typeof body === 'object' && !Buffer.isBuffer(body) && !(body instanceof ArrayBuffer) && !(body instanceof Uint8Array) && !(body && typeof body.pipe === 'function'))
70
+ {
71
+ if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/json';
72
+ body = Buffer.from(JSON.stringify(body), 'utf8');
73
+ }
74
+ else if (body instanceof ArrayBuffer)
75
+ {
76
+ body = Buffer.from(body);
77
+ }
78
+ else if (body instanceof Uint8Array && !Buffer.isBuffer(body))
79
+ {
80
+ body = Buffer.from(body);
81
+ }
82
+
83
+ // Set Content-Length for known-size bodies
84
+ if ((Buffer.isBuffer(body) || typeof body === 'string') && !headers['Content-Length'] && !headers['content-length'])
85
+ {
86
+ headers['Content-Length'] = String(Buffer.isBuffer(body) ? body.length : Buffer.byteLength(body));
87
+ }
88
+
89
+ const options = { method, headers };
90
+ if (opts.agent) options.agent = opts.agent;
91
+
92
+ // Pass through TLS options for HTTPS requests
93
+ if (lib === https)
94
+ {
95
+ const tlsKeys = [
96
+ 'rejectUnauthorized', 'ca', 'cert', 'key', 'pfx', 'passphrase',
97
+ 'servername', 'ciphers', 'secureProtocol', 'minVersion', 'maxVersion'
98
+ ];
99
+ for (const k of tlsKeys)
100
+ {
101
+ if (opts[k] !== undefined) options[k] = opts[k];
102
+ }
103
+ }
104
+
105
+ const req = lib.request(u, options, (res) =>
106
+ {
107
+ const chunks = [];
108
+ let downloaded = 0;
109
+ const total = parseInt(res.headers['content-length'] || '0', 10) || null;
110
+
111
+ res.on('data', (c) =>
112
+ {
113
+ chunks.push(c);
114
+ downloaded += c.length;
115
+ if (typeof opts.onDownloadProgress === 'function')
116
+ {
117
+ try { opts.onDownloadProgress({ loaded: downloaded, total }); } catch (e) { }
118
+ }
119
+ });
120
+
121
+ res.on('end', () =>
122
+ {
123
+ const buf = Buffer.concat(chunks);
124
+ const status = res.statusCode;
125
+ const rawHeaders = res.headers || {};
126
+ const responseHeaders = {
127
+ get(name)
128
+ {
129
+ if (!name) return undefined;
130
+ const v = rawHeaders[name.toLowerCase()];
131
+ return Array.isArray(v) ? v.join(', ') : v;
132
+ },
133
+ raw: rawHeaders,
134
+ };
135
+
136
+ resolve({
137
+ status,
138
+ statusText: STATUS_CODES[status] || '',
139
+ ok: status >= 200 && status < 300,
140
+ secure: u.protocol === 'https:',
141
+ url: u.href,
142
+ headers: responseHeaders,
143
+ arrayBuffer: () => Promise.resolve(buf),
144
+ text: () => Promise.resolve(buf.toString('utf8')),
145
+ json: () =>
146
+ {
147
+ try { return Promise.resolve(JSON.parse(buf.toString('utf8'))); }
148
+ catch (e) { return Promise.reject(e); }
149
+ },
150
+ });
151
+ });
152
+ });
153
+
154
+ req.on('error', reject);
155
+
156
+ // Timeout
157
+ if (typeof opts.timeout === 'number' && opts.timeout > 0)
158
+ {
159
+ req.setTimeout(opts.timeout, () =>
160
+ {
161
+ const err = new Error('Request timed out');
162
+ err.code = 'ETIMEOUT';
163
+ req.destroy(err);
164
+ });
165
+ }
166
+
167
+ // AbortSignal support
168
+ let abortHandler;
169
+ if (opts.signal)
170
+ {
171
+ if (opts.signal.aborted)
172
+ {
173
+ const err = new Error('Request aborted');
174
+ err.name = 'AbortError';
175
+ req.destroy(err);
176
+ return;
177
+ }
178
+ abortHandler = () =>
179
+ {
180
+ const err = new Error('Request aborted');
181
+ err.name = 'AbortError';
182
+ req.destroy(err);
183
+ };
184
+ if (typeof opts.signal.addEventListener === 'function') opts.signal.addEventListener('abort', abortHandler);
185
+ else if (typeof opts.signal.on === 'function') opts.signal.on('abort', abortHandler);
186
+ }
187
+
188
+ // Cleanup signal listener
189
+ const cleanup = () =>
190
+ {
191
+ if (opts.signal && abortHandler)
192
+ {
193
+ try
194
+ {
195
+ if (typeof opts.signal.removeEventListener === 'function') opts.signal.removeEventListener('abort', abortHandler);
196
+ else if (typeof opts.signal.off === 'function') opts.signal.off('abort', abortHandler);
197
+ }
198
+ catch (e) { }
199
+ }
200
+ };
201
+ req.on('close', cleanup);
202
+
203
+ // Write body
204
+ if (body && typeof body.pipe === 'function')
205
+ {
206
+ let uploaded = 0;
207
+ body.on('data', (chunk) =>
208
+ {
209
+ uploaded += chunk.length;
210
+ if (typeof opts.onUploadProgress === 'function')
211
+ {
212
+ try { opts.onUploadProgress({ loaded: uploaded, total: headers['Content-Length'] ? Number(headers['Content-Length']) : null }); } catch (e) { }
213
+ }
214
+ });
215
+ body.on('error', (err) => req.destroy(err));
216
+ body.pipe(req);
217
+ }
218
+ else if (Buffer.isBuffer(body) || typeof body === 'string')
219
+ {
220
+ const buf = Buffer.isBuffer(body) ? body : Buffer.from(body);
221
+ const total = buf.length;
222
+ const CHUNK = 64 * 1024;
223
+ let sent = 0;
224
+
225
+ function writeNext()
226
+ {
227
+ if (sent >= total) { req.end(); return; }
228
+ const slice = buf.slice(sent, Math.min(sent + CHUNK, total));
229
+ const ok = req.write(slice, () =>
230
+ {
231
+ sent += slice.length;
232
+ if (typeof opts.onUploadProgress === 'function')
233
+ {
234
+ try { opts.onUploadProgress({ loaded: sent, total }); } catch (e) { }
235
+ }
236
+ writeNext();
237
+ });
238
+ if (!ok) req.once('drain', writeNext);
239
+ }
240
+ writeNext();
241
+ }
242
+ else if (body == null)
243
+ {
244
+ req.end();
245
+ }
246
+ else
247
+ {
248
+ req.write(String(body));
249
+ req.end();
250
+ }
251
+ }
252
+ catch (e) { reject(e); }
253
+ });
254
+ }
255
+
256
+ module.exports = miniFetch;