@blamejs/core 0.4.23 → 0.4.24

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/CHANGELOG.md CHANGED
@@ -8,6 +8,7 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.4.x
10
10
 
11
+ - **0.4.23** (2026-04-30) — b.mail.dkim signing + calendar invites
11
12
  - **0.4.22** (2026-04-30) — b.mail attachments + inline images + plain/HTML alternatives
12
13
  - **0.4.21** (2026-04-30) — b.queue: repeat-in-queue (cron) + parent-child Flows
13
14
  - **0.4.20** (2026-04-30) — b.queue + b.jobs: priority, rate-limit, progress
@@ -208,6 +208,135 @@ function _request(method, url, headers, body, opts) {
208
208
  });
209
209
  }
210
210
 
211
+ // ---- Multipart-upload constants ----
212
+
213
+ // S3 spec floor for non-final part size. Below this the API rejects
214
+ // CompleteMultipartUpload with EntityTooSmall. The framework refuses
215
+ // configurations below this floor at create() time so operators don't
216
+ // see surprising failures only on large uploads.
217
+ var MIN_PART_SIZE_BYTES = 5 * 1024 * 1024;
218
+ // S3 spec ceiling on part count. CompleteMultipartUpload rejects
219
+ // uploads with more than 10000 parts.
220
+ var MAX_PARTS = 10000;
221
+ // Auto-multipart trigger: buffered bodies under this stay single-PUT.
222
+ // Streams always go multipart since size isn't known up-front.
223
+ var DEFAULT_MULTIPART_THRESHOLD_BYTES = 64 * 1024 * 1024;
224
+ // Conservative default part size — large enough to keep round-trip
225
+ // overhead small relative to payload, small enough to fit comfortably
226
+ // in a 4-way-concurrent upload's memory footprint.
227
+ var DEFAULT_PART_SIZE_BYTES = 16 * 1024 * 1024;
228
+ var DEFAULT_PART_CONCURRENCY = 4;
229
+
230
+ // ---- SSE option handling ----
231
+
232
+ function _resolveSseHeaders(sse) {
233
+ if (sse === undefined || sse === null) return null;
234
+ var type;
235
+ var keyId = null;
236
+ if (typeof sse === "string") {
237
+ type = sse;
238
+ } else if (sse && typeof sse === "object") {
239
+ type = sse.type;
240
+ keyId = sse.keyId || null;
241
+ } else {
242
+ throw _err("INVALID_SSE",
243
+ "opts.sse must be a string ('AES256' | 'aws:kms') or " +
244
+ "{ type, keyId }, got " + typeof sse, true);
245
+ }
246
+ if (type !== "AES256" && type !== "aws:kms") {
247
+ throw _err("INVALID_SSE",
248
+ "opts.sse type must be 'AES256' or 'aws:kms', got '" + type + "'", true);
249
+ }
250
+ var h = { "x-amz-server-side-encryption": type };
251
+ if (type === "aws:kms" && keyId) {
252
+ h["x-amz-server-side-encryption-aws-kms-key-id"] = String(keyId);
253
+ }
254
+ return { type: type, keyId: keyId, headers: h };
255
+ }
256
+
257
+ function _verifySseResponse(sseRequested, resHeaders) {
258
+ // Operators who specified an SSE policy expect the bucket / object to
259
+ // honor it. If the server silently dropped the header (mis-configured
260
+ // bucket policy, unsupported endpoint, etc.) the request looks like a
261
+ // success but the at-rest data is unencrypted. Surface this as a
262
+ // hard failure rather than a silent compliance hole.
263
+ if (!sseRequested) return;
264
+ var got = resHeaders["x-amz-server-side-encryption"];
265
+ if (!got) {
266
+ throw _err("SSE_NOT_APPLIED",
267
+ "opts.sse was '" + sseRequested.type + "' but server did not " +
268
+ "apply server-side encryption (no x-amz-server-side-encryption " +
269
+ "response header)", true);
270
+ }
271
+ if (got !== sseRequested.type) {
272
+ throw _err("SSE_MISMATCH",
273
+ "opts.sse requested '" + sseRequested.type + "' but server " +
274
+ "applied '" + got + "'", true);
275
+ }
276
+ }
277
+
278
+ // ---- Multipart helpers ----
279
+
280
+ // Build the CompleteMultipartUpload request body. Parts must be in
281
+ // ascending PartNumber order. ETags from S3 include surrounding
282
+ // quotes — preserve them exactly.
283
+ function _buildCompleteMultipartXml(parts) {
284
+ var body = "<CompleteMultipartUpload>";
285
+ for (var i = 0; i < parts.length; i++) {
286
+ body += "<Part>";
287
+ body += "<PartNumber>" + parts[i].partNumber + "</PartNumber>";
288
+ body += "<ETag>" + parts[i].etag + "</ETag>";
289
+ body += "</Part>";
290
+ }
291
+ body += "</CompleteMultipartUpload>";
292
+ return body;
293
+ }
294
+
295
+ // Read a Readable stream into fixed-size buffers. Yields one Buffer
296
+ // per part (size <= partSize). The final part may be smaller. The
297
+ // stream is consumed exactly once.
298
+ async function _readStreamParts(readable, partSize) {
299
+ var parts = [];
300
+ var pending = [];
301
+ var pendingBytes = 0;
302
+ for await (var chunk of readable) {
303
+ var buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
304
+ pending.push(buf);
305
+ pendingBytes += buf.length;
306
+ while (pendingBytes >= partSize) {
307
+ var combined = Buffer.concat(pending, pendingBytes);
308
+ parts.push(combined.slice(0, partSize));
309
+ var leftover = combined.slice(partSize);
310
+ pending = leftover.length > 0 ? [leftover] : [];
311
+ pendingBytes = leftover.length;
312
+ }
313
+ }
314
+ if (pendingBytes > 0) {
315
+ parts.push(Buffer.concat(pending, pendingBytes));
316
+ }
317
+ return parts;
318
+ }
319
+
320
+ // Run an array of async tasks with bounded parallelism. Preserves
321
+ // result order by index.
322
+ async function _bounded(items, concurrency, runner) {
323
+ var results = new Array(items.length);
324
+ var i = 0;
325
+ async function worker() {
326
+ while (true) {
327
+ var idx = i++;
328
+ if (idx >= items.length) return;
329
+ results[idx] = await runner(items[idx], idx);
330
+ }
331
+ }
332
+ var workers = [];
333
+ for (var w = 0; w < Math.min(concurrency, items.length); w++) {
334
+ workers.push(worker());
335
+ }
336
+ await Promise.all(workers);
337
+ return results;
338
+ }
339
+
211
340
  // ---- Public adapter factory ----
212
341
 
213
342
  function create(config) {
@@ -220,6 +349,30 @@ function create(config) {
220
349
  var endpoint = config.endpoint || ("https://s3." + config.region + ".amazonaws.com");
221
350
  if (endpoint.endsWith("/")) endpoint = endpoint.slice(0, -1);
222
351
  var pathStyle = !!(config.pathStyle || config.forcePathStyle);
352
+
353
+ var partSize = config.partSizeBytes != null
354
+ ? config.partSizeBytes
355
+ : DEFAULT_PART_SIZE_BYTES;
356
+ if (typeof partSize !== "number" || !isFinite(partSize) || partSize < MIN_PART_SIZE_BYTES) {
357
+ throw _err("INVALID_CONFIG",
358
+ "sigv4: partSizeBytes must be a number >= " + MIN_PART_SIZE_BYTES +
359
+ " (S3 minimum part size), got " + partSize, true);
360
+ }
361
+ var multipartThreshold = config.multipartThresholdBytes != null
362
+ ? config.multipartThresholdBytes
363
+ : DEFAULT_MULTIPART_THRESHOLD_BYTES;
364
+ if (typeof multipartThreshold !== "number" || !isFinite(multipartThreshold) || multipartThreshold < 0) {
365
+ throw _err("INVALID_CONFIG",
366
+ "sigv4: multipartThresholdBytes must be a non-negative finite number, got " +
367
+ multipartThreshold, true);
368
+ }
369
+ var partConcurrency = config.partConcurrency != null
370
+ ? config.partConcurrency
371
+ : DEFAULT_PART_CONCURRENCY;
372
+ if (typeof partConcurrency !== "number" || partConcurrency < 1 || !isFinite(partConcurrency)) {
373
+ throw _err("INVALID_CONFIG",
374
+ "sigv4: partConcurrency must be a positive finite number, got " + partConcurrency, true);
375
+ }
223
376
  // HTTPS-only by default — AWS S3, R2, MinIO-over-https. Operators with
224
377
  // an internal cleartext S3-compatible endpoint (test fixtures, local
225
378
  // dev MinIO) opt in via config.allowedProtocols.
@@ -274,19 +427,150 @@ function create(config) {
274
427
  }
275
428
 
276
429
  function put(key, body, opts) {
277
- var url = _keyToUrl(key);
430
+ opts = opts || {};
431
+ var sseRequested = _resolveSseHeaders(opts.sse);
432
+ // Streams always go multipart — size isn't known up-front. Buffers
433
+ // dispatch to multipart when they exceed the threshold; operators
434
+ // can force the single-PUT path with `multipart: false` (small
435
+ // bodies in unit tests, or to keep the request count to one).
436
+ var isStream = body && typeof body === "object" && typeof body.pipe === "function";
437
+ if (isStream) {
438
+ if (opts.multipart === false) {
439
+ return Promise.reject(_err("STREAM_REQUIRES_MULTIPART",
440
+ "put(stream) requires multipart upload (set opts.multipart !== false)", true));
441
+ }
442
+ return _multipartPut(key, body, opts, sseRequested);
443
+ }
278
444
  var buf = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : "", "utf8");
445
+ if (opts.multipart !== false &&
446
+ (opts.multipart === true || buf.length > multipartThreshold)) {
447
+ return _multipartPut(key, buf, opts, sseRequested);
448
+ }
449
+ return _singlePut(key, buf, opts, sseRequested);
450
+ }
451
+
452
+ function _singlePut(key, buf, opts, sseRequested) {
453
+ var url = _keyToUrl(key);
279
454
  var payloadHash = sha256Hex(buf);
280
- var contentType = (opts && opts.contentType) || "application/octet-stream";
281
- var headers = _makeSigned("PUT", url, payloadHash, {
455
+ var contentType = opts.contentType || "application/octet-stream";
456
+ var extra = {
282
457
  "Content-Type": contentType,
283
458
  "Content-Length": String(buf.length),
284
- });
459
+ };
460
+ if (sseRequested) Object.assign(extra, sseRequested.headers);
461
+ var headers = _makeSigned("PUT", url, payloadHash, extra);
285
462
  return _request("PUT", url, headers, buf, reqOpts).then(function (res) {
463
+ _verifySseResponse(sseRequested, res.headers);
286
464
  return { size: buf.length, etag: res.headers.etag };
287
465
  });
288
466
  }
289
467
 
468
+ async function _multipartPut(key, body, opts, sseRequested) {
469
+ var contentType = opts.contentType || "application/octet-stream";
470
+
471
+ // Slice into parts. For Buffers we slice up-front; for streams we
472
+ // read sequentially into part-sized buffers (memory bounded).
473
+ var parts;
474
+ if (Buffer.isBuffer(body)) {
475
+ parts = [];
476
+ for (var off = 0; off < body.length; off += partSize) {
477
+ parts.push(body.slice(off, Math.min(off + partSize, body.length)));
478
+ }
479
+ // Edge case: empty buffer → one zero-length part. S3 rejects
480
+ // multipart with zero parts; rather than handling this corner
481
+ // we route empty buffers through single-PUT instead.
482
+ if (parts.length === 0) parts = [Buffer.alloc(0)];
483
+ } else {
484
+ parts = await _readStreamParts(body, partSize);
485
+ if (parts.length === 0) parts = [Buffer.alloc(0)];
486
+ }
487
+ if (parts.length > MAX_PARTS) {
488
+ throw _err("TOO_MANY_PARTS",
489
+ "multipart upload would require " + parts.length + " parts " +
490
+ "(S3 max " + MAX_PARTS + "); increase partSizeBytes", true);
491
+ }
492
+
493
+ // 1. Initiate
494
+ var url = _keyToUrl(key);
495
+ var initiateUrl = new URL(url.href);
496
+ initiateUrl.searchParams.set("uploads", "");
497
+ var initiateExtra = {
498
+ "Content-Type": contentType,
499
+ "Content-Length": "0",
500
+ };
501
+ if (sseRequested) Object.assign(initiateExtra, sseRequested.headers);
502
+ var initiateHeaders = _makeSigned("POST", initiateUrl, sha256Hex(Buffer.alloc(0)), initiateExtra);
503
+ var initRes = await _request("POST", initiateUrl, initiateHeaders, Buffer.alloc(0), reqOpts);
504
+ _verifySseResponse(sseRequested, initRes.headers);
505
+ var initDoc = safeXml.parse(initRes.body, LIST_PARSE_OPTS);
506
+ var uploadId = initDoc.InitiateMultipartUploadResult &&
507
+ initDoc.InitiateMultipartUploadResult.UploadId;
508
+ if (!uploadId) {
509
+ throw _err("MULTIPART_INIT_FAILED",
510
+ "S3 InitiateMultipartUpload response missing UploadId", false);
511
+ }
512
+
513
+ var totalSize = 0;
514
+ var uploadedEtags;
515
+
516
+ try {
517
+ // 2. Upload parts (concurrency-bounded)
518
+ uploadedEtags = await _bounded(parts, partConcurrency, async function (partBuf, idx) {
519
+ var partNumber = idx + 1;
520
+ var partUrl = new URL(url.href);
521
+ partUrl.searchParams.set("partNumber", String(partNumber));
522
+ partUrl.searchParams.set("uploadId", uploadId);
523
+ var partHeaders = _makeSigned("PUT", partUrl, sha256Hex(partBuf), {
524
+ "Content-Length": String(partBuf.length),
525
+ });
526
+ var partRes = await _request("PUT", partUrl, partHeaders, partBuf, reqOpts);
527
+ if (!partRes.headers.etag) {
528
+ throw _err("MULTIPART_PART_FAILED",
529
+ "UploadPart response missing ETag for part " + partNumber, false);
530
+ }
531
+ totalSize += partBuf.length;
532
+ return { partNumber: partNumber, etag: partRes.headers.etag };
533
+ });
534
+
535
+ // 3. Complete
536
+ var completeUrl = new URL(url.href);
537
+ completeUrl.searchParams.set("uploadId", uploadId);
538
+ var completeBody = Buffer.from(_buildCompleteMultipartXml(uploadedEtags), "utf8");
539
+ var completeHeaders = _makeSigned("POST", completeUrl, sha256Hex(completeBody), {
540
+ "Content-Type": "application/xml",
541
+ "Content-Length": String(completeBody.length),
542
+ });
543
+ var completeRes = await _request("POST", completeUrl, completeHeaders, completeBody, reqOpts);
544
+ // S3 may return 200 OK with an error body on CompleteMultipartUpload —
545
+ // surface that as a hard error rather than a silent success.
546
+ var completeDoc = safeXml.parse(completeRes.body, LIST_PARSE_OPTS);
547
+ if (completeDoc.Error) {
548
+ throw _err("MULTIPART_COMPLETE_FAILED",
549
+ "CompleteMultipartUpload returned error: " +
550
+ (completeDoc.Error.Code || "unknown") + " " +
551
+ (completeDoc.Error.Message || ""), false);
552
+ }
553
+ // SSE was already verified on the InitiateMultipartUpload
554
+ // response — that's the request that establishes the upload's
555
+ // encryption policy server-side. The CompleteMultipartUpload
556
+ // response may or may not echo the header depending on vendor;
557
+ // re-verifying here would double-fault on otherwise-fine setups.
558
+ var result = completeDoc.CompleteMultipartUploadResult || {};
559
+ return { size: totalSize, etag: result.ETag || completeRes.headers.etag, multipart: true };
560
+ } catch (e) {
561
+ // Abort cleans up server-side storage for the partial upload.
562
+ // Failures here are silently swallowed — the caller's original
563
+ // error is what they need to see, not a secondary cleanup error.
564
+ try {
565
+ var abortUrl = new URL(url.href);
566
+ abortUrl.searchParams.set("uploadId", uploadId);
567
+ var abortHeaders = _makeSigned("DELETE", abortUrl, sha256Hex(Buffer.alloc(0)));
568
+ await _request("DELETE", abortUrl, abortHeaders, null, reqOpts);
569
+ } catch (_e) { /* primary error wins */ }
570
+ throw e;
571
+ }
572
+ }
573
+
290
574
  function get(key) {
291
575
  var url = _keyToUrl(key);
292
576
  var headers = _makeSigned("GET", url, sha256Hex(Buffer.alloc(0)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.4.23",
3
+ "version": "0.4.24",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",