wao 0.27.3 → 0.28.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/cjs/encode.js CHANGED
@@ -5,14 +5,13 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.enc = enc;
7
7
  var _base64url = _interopRequireDefault(require("base64url"));
8
- var _fastSha = require("fast-sha256");
8
+ var _encodeUtils = require("./encode-utils.js");
9
+ var _encodeArrayItem = _interopRequireDefault(require("./encode-array-item.js"));
10
+ var _collectBodyKeys = _interopRequireDefault(require("./collect-body-keys.js"));
9
11
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
10
12
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
11
- function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
12
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
13
- function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
14
- function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
15
13
  function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
14
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
16
15
  function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
17
16
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
18
17
  function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
@@ -21,2068 +20,1339 @@ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" !=
21
20
  function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
22
21
  function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
23
22
  function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
24
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
25
- function isBytes(value) {
26
- return value instanceof ArrayBuffer || ArrayBuffer.isView(value) || Buffer.isBuffer(value) || value && _typeof(value) === "object" && value.type === "Buffer" && Array.isArray(value.data);
23
+ var MAX_HEADER_LENGTH = 4096;
24
+
25
+ // Step 1: Process and normalize input values (handle symbols, nested objects/arrays)
26
+ function processInputValues(obj) {
27
+ // Currently this is a no-op, but will be used for input validation/normalization
28
+ return obj;
27
29
  }
28
- function isPojo(value) {
29
- return !isBytes(value) && !Array.isArray(value) && !(value instanceof Blob) && _typeof(value) === "object" && value !== null;
30
+
31
+ // Step 2: Handle empty object case
32
+ function handleEmptyObject(obj) {
33
+ if (Object.keys(obj).length === 0) {
34
+ return {
35
+ headers: {},
36
+ body: undefined
37
+ };
38
+ }
39
+ return null;
30
40
  }
31
- var MAX_HEADER_LENGTH = 4096;
32
- function hasNewline(_x) {
33
- return _hasNewline.apply(this, arguments);
41
+
42
+ // Step 3: Handle single field with empty binary
43
+ function handleSingleEmptyBinaryField(obj) {
44
+ var objKeys = Object.keys(obj);
45
+ if (objKeys.length === 1) {
46
+ var fieldName = objKeys[0];
47
+ var fieldValue = obj[fieldName];
48
+ if ((0, _encodeUtils.isBytes)(fieldValue) && (fieldValue.length === 0 || fieldValue.byteLength === 0)) {
49
+ var headers = {};
50
+ headers["ao-types"] = "".concat(fieldName.toLowerCase(), "=\"empty-binary\"");
51
+ return {
52
+ headers: headers,
53
+ body: undefined
54
+ };
55
+ }
56
+ }
57
+ return null;
34
58
  }
35
- function _hasNewline() {
36
- _hasNewline = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(value) {
59
+
60
+ // Step 4: Handle single field with binary data
61
+ function handleSingleBinaryField(_x) {
62
+ return _handleSingleBinaryField.apply(this, arguments);
63
+ } // Step 5: Handle single field with primitive value (string/number/boolean/null/undefined/symbol)
64
+ function _handleSingleBinaryField() {
65
+ _handleSingleBinaryField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(obj) {
66
+ var hasBodyBinary, otherFields, headers, bodyBuffer, bodyArrayBuffer, contentDigest, base64;
37
67
  return _regeneratorRuntime().wrap(function _callee$(_context) {
38
68
  while (1) switch (_context.prev = _context.next) {
39
69
  case 0:
40
- if (!(typeof value === "string")) {
41
- _context.next = 2;
42
- break;
43
- }
44
- return _context.abrupt("return", value.includes("\n"));
45
- case 2:
46
- if (!(value instanceof Blob)) {
47
- _context.next = 7;
48
- break;
49
- }
50
- _context.next = 5;
51
- return value.text();
52
- case 5:
53
- value = _context.sent;
54
- return _context.abrupt("return", value.includes("\n"));
55
- case 7:
56
- if (!isBytes(value)) {
57
- _context.next = 9;
70
+ hasBodyBinary = obj.body && (0, _encodeUtils.isBytes)(obj.body);
71
+ otherFields = Object.keys(obj).filter(function (k) {
72
+ return k !== "body";
73
+ });
74
+ if (!(hasBodyBinary && otherFields.length === 0)) {
75
+ _context.next = 12;
58
76
  break;
59
77
  }
60
- return _context.abrupt("return", Buffer.from(value).includes("\n"));
61
- case 9:
62
- return _context.abrupt("return", false);
63
- case 10:
78
+ headers = {};
79
+ bodyBuffer = (0, _encodeUtils.toBuffer)(obj.body);
80
+ bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
81
+ _context.next = 8;
82
+ return (0, _encodeUtils.sha256)(bodyArrayBuffer);
83
+ case 8:
84
+ contentDigest = _context.sent;
85
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
86
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
87
+ return _context.abrupt("return", {
88
+ headers: headers,
89
+ body: obj.body
90
+ });
91
+ case 12:
92
+ return _context.abrupt("return", null);
93
+ case 13:
64
94
  case "end":
65
95
  return _context.stop();
66
96
  }
67
97
  }, _callee);
68
98
  }));
69
- return _hasNewline.apply(this, arguments);
99
+ return _handleSingleBinaryField.apply(this, arguments);
70
100
  }
71
- function sha256(_x2) {
72
- return _sha.apply(this, arguments);
73
- }
74
- function _sha() {
75
- _sha = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(data) {
76
- var uint8Array, hashResult;
101
+ function handleSinglePrimitiveField(_x2) {
102
+ return _handleSinglePrimitiveField.apply(this, arguments);
103
+ } // Step 6a: Handle single field with non-empty binary (not body field)
104
+ function _handleSinglePrimitiveField() {
105
+ _handleSinglePrimitiveField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(obj) {
106
+ var objKeys, fieldName, fieldValue, headers, bodyContent, encoder, encoded, contentDigest, base64, aoType;
77
107
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
78
108
  while (1) switch (_context2.prev = _context2.next) {
79
109
  case 0:
80
- if (!(data instanceof ArrayBuffer)) {
81
- _context2.next = 4;
110
+ objKeys = Object.keys(obj);
111
+ if (!(objKeys.length === 1)) {
112
+ _context2.next = 18;
82
113
  break;
83
114
  }
84
- uint8Array = new Uint8Array(data);
85
- _context2.next = 13;
86
- break;
87
- case 4:
88
- if (!(data instanceof Uint8Array)) {
89
- _context2.next = 8;
115
+ fieldName = objKeys[0];
116
+ fieldValue = obj[fieldName];
117
+ if (!((fieldName === "data" || fieldName === "body") && (typeof fieldValue === "string" || typeof fieldValue === "boolean" || typeof fieldValue === "number" || fieldValue === null || fieldValue === undefined || _typeof(fieldValue) === "symbol"))) {
118
+ _context2.next = 18;
90
119
  break;
91
120
  }
92
- uint8Array = data;
93
- _context2.next = 13;
94
- break;
95
- case 8:
96
- if (!ArrayBuffer.isView(data)) {
97
- _context2.next = 12;
98
- break;
121
+ headers = {};
122
+ bodyContent = (0, _encodeUtils.encodePrimitiveContent)(fieldValue);
123
+ encoder = new TextEncoder();
124
+ encoded = encoder.encode(bodyContent);
125
+ _context2.next = 11;
126
+ return (0, _encodeUtils.sha256)(encoded.buffer);
127
+ case 11:
128
+ contentDigest = _context2.sent;
129
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
130
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
131
+ aoType = (0, _encodeUtils.getAoType)(fieldValue);
132
+ if (aoType === "atom" || aoType === "integer" || aoType === "float") {
133
+ headers["ao-types"] = "".concat(fieldName.toLowerCase(), "=\"").concat(aoType, "\"");
99
134
  }
100
- uint8Array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
101
- _context2.next = 13;
102
- break;
103
- case 12:
104
- throw new Error("sha256 expects ArrayBuffer or ArrayBufferView");
105
- case 13:
106
- hashResult = (0, _fastSha.hash)(uint8Array);
107
- return _context2.abrupt("return", hashResult.buffer.slice(hashResult.byteOffset, hashResult.byteOffset + hashResult.byteLength));
108
- case 15:
135
+ if (fieldName !== "body") {
136
+ headers["inline-body-key"] = fieldName;
137
+ }
138
+ return _context2.abrupt("return", {
139
+ headers: headers,
140
+ body: bodyContent
141
+ });
142
+ case 18:
143
+ return _context2.abrupt("return", null);
144
+ case 19:
109
145
  case "end":
110
146
  return _context2.stop();
111
147
  }
112
148
  }, _callee2);
113
149
  }));
114
- return _sha.apply(this, arguments);
150
+ return _handleSinglePrimitiveField.apply(this, arguments);
115
151
  }
116
- function formatFloat(num) {
117
- var exp = num.toExponential(20);
118
- exp = exp.replace(/e\+(\d)$/, "e+0$1");
119
- exp = exp.replace(/e-(\d)$/, "e-0$1");
120
- return exp;
152
+ function handleSingleNonEmptyBinaryField(_x3) {
153
+ return _handleSingleNonEmptyBinaryField.apply(this, arguments);
154
+ } // Step 6: Handle single field with non-ASCII string
155
+ function _handleSingleNonEmptyBinaryField() {
156
+ _handleSingleNonEmptyBinaryField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(obj) {
157
+ var objKeys, fieldName, fieldValue, headers, bodyBuffer, bodyArrayBuffer, contentDigest, base64;
158
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
159
+ while (1) switch (_context3.prev = _context3.next) {
160
+ case 0:
161
+ objKeys = Object.keys(obj);
162
+ if (!(objKeys.length === 1)) {
163
+ _context3.next = 15;
164
+ break;
165
+ }
166
+ fieldName = objKeys[0];
167
+ fieldValue = obj[fieldName];
168
+ if (!((0, _encodeUtils.isBytes)(fieldValue) && fieldValue.length > 0)) {
169
+ _context3.next = 15;
170
+ break;
171
+ }
172
+ headers = {};
173
+ bodyBuffer = (0, _encodeUtils.toBuffer)(fieldValue);
174
+ bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
175
+ _context3.next = 10;
176
+ return (0, _encodeUtils.sha256)(bodyArrayBuffer);
177
+ case 10:
178
+ contentDigest = _context3.sent;
179
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
180
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
181
+ if (fieldName !== "body") {
182
+ headers["inline-body-key"] = fieldName;
183
+ }
184
+ return _context3.abrupt("return", {
185
+ headers: headers,
186
+ body: fieldValue
187
+ });
188
+ case 15:
189
+ return _context3.abrupt("return", null);
190
+ case 16:
191
+ case "end":
192
+ return _context3.stop();
193
+ }
194
+ }, _callee3);
195
+ }));
196
+ return _handleSingleNonEmptyBinaryField.apply(this, arguments);
197
+ }
198
+ function handleSingleNonAsciiStringField(_x4) {
199
+ return _handleSingleNonAsciiStringField.apply(this, arguments);
200
+ } // Step 7: Collect all keys that need to go in body
201
+ function _handleSingleNonAsciiStringField() {
202
+ _handleSingleNonAsciiStringField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(obj) {
203
+ var objKeys, fieldName, fieldValue, headers, encoder, encoded, contentDigest, base64;
204
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
205
+ while (1) switch (_context4.prev = _context4.next) {
206
+ case 0:
207
+ objKeys = Object.keys(obj);
208
+ if (!(objKeys.length === 1)) {
209
+ _context4.next = 15;
210
+ break;
211
+ }
212
+ fieldName = objKeys[0];
213
+ fieldValue = obj[fieldName];
214
+ if (!(typeof fieldValue === "string" && (0, _encodeUtils.hasNonAscii)(fieldValue))) {
215
+ _context4.next = 15;
216
+ break;
217
+ }
218
+ headers = {};
219
+ encoder = new TextEncoder();
220
+ encoded = encoder.encode(fieldValue);
221
+ _context4.next = 10;
222
+ return (0, _encodeUtils.sha256)(encoded.buffer);
223
+ case 10:
224
+ contentDigest = _context4.sent;
225
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
226
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
227
+ if (fieldName !== "body") {
228
+ headers["inline-body-key"] = fieldName;
229
+ }
230
+ return _context4.abrupt("return", {
231
+ headers: headers,
232
+ body: fieldValue
233
+ });
234
+ case 15:
235
+ return _context4.abrupt("return", null);
236
+ case 16:
237
+ case "end":
238
+ return _context4.stop();
239
+ }
240
+ }, _callee4);
241
+ }));
242
+ return _handleSingleNonAsciiStringField.apply(this, arguments);
121
243
  }
122
- function hasNonAscii(str) {
123
- return /[^\x00-\x7F]/.test(str);
244
+ function collectBodyKeysStep(obj) {
245
+ return (0, _collectBodyKeys["default"])(obj);
124
246
  }
125
- function encodeArrayItem(item) {
126
- if (typeof item === "number") {
127
- if (Number.isInteger(item)) {
128
- return "\"(ao-type-integer) ".concat(item, "\"");
247
+
248
+ // Step 8: Process fields that can go in headers
249
+ function processHeaderFields(obj, bodyKeys, headers, headerTypes) {
250
+ var _loop = function _loop() {
251
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
252
+ key = _Object$entries$_i[0],
253
+ value = _Object$entries$_i[1];
254
+ var needsBody = bodyKeys.includes(key) || bodyKeys.some(function (k) {
255
+ return k.startsWith("".concat(key, "/"));
256
+ });
257
+ if (!needsBody) {
258
+ if (value === null) {
259
+ headers[key] = '"null"';
260
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
261
+ } else if (value === undefined) {
262
+ headers[key] = '"undefined"';
263
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
264
+ } else if (typeof value === "boolean") {
265
+ headers[key] = "\"".concat(value, "\"");
266
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
267
+ } else if (_typeof(value) === "symbol") {
268
+ headers[key] = "\"".concat(value.description || "Symbol.for()", "\"");
269
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
270
+ } else if (typeof value === "number") {
271
+ headers[key] = String(value);
272
+ headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
273
+ } else if (typeof value === "string") {
274
+ if (value.length === 0) {
275
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
276
+ } else if ((0, _encodeUtils.hasNonAscii)(value)) {
277
+ return 1; // continue
278
+ } else {
279
+ headers[key] = value;
280
+ }
281
+ } else if (Array.isArray(value) && value.length === 0) {
282
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-list\""));
283
+ } else if (Array.isArray(value) && !value.some(function (item) {
284
+ return (0, _encodeUtils.isPojo)(item);
285
+ })) {
286
+ var hasNonAsciiItems = value.some(function (item) {
287
+ return typeof item === "string" && (0, _encodeUtils.hasNonAscii)(item);
288
+ });
289
+ if (!hasNonAsciiItems) {
290
+ var encodedItems = value.map(function (item) {
291
+ return (0, _encodeArrayItem["default"])(item);
292
+ }).join(", ");
293
+ headers[key] = encodedItems;
294
+ headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
295
+ }
296
+ } else if ((0, _encodeUtils.isBytes)(value) && (value.length === 0 || value.byteLength === 0)) {
297
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
298
+ } else if ((0, _encodeUtils.isPojo)(value) && Object.keys(value).length === 0) {
299
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-message\""));
300
+ }
129
301
  } else {
130
- return "\"(ao-type-float) ".concat(formatFloat(item), "\"");
302
+ // Fields that need body still get type annotations
303
+ var aoType = (0, _encodeUtils.getAoType)(value);
304
+ if (aoType) {
305
+ headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(aoType, "\""));
306
+ }
131
307
  }
132
- } else if (typeof item === "string") {
133
- return "\"".concat(item, "\"");
134
- } else if (item === null) {
135
- return "\"(ao-type-atom) \\\"null\\\"\"";
136
- } else if (item === undefined) {
137
- return "\"(ao-type-atom) \\\"undefined\\\"\"";
138
- } else if (_typeof(item) === "symbol") {
139
- var desc = item.description || "Symbol.for()";
140
- return "\"(ao-type-atom) \\\"".concat(desc, "\\\"\"");
141
- } else if (typeof item === "boolean") {
142
- return "\"(ao-type-atom) \\\"".concat(item, "\\\"\"");
143
- } else if (Array.isArray(item)) {
144
- var nestedItems = item.map(function (nestedItem) {
145
- if (typeof nestedItem === "number") {
146
- if (Number.isInteger(nestedItem)) {
147
- return "\\\"(ao-type-integer) ".concat(nestedItem, "\\\"");
148
- } else {
149
- return "\\\"(ao-type-float) ".concat(formatFloat(nestedItem), "\\\"");
308
+ };
309
+ for (var _i = 0, _Object$entries = Object.entries(obj); _i < _Object$entries.length; _i++) {
310
+ if (_loop()) continue;
311
+ }
312
+
313
+ // Second pass for array type annotations
314
+ var _loop2 = function _loop2() {
315
+ var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
316
+ key = _Object$entries2$_i[0],
317
+ value = _Object$entries2$_i[1];
318
+ if (Array.isArray(value)) {
319
+ if (bodyKeys.includes(key) || bodyKeys.some(function (k) {
320
+ return k.startsWith("".concat(key, "/"));
321
+ })) {
322
+ if (!headerTypes.some(function (t) {
323
+ return t.startsWith("".concat(key.toLowerCase(), "="));
324
+ })) {
325
+ headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
150
326
  }
151
- } else if (typeof nestedItem === "string") {
152
- return "\\\"".concat(nestedItem, "\\\"");
153
- } else if (nestedItem === null) {
154
- return "\\\"(ao-type-atom) \\\\\\\"null\\\\\\\"\\\"";
155
- } else if (nestedItem === undefined) {
156
- return "\\\"(ao-type-atom) \\\\\\\"undefined\\\\\\\"\\\"";
157
- } else if (_typeof(nestedItem) === "symbol") {
158
- var _desc = nestedItem.description || "Symbol.for()";
159
- return "\\\"(ao-type-atom) \\\\\\\"".concat(_desc, "\\\\\\\"\\\"");
160
- } else if (typeof nestedItem === "boolean") {
161
- return "\\\"(ao-type-atom) \\\\\\\"".concat(nestedItem, "\\\\\\\"\\\"");
162
- } else if (Array.isArray(nestedItem)) {
163
- // Handle nested arrays recursively
164
- var deeperItems = nestedItem.map(function (deepItem) {
165
- if (typeof deepItem === "number") {
166
- if (Number.isInteger(deepItem)) {
167
- return "\\\\\\\"(ao-type-integer) ".concat(deepItem, "\\\\\\\"");
168
- } else {
169
- return "\\\\\\\"(ao-type-float) ".concat(formatFloat(deepItem), "\\\\\\\"");
170
- }
171
- } else if (typeof deepItem === "string") {
172
- return "\\\\\\\"".concat(deepItem, "\\\\\\\"");
173
- } else if (Array.isArray(deepItem)) {
174
- // Even deeper nesting - need to escape more
175
- var deepestItems = deepItem.map(function (deepestItem) {
176
- if (typeof deepestItem === "number") {
177
- if (Number.isInteger(deepestItem)) {
178
- return "\\\\\\\\\\\\\\\"(ao-type-integer) ".concat(deepestItem, "\\\\\\\\\\\\\\\"");
179
- } else {
180
- return "\\\\\\\\\\\\\\\"(ao-type-float) ".concat(formatFloat(deepestItem), "\\\\\\\\\\\\\\\"");
181
- }
182
- } else if (typeof deepestItem === "string") {
183
- return "\\\\\\\\\\\\\\\"".concat(deepestItem, "\\\\\\\\\\\\\\\"");
184
- } else {
185
- return "\\\\\\\\\\\\\\\"".concat(String(deepestItem), "\\\\\\\\\\\\\\\"");
186
- }
187
- }).join(", ");
188
- return "\\\\\\\"(ao-type-list) ".concat(deepestItems, "\\\\\\\"");
189
- } else if (deepItem === null) {
190
- return "\\\\\\\"(ao-type-atom) \\\\\\\\\\\\\\\"null\\\\\\\\\\\\\\\"\\\\\\\"";
191
- } else if (deepItem === undefined) {
192
- return "\\\\\\\"(ao-type-atom) \\\\\\\\\\\\\\\"undefined\\\\\\\\\\\\\\\"\\\\\\\"";
193
- } else if (_typeof(deepItem) === "symbol") {
194
- var _desc2 = deepItem.description || "Symbol.for()";
195
- return "\\\\\\\"(ao-type-atom) \\\\\\\\\\\\\\\"".concat(_desc2, "\\\\\\\\\\\\\\\"\\\\\\\"");
196
- } else if (typeof deepItem === "boolean") {
197
- return "\\\\\\\"(ao-type-atom) \\\\\\\\\\\\\\\"".concat(deepItem, "\\\\\\\\\\\\\\\"\\\\\\\"");
327
+ }
328
+ }
329
+ };
330
+ for (var _i2 = 0, _Object$entries2 = Object.entries(obj); _i2 < _Object$entries2.length; _i2++) {
331
+ _loop2();
332
+ }
333
+ }
334
+
335
+ // Step 9: Handle case where all body keys are empty binaries
336
+ function handleAllEmptyBinaryBodyKeys(obj, bodyKeys, headers, headerTypes) {
337
+ if (bodyKeys.length === 0) {
338
+ if (headerTypes.length > 0) {
339
+ headers["ao-types"] = headerTypes.sort().join(", ");
340
+ }
341
+ return {
342
+ headers: headers,
343
+ body: undefined
344
+ };
345
+ }
346
+ var allBodyKeysAreEmptyBinaries = bodyKeys.every(function (key) {
347
+ var value = (0, _encodeUtils.getValueByPath)(obj, key);
348
+ return (0, _encodeUtils.isBytes)(value) && (value.length === 0 || value.byteLength === 0);
349
+ });
350
+ if (allBodyKeysAreEmptyBinaries) {
351
+ if (headerTypes.length > 0) {
352
+ headers["ao-types"] = headerTypes.sort().join(", ");
353
+ }
354
+ return {
355
+ headers: headers,
356
+ body: undefined
357
+ };
358
+ }
359
+ return null;
360
+ }
361
+
362
+ // Step 10: Handle single body key optimization
363
+ function handleSingleBodyKeyOptimization(_x5, _x6, _x7, _x8) {
364
+ return _handleSingleBodyKeyOptimization.apply(this, arguments);
365
+ } // Step 11: Sort body keys
366
+ function _handleSingleBodyKeyOptimization() {
367
+ _handleSingleBodyKeyOptimization = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(obj, bodyKeys, headers, headerTypes) {
368
+ var singleKey, value, contentToHash, bodyContent, bodyBuffer, encoder, encoded, contentDigest, base64;
369
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
370
+ while (1) switch (_context5.prev = _context5.next) {
371
+ case 0:
372
+ if (!(bodyKeys.length === 1)) {
373
+ _context5.next = 14;
374
+ break;
375
+ }
376
+ singleKey = bodyKeys[0];
377
+ value = (0, _encodeUtils.getValueByPath)(obj, singleKey); // Apply optimization for binary data OR strings with newlines
378
+ if (!((0, _encodeUtils.isBytes)(value) && value.length > 0 || typeof value === "string" && value.includes("\n"))) {
379
+ _context5.next = 14;
380
+ break;
381
+ }
382
+ bodyContent = value;
383
+ if ((0, _encodeUtils.isBytes)(value)) {
384
+ bodyBuffer = (0, _encodeUtils.toBuffer)(value);
385
+ contentToHash = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
198
386
  } else {
199
- return "\\\\\\\"".concat(String(deepItem), "\\\\\\\"");
387
+ // For strings, encode to UTF-8 for hashing
388
+ encoder = new TextEncoder();
389
+ encoded = encoder.encode(value);
390
+ contentToHash = encoded.buffer;
391
+ bodyContent = value;
200
392
  }
201
- }).join(", ");
202
- return "\\\"(ao-type-list) ".concat(deeperItems, "\\\"");
203
- } else {
204
- return "\\\"".concat(String(nestedItem), "\\\"");
393
+ _context5.next = 8;
394
+ return (0, _encodeUtils.sha256)(contentToHash);
395
+ case 8:
396
+ contentDigest = _context5.sent;
397
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
398
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
399
+ if (singleKey !== "body") {
400
+ headers["inline-body-key"] = singleKey;
401
+ }
402
+ if (headerTypes.length > 0) {
403
+ headers["ao-types"] = headerTypes.sort().join(", ");
404
+ }
405
+ return _context5.abrupt("return", {
406
+ headers: headers,
407
+ body: bodyContent
408
+ });
409
+ case 14:
410
+ return _context5.abrupt("return", null);
411
+ case 15:
412
+ case "end":
413
+ return _context5.stop();
205
414
  }
206
- }).join(", ");
207
- return "\"(ao-type-list) ".concat(nestedItems, "\"");
208
- } else if (isBytes(item)) {
209
- var buffer = toBuffer(item);
210
- if (buffer.length === 0 || buffer.byteLength === 0) {
211
- return "\"\"";
415
+ }, _callee5);
416
+ }));
417
+ return _handleSingleBodyKeyOptimization.apply(this, arguments);
418
+ }
419
+ function sortBodyKeys(bodyKeys) {
420
+ return bodyKeys.sort(function (a, b) {
421
+ var aIsArrayElement = /\/\d+$/.test(a);
422
+ var bIsArrayElement = /\/\d+$/.test(b);
423
+ var aBase = a.split("/")[0];
424
+ var bBase = b.split("/")[0];
425
+ if (aBase === bBase) {
426
+ if (!aIsArrayElement && bIsArrayElement) {
427
+ return -1;
428
+ }
429
+ if (aIsArrayElement && !bIsArrayElement) {
430
+ return 1;
431
+ }
432
+ if (aIsArrayElement && bIsArrayElement) {
433
+ var aIndex = parseInt(a.split("/")[1]);
434
+ var bIndex = parseInt(b.split("/")[1]);
435
+ return aIndex - bIndex;
436
+ }
437
+ return a.localeCompare(b);
212
438
  }
213
- return "\"(ao-type-binary)\"";
214
- } else if (isPojo(item)) {
215
- var json = JSON.stringify(item);
216
- var escaped = json.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
217
- return "\"(ao-type-map) ".concat(escaped, "\"");
218
- } else {
219
- return "\"".concat(String(item), "\"");
439
+ return a.localeCompare(b);
440
+ });
441
+ }
442
+
443
+ // Step 12: Check for special data/body case
444
+ function checkSpecialDataBodyCase(obj, sortedBodyKeys) {
445
+ return sortedBodyKeys.includes("data") && sortedBodyKeys.includes("body") && obj.data && obj.data.body && (0, _encodeUtils.isBytes)(obj.data.body) && obj.body && obj.body.data && (0, _encodeUtils.isBytes)(obj.body.data);
446
+ }
447
+
448
+ // Step 13.2.2: Handle empty string in nested path
449
+ function handleEmptyStringInNestedPath(bodyKey, value, pathParts) {
450
+ if (typeof value === "string" && value === "" && pathParts.length > 1) {
451
+ var lines = [];
452
+ lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
453
+ lines.push("");
454
+ lines.push("");
455
+ return new Blob([lines.join("\r\n")]);
220
456
  }
457
+ return null;
221
458
  }
222
- function toBuffer(value) {
223
- if (Buffer.isBuffer(value)) {
224
- return value;
225
- } else if (value && _typeof(value) === "object" && value.type === "Buffer" && Array.isArray(value.data)) {
226
- return Buffer.from(value.data);
227
- } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
228
- return Buffer.from(value);
459
+
460
+ // Step 13.2.3.2: Handle arrays with only empty elements
461
+ function handleArrayWithOnlyEmptyElements(bodyKey, value, headers, sortedBodyKeys) {
462
+ var fieldLines = [];
463
+ var partTypes = [];
464
+ value.forEach(function (item, idx) {
465
+ var index = idx + 1;
466
+ var itemType = (0, _encodeUtils.getAoType)(item);
467
+ if (itemType) {
468
+ partTypes.push("".concat(index, "=\"").concat(itemType, "\""));
469
+ }
470
+ });
471
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
472
+ if (isInline) {
473
+ var orderedLines = [];
474
+ if (partTypes.length > 0) {
475
+ orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
476
+ }
477
+ orderedLines.push("content-disposition: inline");
478
+ orderedLines.push("");
479
+ return new Blob([orderedLines.join("\r\n")]);
229
480
  } else {
230
- return Buffer.from(value);
481
+ var _orderedLines = [];
482
+ if (partTypes.length > 0) {
483
+ _orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
484
+ }
485
+ _orderedLines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
486
+ var isLastBodyPart = sortedBodyKeys.indexOf(bodyKey) === sortedBodyKeys.length - 1;
487
+ var hasOnlyTypes = partTypes.length > 0 && fieldLines.length === 0;
488
+ if (isLastBodyPart && hasOnlyTypes) {
489
+ return new Blob([_orderedLines.join("\r\n")]);
490
+ } else {
491
+ _orderedLines.push("");
492
+ return new Blob([_orderedLines.join("\r\n")]);
493
+ }
231
494
  }
232
495
  }
233
- function collectBodyKeys(obj) {
234
- var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
235
- console.log("=== collectBodyKeys START ===");
236
- console.log("Input object:", JSON.stringify(obj));
237
- var keys = [];
238
- function traverse(current, path) {
239
- console.log("[traverse] Called with path: \"".concat(path, "\""));
240
- var hasSimpleFields = false;
241
- var nestedPaths = [];
242
- var hasArraysWithObjects = false;
243
- var _loop = function _loop() {
244
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
245
- key = _Object$entries$_i[0],
246
- value = _Object$entries$_i[1];
247
- var fullPath = path ? "".concat(path, "/").concat(key) : key;
248
- if (Array.isArray(value)) {
249
- console.log("[traverse] Found array at ".concat(fullPath, ", length: ").concat(value.length));
250
- var hasObjects = value.some(function (item) {
251
- return isPojo(item);
252
- });
253
- var hasNonObjects = value.some(function (item) {
254
- return !isPojo(item);
255
- });
256
- if (value.length === 0) {
257
- console.log("[traverse] Empty array at ".concat(fullPath, " - marking parent as having simple fields"));
258
- hasSimpleFields = true;
259
- } else if (hasObjects) {
260
- hasArraysWithObjects = true;
261
- // Check if we need special handling for mixed arrays
262
- var hasEmptyStrings = value.some(function (item) {
263
- return typeof item === "string" && item === "";
264
- });
265
- var hasEmptyObjects = value.some(function (item) {
266
- return isPojo(item) && Object.keys(item).length === 0;
267
- });
268
- var hasNonEmptyObjects = value.some(function (item) {
269
- return isPojo(item) && Object.keys(item).length > 0;
270
- });
271
496
 
272
- // Check if objects contain only empty values (not empty objects)
273
- var hasObjectsWithOnlyEmptyValues = value.some(function (item) {
274
- if (!isPojo(item) || Object.keys(item).length === 0) return false;
275
- return Object.values(item).every(function (v) {
276
- return typeof v === "string" && v === "" || Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0;
277
- });
278
- });
497
+ // Step 13.2.3.3: Build indices with own parts
498
+ function buildIndicesWithOwnParts(bodyKey, sortedBodyKeys) {
499
+ var indicesWithOwnParts = new Set();
500
+ sortedBodyKeys.forEach(function (key) {
501
+ if (key.startsWith(bodyKey + "/")) {
502
+ var subPath = key.substring(bodyKey.length + 1);
503
+ var match = subPath.match(/^(\d+)/);
504
+ if (match) {
505
+ indicesWithOwnParts.add(parseInt(match[1]));
506
+ }
507
+ }
508
+ });
509
+ return indicesWithOwnParts;
510
+ }
279
511
 
280
- // Only use special handling if we have BOTH empty elements AND non-empty objects
281
- if ((hasEmptyStrings || hasEmptyObjects) && hasNonEmptyObjects) {
282
- // Special case: mixed array with empty strings/objects - only non-empty objects get parts
283
- value.forEach(function (item, index) {
284
- if (isPojo(item) && Object.keys(item).length > 0) {
285
- var itemPath = "".concat(fullPath, "/").concat(index + 1);
286
- keys.push(itemPath);
287
- nestedPaths.push(itemPath);
288
- }
289
- });
290
- if (hasNonObjects) {
291
- hasSimpleFields = true;
292
- keys.push(fullPath);
512
+ // Step 13.2.3.4: Process array items
513
+ function processArrayItems(value, indicesWithOwnParts, hasNestedObjectParts, pathParts) {
514
+ var fieldLines = [];
515
+ var partTypes = [];
516
+ if (hasNestedObjectParts) {
517
+ value.forEach(function (item, idx) {
518
+ var index = idx + 1;
519
+ if (Array.isArray(item)) {
520
+ partTypes.push("".concat(index, "=\"list\""));
521
+ }
522
+ });
523
+ }
524
+ value.forEach(function (item, idx) {
525
+ var index = idx + 1;
526
+ if (indicesWithOwnParts.has(index)) {
527
+ return;
528
+ }
529
+ if (hasNestedObjectParts && Array.isArray(item) && item.some(function (subItem) {
530
+ return (0, _encodeUtils.isPojo)(subItem);
531
+ })) {
532
+ return;
533
+ }
534
+ if (typeof item === "string" && item === "") {
535
+ partTypes.push("".concat(index, "=\"empty-binary\""));
536
+ } else if ((0, _encodeUtils.isPojo)(item) && Object.keys(item).length === 0) {
537
+ partTypes.push("".concat(index, "=\"empty-message\""));
538
+ } else if ((0, _encodeUtils.isPojo)(item)) {
539
+ // Non-empty objects are handled elsewhere
540
+ } else if (Array.isArray(item)) {
541
+ if (item.length === 0) {
542
+ partTypes.push("".concat(index, "=\"empty-list\""));
543
+ } else {
544
+ partTypes.push("".concat(index, "=\"list\""));
545
+ var encodedItems = item.map(function (subItem) {
546
+ if (typeof subItem === "number") {
547
+ if (Number.isInteger(subItem)) {
548
+ return "\"(ao-type-integer) ".concat(subItem, "\"");
549
+ } else {
550
+ return "\"(ao-type-float) ".concat((0, _encodeUtils.formatFloat)(subItem), "\"");
293
551
  }
294
- } else if (hasObjectsWithOnlyEmptyValues && !hasNonObjects) {
295
- // Special case: objects that contain only empty values should get parts
296
- value.forEach(function (item, index) {
297
- if (isPojo(item)) {
298
- var itemPath = "".concat(fullPath, "/").concat(index + 1);
299
- keys.push(itemPath);
300
- if (Object.keys(item).length > 0) {
301
- nestedPaths.push(itemPath);
302
- }
303
- }
304
- });
305
- } else {
306
- // Normal case: all objects get parts
307
- value.forEach(function (item, index) {
308
- if (isPojo(item)) {
309
- var itemPath = "".concat(fullPath, "/").concat(index + 1);
310
- keys.push(itemPath);
311
- if (Object.keys(item).length > 0) {
312
- nestedPaths.push(itemPath);
313
- }
314
- }
315
- });
316
- if (hasNonObjects) {
317
- hasSimpleFields = true;
318
- keys.push(fullPath);
552
+ } else if (typeof subItem === "string") {
553
+ return "\"".concat(subItem, "\"");
554
+ } else if (subItem === null) {
555
+ return "\"(ao-type-atom) \\\"null\\\"\"";
556
+ } else if (subItem === undefined) {
557
+ return "\"(ao-type-atom) \\\"undefined\\\"\"";
558
+ } else if (_typeof(subItem) === "symbol") {
559
+ var desc = subItem.description || "Symbol.for()";
560
+ return "\"(ao-type-atom) \\\"".concat(desc, "\\\"\"");
561
+ } else if (typeof subItem === "boolean") {
562
+ return "\"(ao-type-atom) \\\"".concat(subItem, "\\\"\"");
563
+ } else if (Array.isArray(subItem)) {
564
+ return (0, _encodeArrayItem["default"])(subItem);
565
+ } else if ((0, _encodeUtils.isBytes)(subItem)) {
566
+ var buffer = (0, _encodeUtils.toBuffer)(subItem);
567
+ if (buffer.length === 0 || buffer.byteLength === 0) {
568
+ return "\"\"";
319
569
  }
320
- }
321
- } else {
322
- console.log("[traverse] Non-empty array without objects at ".concat(fullPath, " - marking as simple field"));
323
- hasSimpleFields = true;
324
- }
325
- } else if (isPojo(value)) {
326
- if (Object.keys(value).length === 0) {
327
- console.log("[traverse] Empty object at ".concat(fullPath, " - marking parent as having simple fields"));
328
- hasSimpleFields = true;
329
- } else {
330
- // Don't traverse into the object if it only contains empty values
331
- var containsOnlyEmptyCollections = Object.entries(value).every(function (_ref) {
332
- var _ref2 = _slicedToArray(_ref, 2),
333
- k = _ref2[0],
334
- v = _ref2[1];
335
- return Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0 || isBytes(v) && (v.length === 0 || v.byteLength === 0) || typeof v === "string" && v.length === 0;
336
- });
337
- if (containsOnlyEmptyCollections && Object.keys(value).length > 0) {
338
- console.log("[traverse] Object at ".concat(fullPath, " contains only empty collections - adding as body key"));
339
- keys.push(fullPath);
570
+ return "\"(ao-type-binary)\"";
571
+ } else if ((0, _encodeUtils.isPojo)(subItem)) {
572
+ var json = JSON.stringify(subItem);
573
+ var escaped = json.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
574
+ return "\"(ao-type-map) ".concat(escaped, "\"");
340
575
  } else {
341
- // Check if this object contains arrays with only empty elements
342
- var hasArraysWithOnlyEmptyElements = Object.entries(value).some(function (_ref3) {
343
- var _ref4 = _slicedToArray(_ref3, 2),
344
- k = _ref4[0],
345
- v = _ref4[1];
346
- return Array.isArray(v) && v.length > 0 && v.every(function (item) {
347
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
348
- });
349
- });
350
- if (hasArraysWithOnlyEmptyElements) {
351
- // This object needs a body part to show its array types
352
- console.log("[traverse] Object at ".concat(fullPath, " has arrays with empty elements - adding as body key"));
353
- keys.push(fullPath);
354
- }
355
- console.log("[traverse] Non-empty object at ".concat(fullPath, " - will traverse into it"));
356
- nestedPaths.push(fullPath);
576
+ return "\"".concat(String(subItem), "\"");
357
577
  }
358
- }
359
- } else if (isBytes(value) && value.length > 0) {
360
- hasSimpleFields = true;
361
- } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === undefined || _typeof(value) === "symbol") {
362
- hasSimpleFields = true;
578
+ }).join(", ");
579
+ fieldLines.push("".concat(index, ": ").concat(encodedItems));
580
+ }
581
+ } else if (typeof item === "number") {
582
+ if (Number.isInteger(item)) {
583
+ partTypes.push("".concat(index, "=\"integer\""));
584
+ fieldLines.push("".concat(index, ": ").concat(item));
585
+ } else {
586
+ partTypes.push("".concat(index, "=\"float\""));
587
+ fieldLines.push("".concat(index, ": ").concat((0, _encodeUtils.formatFloat)(item)));
588
+ }
589
+ } else if (typeof item === "string") {
590
+ fieldLines.push("".concat(index, ": ").concat(item));
591
+ } else if (item === null || item === undefined || _typeof(item) === "symbol" || typeof item === "boolean") {
592
+ partTypes.push("".concat(index, "=\"atom\""));
593
+ if (item === null) {
594
+ fieldLines.push("".concat(index, ": null"));
595
+ } else if (item === undefined) {
596
+ fieldLines.push("".concat(index, ": undefined"));
597
+ } else if (_typeof(item) === "symbol") {
598
+ var desc = item.description || "Symbol.for()";
599
+ fieldLines.push("".concat(index, ": ").concat(desc));
600
+ } else {
601
+ fieldLines.push("".concat(index, ": ").concat(item));
602
+ }
603
+ } else if ((0, _encodeUtils.isBytes)(item)) {
604
+ var buffer = (0, _encodeUtils.toBuffer)(item);
605
+ if (buffer.length === 0) {
606
+ partTypes.push("".concat(index, "=\"empty-binary\""));
607
+ } else {
608
+ partTypes.push("".concat(index, "=\"binary\""));
363
609
  }
364
- };
365
- for (var _i = 0, _Object$entries = Object.entries(current); _i < _Object$entries.length; _i++) {
366
- _loop();
367
- }
368
- if (hasSimpleFields) {
369
- console.log("[traverse] Adding \"".concat(path, "\" to keys (has simple fields)"));
370
- keys.push(path);
371
- } else if (hasArraysWithObjects && path) {
372
- // If the object only contains arrays with objects, we still need to add it as a body key
373
- console.log("[traverse] Adding \"".concat(path, "\" to keys (contains arrays with objects)"));
374
- keys.push(path);
375
610
  }
611
+ });
612
+ return {
613
+ fieldLines: fieldLines,
614
+ partTypes: partTypes
615
+ };
616
+ }
376
617
 
377
- // Check for arrays with only empty elements that need their own body parts
378
- for (var _i2 = 0, _Object$entries2 = Object.entries(current); _i2 < _Object$entries2.length; _i2++) {
379
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
380
- key = _Object$entries2$_i[0],
381
- value = _Object$entries2$_i[1];
382
- var fullPath = path ? "".concat(path, "/").concat(key) : key;
383
- if (Array.isArray(value) && value.length > 0) {
384
- var hasOnlyEmptyElements = value.every(function (item) {
385
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
386
- });
387
- if (hasOnlyEmptyElements) {
388
- console.log("[traverse] Array at ".concat(fullPath, " has only empty elements - adding as body key"));
389
- keys.push(fullPath);
390
- }
391
- }
618
+ // Step 13.2.3.5: Create array body part
619
+ function createArrayBodyPart(bodyKey, fieldLines, partTypes, headers) {
620
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
621
+ if (isInline) {
622
+ var orderedLines = [];
623
+ if (partTypes.length > 0) {
624
+ orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
392
625
  }
393
- for (var _i3 = 0, _nestedPaths = nestedPaths; _i3 < _nestedPaths.length; _i3++) {
394
- var nestedPath = _nestedPaths[_i3];
395
- var parts = nestedPath.split("/");
396
- var nestedObj = obj;
397
- var _iterator = _createForOfIteratorHelper(parts),
626
+ orderedLines.push("content-disposition: inline");
627
+ if (fieldLines.length > 0) {
628
+ orderedLines.push("");
629
+ var _iterator = _createForOfIteratorHelper(fieldLines),
398
630
  _step;
399
631
  try {
400
632
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
401
- var part = _step.value;
402
- if (/^\d+$/.test(part)) {
403
- nestedObj = nestedObj[parseInt(part) - 1];
404
- } else {
405
- nestedObj = nestedObj[part];
406
- }
633
+ var line = _step.value;
634
+ orderedLines.push(line);
407
635
  }
408
636
  } catch (err) {
409
637
  _iterator.e(err);
410
638
  } finally {
411
639
  _iterator.f();
412
640
  }
413
- if (isPojo(nestedObj)) {
414
- traverse(nestedObj, nestedPath);
641
+ }
642
+ return new Blob([orderedLines.join("\r\n") + "\r\n"]);
643
+ } else {
644
+ var _orderedLines2 = [];
645
+ if (partTypes.length > 0) {
646
+ _orderedLines2.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
647
+ }
648
+ _orderedLines2.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
649
+ var _iterator2 = _createForOfIteratorHelper(fieldLines),
650
+ _step2;
651
+ try {
652
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
653
+ var _line = _step2.value;
654
+ _orderedLines2.push(_line);
415
655
  }
656
+ } catch (err) {
657
+ _iterator2.e(err);
658
+ } finally {
659
+ _iterator2.f();
660
+ }
661
+ if (fieldLines.length > 0) {
662
+ return new Blob([_orderedLines2.join("\r\n") + "\r\n"]);
663
+ } else {
664
+ return new Blob([_orderedLines2.join("\r\n")]);
416
665
  }
417
666
  }
418
- var objKeys = Object.keys(obj);
419
- var _loop2 = function _loop2() {
420
- var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i4], 2),
421
- key = _Object$entries3$_i[0],
422
- value = _Object$entries3$_i[1];
423
- console.log("\n[main loop] Processing key: \"".concat(key, "\""));
424
- console.log("[main loop] Value type: ".concat(Array.isArray(value) ? "array" : _typeof(value)));
425
- console.log("[main loop] Array length: ".concat(Array.isArray(value) ? value.length : "N/A"));
426
- if ((key === "data" || key === "body") && (typeof value === "string" || typeof value === "boolean" || typeof value === "number" || value === null || value === undefined || _typeof(value) === "symbol") && objKeys.length > 1) {
427
- // Special handling: only add to body keys if there's no other data/body field with an object
428
- if (key === "data" && obj.body && isPojo(obj.body) && Object.keys(obj.body).length > 0) {
429
- console.log("[main loop] Skipping special data field");
430
- } else if (key === "body" && obj.data && isPojo(obj.data) && Object.keys(obj.data).length > 0) {
431
- console.log("[main loop] Skipping special body field");
432
- } else {
433
- console.log("[main loop] Adding special data/body key: \"".concat(key, "\""));
434
- keys.push(key);
435
- }
436
- } else if (Array.isArray(value)) {
437
- if (value.length === 0) {
438
- console.log("[main loop] SKIPPING empty array for key: \"".concat(key, "\""));
439
- return 1; // continue
440
- }
441
- var hasObjects = value.some(function (item) {
442
- return isPojo(item);
443
- });
444
- var hasArrays = value.some(function (item) {
445
- return Array.isArray(item);
446
- });
447
- var hasNonObjects = value.some(function (item) {
448
- return !isPojo(item);
449
- });
667
+ }
450
668
 
451
- // Check if this is an array of arrays containing objects
452
- var hasArraysOfObjects = value.some(function (item) {
453
- return Array.isArray(item) && item.some(function (subItem) {
454
- return isPojo(subItem);
455
- });
456
- });
457
- console.log("[main loop] Array analysis: hasObjects=".concat(hasObjects, ", hasArrays=").concat(hasArrays, ", hasNonObjects=").concat(hasNonObjects, ", hasArraysOfObjects=").concat(hasArraysOfObjects));
458
- if (value.length > 0) {
459
- var bodyPartCounter = 1; // Start counting from 1
669
+ // Step 13.2.3: Handle array values
670
+ function handleArrayValue(bodyKey, value, headers, sortedBodyKeys, pathParts) {
671
+ var arrayInfo = (0, _encodeUtils.analyzeArray)(value);
672
+ if (arrayInfo.hasOnlyNonEmptyObjects) {
673
+ return null;
674
+ }
675
+ if (arrayInfo.hasOnlyEmptyElements) {
676
+ return handleArrayWithOnlyEmptyElements(bodyKey, value, headers, sortedBodyKeys);
677
+ }
678
+ var indicesWithOwnParts = buildIndicesWithOwnParts(bodyKey, sortedBodyKeys);
679
+ var hasNestedObjectParts = sortedBodyKeys.some(function (key) {
680
+ return key.startsWith(bodyKey + "/") && key.split("/").length > pathParts.length + 1;
681
+ });
682
+ var _processArrayItems = processArrayItems(value, indicesWithOwnParts, hasNestedObjectParts, pathParts),
683
+ fieldLines = _processArrayItems.fieldLines,
684
+ partTypes = _processArrayItems.partTypes;
685
+ return createArrayBodyPart(bodyKey, fieldLines, partTypes, headers);
686
+ }
460
687
 
461
- // Check for special mixed array case
462
- var hasEmptyStrings = value.some(function (item) {
463
- return typeof item === "string" && item === "";
464
- });
465
- var hasEmptyObjects = value.some(function (item) {
466
- return isPojo(item) && Object.keys(item).length === 0;
467
- });
688
+ // Step 13.2.4.3: Process object fields
689
+ function processObjectFields(value, bodyKey, sortedBodyKeys) {
690
+ var objectTypes = [];
691
+ var fieldLines = [];
692
+ var binaryFields = [];
693
+ var arrayTypes = [];
468
694
 
469
- // Check for objects that contain only empty values
470
- var hasObjectsWithOnlyEmptyValues = value.some(function (item) {
471
- if (!isPojo(item) || Object.keys(item).length === 0) return false;
472
- return Object.values(item).every(function (v) {
473
- return typeof v === "string" && v === "" || Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0;
474
- });
475
- });
476
- if (hasArraysOfObjects) {
477
- // Handle arrays of arrays containing objects
478
- value.forEach(function (item, index) {
479
- if (Array.isArray(item)) {
480
- item.forEach(function (subItem, subIndex) {
481
- if (isPojo(subItem)) {
482
- var path = "".concat(key, "/").concat(index + 1, "/").concat(subIndex + 1);
483
- console.log("[main loop] Adding nested object path: \"".concat(path, "\""));
484
- keys.push(path);
485
- }
486
- });
487
- }
488
- bodyPartCounter++;
489
- });
490
- // Always add the main array key
491
- console.log("[main loop] ADDING main array key: \"".concat(key, "\""));
492
- keys.push(key);
493
- } else if (hasObjects && (hasEmptyStrings || hasEmptyObjects) && !hasObjectsWithOnlyEmptyValues) {
494
- // Special handling: only non-empty objects get parts
495
- value.forEach(function (item, index) {
496
- if (isPojo(item) && Object.keys(item).length > 0) {
497
- var path = "".concat(key, "/").concat(bodyPartCounter);
498
- console.log("[main loop] Adding non-empty object path: \"".concat(path, "\" (array index ").concat(index, ")"));
499
- keys.push(path);
500
- // Add paths for nested objects
501
- for (var _i5 = 0, _Object$entries4 = Object.entries(item); _i5 < _Object$entries4.length; _i5++) {
502
- var _Object$entries4$_i = _slicedToArray(_Object$entries4[_i5], 2),
503
- nestedKey = _Object$entries4$_i[0],
504
- nestedValue = _Object$entries4$_i[1];
505
- if (isPojo(nestedValue)) {
506
- var nestedPath = "".concat(key, "/").concat(bodyPartCounter, "/").concat(nestedKey);
507
- console.log("[main loop] Adding nested object path: \"".concat(nestedPath, "\""));
508
- keys.push(nestedPath);
509
- }
510
- }
511
- }
512
- bodyPartCounter++;
513
- });
514
- // Always add the main array key
515
- console.log("[main loop] ADDING main array key: \"".concat(key, "\""));
516
- keys.push(key);
517
- } else if (hasObjects) {
518
- // Normal handling: all objects get parts (except if parent array has only empty elements)
519
- var skipEmptyObjects = false;
695
+ // First collect array types
696
+ for (var _i3 = 0, _Object$entries3 = Object.entries(value); _i3 < _Object$entries3.length; _i3++) {
697
+ var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
698
+ k = _Object$entries3$_i[0],
699
+ v = _Object$entries3$_i[1];
700
+ if (Array.isArray(v)) {
701
+ arrayTypes.push("".concat(k.toLowerCase(), "=\"").concat(v.length === 0 ? "empty-list" : "list", "\""));
702
+ }
703
+ }
520
704
 
521
- // Check if this array contains only empty elements
522
- var arrayHasOnlyEmptyElements = value.every(function (item) {
523
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
524
- });
525
- if (arrayHasOnlyEmptyElements) {
526
- skipEmptyObjects = true;
527
- }
528
- value.forEach(function (item, index) {
529
- if (isPojo(item)) {
530
- // Skip empty objects if array has only empty elements
531
- if (skipEmptyObjects && Object.keys(item).length === 0) {
532
- bodyPartCounter++;
533
- return;
534
- }
535
- var path = "".concat(key, "/").concat(bodyPartCounter);
536
- console.log("[main loop] Adding object path: \"".concat(path, "\" (array index ").concat(index, ", empty=").concat(Object.keys(item).length === 0, ")"));
537
- keys.push(path);
538
- // Add paths for nested objects (but not empty ones)
539
- if (Object.keys(item).length > 0) {
540
- for (var _i6 = 0, _Object$entries5 = Object.entries(item); _i6 < _Object$entries5.length; _i6++) {
541
- var _Object$entries5$_i = _slicedToArray(_Object$entries5[_i6], 2),
542
- nestedKey = _Object$entries5$_i[0],
543
- nestedValue = _Object$entries5$_i[1];
544
- if (isPojo(nestedValue) && Object.keys(nestedValue).length > 0) {
545
- var nestedPath = "".concat(key, "/").concat(bodyPartCounter, "/").concat(nestedKey);
546
- console.log("[main loop] Adding nested object path: \"".concat(nestedPath, "\""));
547
- keys.push(nestedPath);
548
- }
549
- }
550
- }
551
- } else if (typeof item === "string" && item === "") {
552
- // Empty strings may get parts in some formats
553
- var _path = "".concat(key, "/").concat(bodyPartCounter);
554
- console.log("[main loop] Adding empty string path: \"".concat(_path, "\" (array index ").concat(index, ")"));
555
- keys.push(_path);
556
- }
557
- bodyPartCounter++;
558
- });
559
- // Don't add main array key for arrays with only objects containing empty values
560
- if (!hasObjectsWithOnlyEmptyValues || value.some(function (item) {
561
- return !isPojo(item);
562
- })) {
563
- // Check if array has only empty elements
564
- var hasOnlyEmptyElements = value.every(function (item) {
565
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
566
- });
567
- if (!hasOnlyEmptyElements) {
568
- // Always add the main array key
569
- console.log("[main loop] ADDING main array key: \"".concat(key, "\""));
570
- keys.push(key);
571
- }
572
- }
573
- } else {
574
- // Check if array has only empty elements
575
- var hasOnlyEmptyArraysOrObjects = value.every(function (item) {
576
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
577
- });
578
- if (hasOnlyEmptyArraysOrObjects && value.length > 0) {
579
- // Always add the main array key for arrays with only empty elements
580
- console.log("[main loop] ADDING main array key for empty elements: \"".concat(key, "\""));
581
- keys.push(key);
582
- } else if (!hasOnlyEmptyArraysOrObjects) {
583
- // Always add the main array key
584
- console.log("[main loop] ADDING main array key: \"".concat(key, "\""));
585
- keys.push(key);
586
- }
587
- }
705
+ // Then process other fields
706
+ for (var _i4 = 0, _Object$entries4 = Object.entries(value); _i4 < _Object$entries4.length; _i4++) {
707
+ var _Object$entries4$_i = _slicedToArray(_Object$entries4[_i4], 2),
708
+ _k = _Object$entries4$_i[0],
709
+ _v = _Object$entries4$_i[1];
710
+ var childPath = "".concat(bodyKey, "/").concat(_k);
711
+ if (sortedBodyKeys.includes(childPath)) {
712
+ continue;
713
+ }
714
+ if (Array.isArray(_v) && _v.some(function (item) {
715
+ return (0, _encodeUtils.isPojo)(item);
716
+ })) {
717
+ var hasOnlyEmpty = _v.every(function (item) {
718
+ return (0, _encodeUtils.isEmpty)(item);
719
+ });
720
+ if (hasOnlyEmpty) {
721
+ continue;
588
722
  }
589
- } else if (isPojo(value)) {
590
- console.log("[main loop] Traversing object at key: \"".concat(key, "\""));
591
- // Check if this object contains arrays with only empty elements
592
- var hasArraysWithOnlyEmptyElements = false;
593
- for (var _i7 = 0, _Object$entries6 = Object.entries(value); _i7 < _Object$entries6.length; _i7++) {
594
- var _Object$entries6$_i = _slicedToArray(_Object$entries6[_i7], 2),
595
- k = _Object$entries6$_i[0],
596
- v = _Object$entries6$_i[1];
597
- if (Array.isArray(v) && v.length > 0 && v.every(function (item) {
598
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
599
- })) {
600
- hasArraysWithOnlyEmptyElements = true;
601
- keys.push("".concat(key, "/").concat(k));
723
+ }
724
+ if (Array.isArray(_v)) {
725
+ // Type already added in arrayTypes
726
+ } else if (_v === null || _v === undefined || _typeof(_v) === "symbol" || typeof _v === "boolean") {
727
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"atom\""));
728
+ } else if (typeof _v === "number") {
729
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"").concat(Number.isInteger(_v) ? "integer" : "float", "\""));
730
+ } else if (typeof _v === "string" && _v.length === 0) {
731
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-binary\""));
732
+ } else if ((0, _encodeUtils.isBytes)(_v) && (_v.length === 0 || _v.byteLength === 0)) {
733
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-binary\""));
734
+ } else if ((0, _encodeUtils.isPojo)(_v) && Object.keys(_v).length === 0) {
735
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-message\""));
736
+ }
737
+ if (typeof _v === "string") {
738
+ if (_v.length === 0) {
739
+ fieldLines.push("".concat(_k, ": "));
740
+ } else {
741
+ fieldLines.push("".concat(_k, ": ").concat(_v));
742
+ }
743
+ } else if (typeof _v === "number") {
744
+ fieldLines.push("".concat(_k, ": ").concat(_v));
745
+ } else if (typeof _v === "boolean") {
746
+ fieldLines.push("".concat(_k, ": \"").concat(_v, "\""));
747
+ } else if (_v === null) {
748
+ fieldLines.push("".concat(_k, ": \"null\""));
749
+ } else if (_v === undefined) {
750
+ fieldLines.push("".concat(_k, ": \"undefined\""));
751
+ } else if (_typeof(_v) === "symbol") {
752
+ var desc = _v.description || "Symbol.for()";
753
+ fieldLines.push("".concat(_k, ": \"").concat(desc, "\""));
754
+ } else if ((0, _encodeUtils.isBytes)(_v)) {
755
+ var buffer = (0, _encodeUtils.toBuffer)(_v);
756
+ binaryFields.push({
757
+ key: _k,
758
+ buffer: buffer
759
+ });
760
+ } else if (Array.isArray(_v) && _v.length > 0) {
761
+ var _childPath = "".concat(bodyKey, "/").concat(_k);
762
+ if (!sortedBodyKeys.includes(_childPath)) {
763
+ var hasObjects = _v.some(function (item) {
764
+ return (0, _encodeUtils.isPojo)(item);
765
+ });
766
+ if (!hasObjects) {
767
+ var encodedItems = _v.map(function (item) {
768
+ return (0, _encodeArrayItem["default"])(item);
769
+ }).join(", ");
770
+ fieldLines.push("".concat(_k, ": ").concat(encodedItems));
602
771
  }
603
772
  }
604
- traverse(value, key);
605
- } else if (isBytes(value) && value.length > 0) {
606
- console.log("[main loop] Adding key for non-empty bytes: \"".concat(key, "\""));
607
- keys.push(key);
608
- } else if (typeof value === "string" && value.includes("\n")) {
609
- console.log("[main loop] Adding key for string with newline: \"".concat(key, "\""));
610
- keys.push(key);
611
- } else if (typeof value === "string" && hasNonAscii(value)) {
612
- console.log("[main loop] Adding key for non-ASCII string: \"".concat(key, "\""));
613
- keys.push(key);
614
- } else {
615
- console.log("[main loop] Skipping key: \"".concat(key, "\" (no match)"));
616
773
  }
617
- };
618
- for (var _i4 = 0, _Object$entries3 = Object.entries(obj); _i4 < _Object$entries3.length; _i4++) {
619
- if (_loop2()) continue;
620
774
  }
621
- var result = _toConsumableArray(new Set(keys)).filter(function (k) {
622
- if (k === "") return false;
775
+ var allTypes = [].concat(arrayTypes, objectTypes);
776
+ return {
777
+ allTypes: allTypes,
778
+ fieldLines: fieldLines,
779
+ binaryFields: binaryFields
780
+ };
781
+ }
623
782
 
624
- // Check if this is a path to an empty object inside an array with only empty elements
625
- var parts = k.split("/");
626
- if (parts.length >= 2 && /^\d+$/.test(parts[parts.length - 1])) {
627
- // This is an array element path like "maps/1"
628
- var arrayPath = parts.slice(0, -1).join("/");
629
- var arrayValue = obj;
783
+ // Step 13.2.4.5: Create object body part
784
+ function createObjectBodyPart(bodyKey, value, allTypes, fieldLines, binaryFields, headers, sortedBodyKeys) {
785
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
786
+ var lines = [];
787
+ if (isInline) {
788
+ var orderedLines = [];
630
789
 
631
- // Navigate to the array
632
- var _iterator2 = _createForOfIteratorHelper(parts.slice(0, -1)),
633
- _step2;
790
+ // For inline mode: fields first, then headers
791
+ var _iterator3 = _createForOfIteratorHelper(fieldLines),
792
+ _step3;
793
+ try {
794
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
795
+ var line = _step3.value;
796
+ orderedLines.push(line);
797
+ }
798
+ } catch (err) {
799
+ _iterator3.e(err);
800
+ } finally {
801
+ _iterator3.f();
802
+ }
803
+ if (allTypes.length > 0) {
804
+ orderedLines.push("ao-types: ".concat(allTypes.sort().join(", ")));
805
+ }
806
+ orderedLines.push("content-disposition: inline");
807
+ var binaryFieldsForInline = Object.entries(value).filter(function (_ref) {
808
+ var _ref2 = _slicedToArray(_ref, 2),
809
+ k = _ref2[0],
810
+ v = _ref2[1];
811
+ return (0, _encodeUtils.isBytes)(v) && !sortedBodyKeys.includes("".concat(bodyKey, "/").concat(k));
812
+ }).map(function (_ref3) {
813
+ var _ref4 = _slicedToArray(_ref3, 2),
814
+ k = _ref4[0],
815
+ v = _ref4[1];
816
+ return {
817
+ key: k,
818
+ buffer: (0, _encodeUtils.toBuffer)(v)
819
+ };
820
+ });
821
+ if (binaryFieldsForInline.length > 0) {
822
+ var parts = [];
823
+ // Join all text lines first
824
+ parts.push(Buffer.from(orderedLines.join("\r\n")));
825
+ // Then add binary fields
826
+ var _iterator4 = _createForOfIteratorHelper(binaryFieldsForInline),
827
+ _step4;
634
828
  try {
635
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
636
- var part = _step2.value;
637
- if (/^\d+$/.test(part)) {
638
- arrayValue = arrayValue[parseInt(part) - 1];
639
- } else {
640
- arrayValue = arrayValue[part];
641
- }
829
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
830
+ var _step4$value = _step4.value,
831
+ key = _step4$value.key,
832
+ buffer = _step4$value.buffer;
833
+ parts.push(Buffer.from("\r\n".concat(key, ": ")));
834
+ parts.push(buffer);
642
835
  }
643
-
644
- // Check if this array contains only empty elements
645
836
  } catch (err) {
646
- _iterator2.e(err);
837
+ _iterator4.e(err);
647
838
  } finally {
648
- _iterator2.f();
839
+ _iterator4.f();
649
840
  }
650
- if (Array.isArray(arrayValue)) {
651
- var hasOnlyEmptyElements = arrayValue.every(function (item) {
652
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
653
- });
654
- if (hasOnlyEmptyElements) {
655
- // Filter out paths to individual empty elements
656
- console.log("[filter] Removing path to empty element: \"".concat(k, "\""));
657
- return false;
841
+ parts.push(Buffer.from("\r\n"));
842
+ var fullBody = Buffer.concat(parts);
843
+ return new Blob([fullBody]);
844
+ } else {
845
+ return new Blob([orderedLines.join("\r\n") + "\r\n"]);
846
+ }
847
+ } else {
848
+ // Non-inline mode remains the same
849
+ var _orderedLines3 = [];
850
+ if (allTypes.length > 0) {
851
+ _orderedLines3.push("ao-types: ".concat(allTypes.sort().join(", ")));
852
+ }
853
+ _orderedLines3.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
854
+ var hasBinaryFields = binaryFields && binaryFields.length > 0;
855
+ if (hasBinaryFields || fieldLines.length === 0) {
856
+ _orderedLines3.push("");
857
+ }
858
+ var _iterator5 = _createForOfIteratorHelper(fieldLines),
859
+ _step5;
860
+ try {
861
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
862
+ var _line2 = _step5.value;
863
+ _orderedLines3.push(_line2);
864
+ }
865
+ } catch (err) {
866
+ _iterator5.e(err);
867
+ } finally {
868
+ _iterator5.f();
869
+ }
870
+ if (binaryFields && binaryFields.length > 0) {
871
+ var _parts = [];
872
+ var headerText = _orderedLines3.join("\r\n");
873
+ _parts.push(Buffer.from(headerText));
874
+ for (var i = 0; i < binaryFields.length; i++) {
875
+ var _binaryFields$i = binaryFields[i],
876
+ _key = _binaryFields$i.key,
877
+ _buffer = _binaryFields$i.buffer;
878
+ if (i > 0) {
879
+ _parts.push(Buffer.from("\r\n"));
658
880
  }
881
+ _parts.push(Buffer.from("".concat(_key, ": ")));
882
+ _parts.push(_buffer);
883
+ }
884
+ _parts.push(Buffer.from("\r\n"));
885
+ var _fullBody = Buffer.concat(_parts);
886
+ return new Blob([_fullBody]);
887
+ } else {
888
+ if (fieldLines.length > 0) {
889
+ return new Blob([_orderedLines3.join("\r\n") + "\r\n"]);
890
+ } else {
891
+ return new Blob([_orderedLines3.join("\r\n")]);
659
892
  }
660
893
  }
661
- return true;
894
+ }
895
+ }
896
+
897
+ // Step 13.2.4: Handle object values
898
+ function handleObjectValue(obj, bodyKey, value, headers, sortedBodyKeys, pathParts, hasSpecialDataBody) {
899
+ if (Object.keys(value).length === 0) {
900
+ // Skip empty objects in certain contexts
901
+ var parentPath = pathParts.slice(0, -1).join("/");
902
+ var parentValue = parentPath ? (0, _encodeUtils.getValueByPath)(obj, parentPath) : obj;
903
+ if (Array.isArray(parentValue)) {
904
+ var parentArrayInfo = (0, _encodeUtils.analyzeArray)(parentValue);
905
+ if (parentArrayInfo.hasObjects && (parentArrayInfo.hasEmptyStrings || parentArrayInfo.hasEmptyObjects)) {
906
+ return null;
907
+ }
908
+ }
909
+ return null;
910
+ }
911
+
912
+ // Skip special data/body case
913
+ if (hasSpecialDataBody && bodyKey === "data" && Object.keys(value).length === 1 && value.body && (0, _encodeUtils.isBytes)(value.body)) {
914
+ return null;
915
+ }
916
+ var _processObjectFields = processObjectFields(value, bodyKey, sortedBodyKeys),
917
+ allTypes = _processObjectFields.allTypes,
918
+ fieldLines = _processObjectFields.fieldLines,
919
+ binaryFields = _processObjectFields.binaryFields;
920
+
921
+ // Check if object should be skipped
922
+ var hasOnlyEmptyCollections = Object.entries(value).every(function (_ref5) {
923
+ var _ref6 = _slicedToArray(_ref5, 2),
924
+ k = _ref6[0],
925
+ v = _ref6[1];
926
+ return (0, _encodeUtils.isEmpty)(v);
927
+ });
928
+ var hasArraysWithOnlyEmptyElements = Object.entries(value).some(function (_ref7) {
929
+ var _ref8 = _slicedToArray(_ref7, 2),
930
+ k = _ref8[0],
931
+ v = _ref8[1];
932
+ return Array.isArray(v) && v.length > 0 && v.every(function (item) {
933
+ return (0, _encodeUtils.isEmpty)(item);
934
+ });
662
935
  });
663
- console.log("\n=== collectBodyKeys RESULT ===");
664
- console.log("Final bodyKeys:", JSON.stringify(result));
665
- console.log("=== collectBodyKeys END ===\n");
666
- return result;
936
+ var shouldSkipObject = Object.entries(value).every(function (_ref9) {
937
+ var _ref10 = _slicedToArray(_ref9, 2),
938
+ k = _ref10[0],
939
+ v = _ref10[1];
940
+ var childPath = "".concat(bodyKey, "/").concat(k);
941
+ if (sortedBodyKeys.includes(childPath)) return true;
942
+ if (Array.isArray(v) && v.some(function (item) {
943
+ return (0, _encodeUtils.isPojo)(item);
944
+ })) {
945
+ var hasOnlyEmpty = v.every(function (item) {
946
+ return (0, _encodeUtils.isEmpty)(item);
947
+ });
948
+ return hasOnlyEmpty || sortedBodyKeys.includes(childPath);
949
+ }
950
+ return false;
951
+ });
952
+ if (shouldSkipObject && !hasOnlyEmptyCollections && !hasArraysWithOnlyEmptyElements) {
953
+ return null;
954
+ }
955
+ return createObjectBodyPart(bodyKey, value, allTypes, fieldLines, binaryFields, headers, sortedBodyKeys);
956
+ }
957
+
958
+ // Step 13.2.5: Handle primitive values
959
+ function handlePrimitiveValue(bodyKey, value, headers) {
960
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
961
+ var lines = [];
962
+ if (isInline) {
963
+ lines.push("content-disposition: inline");
964
+ } else {
965
+ lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
966
+ }
967
+ if (typeof value === "string") {
968
+ lines.push("");
969
+ lines.push(value);
970
+ return new Blob([lines.join("\r\n")]);
971
+ } else {
972
+ var content = (0, _encodeUtils.encodePrimitiveContent)(value);
973
+ lines.push("");
974
+ lines.push(content);
975
+ return new Blob([lines.join("\r\n")]);
976
+ }
977
+ }
978
+
979
+ // Step 13.2.6: Handle binary values
980
+ function handleBinaryValue(bodyKey, value, headers) {
981
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
982
+ var lines = [];
983
+ if (isInline) {
984
+ lines.push("content-disposition: inline");
985
+ } else {
986
+ lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
987
+ }
988
+ var buffer = (0, _encodeUtils.toBuffer)(value);
989
+ var headerText = lines.join("\r\n") + "\r\n\r\n";
990
+ return new Blob([headerText, buffer]);
991
+ }
992
+
993
+ // Step 13.3: Handle special data/body case
994
+ function handleSpecialDataBodyCase(obj, hasSpecialDataBody) {
995
+ if (hasSpecialDataBody && obj.data && obj.data.body && (0, _encodeUtils.isBytes)(obj.data.body)) {
996
+ var buffer = (0, _encodeUtils.toBuffer)(obj.data.body);
997
+ var specialPart = ["content-disposition: form-data;name=\"data/body\"", "", ""].join("\r\n");
998
+ return new Blob([specialPart, buffer]);
999
+ }
1000
+ return null;
1001
+ }
1002
+
1003
+ // Step 13: Build body parts for each body key
1004
+ function buildBodyParts(obj, sortedBodyKeys, headers, hasSpecialDataBody) {
1005
+ // Step 13.1: Initialize body parts collection
1006
+ var bodyParts = [];
1007
+
1008
+ // Step 13.2: Process each body key
1009
+ var _iterator6 = _createForOfIteratorHelper(sortedBodyKeys),
1010
+ _step6;
1011
+ try {
1012
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1013
+ var bodyKey = _step6.value;
1014
+ // Step 13.2.1: Get value for current body key
1015
+ var value = (0, _encodeUtils.getValueByPath)(obj, bodyKey);
1016
+ var pathParts = bodyKey.split("/");
1017
+
1018
+ // Step 13.2.2: Handle empty string in nested path
1019
+ var emptyStringPart = handleEmptyStringInNestedPath(bodyKey, value, pathParts);
1020
+ if (emptyStringPart) {
1021
+ bodyParts.push(emptyStringPart);
1022
+ continue;
1023
+ }
1024
+
1025
+ // Step 13.2.3: Handle array values
1026
+ if (Array.isArray(value)) {
1027
+ var arrayPart = handleArrayValue(bodyKey, value, headers, sortedBodyKeys, pathParts);
1028
+ if (arrayPart) {
1029
+ bodyParts.push(arrayPart);
1030
+ }
1031
+ continue;
1032
+ }
1033
+
1034
+ // Step 13.2.4: Handle object values
1035
+ if ((0, _encodeUtils.isPojo)(value)) {
1036
+ var objectPart = handleObjectValue(obj, bodyKey, value, headers, sortedBodyKeys, pathParts, hasSpecialDataBody);
1037
+ if (objectPart) {
1038
+ bodyParts.push(objectPart);
1039
+ }
1040
+ continue;
1041
+ }
1042
+
1043
+ // Step 13.2.5: Handle primitive values
1044
+ if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" || value === null || value === undefined || _typeof(value) === "symbol") {
1045
+ var primitivePart = handlePrimitiveValue(bodyKey, value, headers);
1046
+ bodyParts.push(primitivePart);
1047
+ continue;
1048
+ }
1049
+
1050
+ // Step 13.2.6: Handle binary values
1051
+ if ((0, _encodeUtils.isBytes)(value)) {
1052
+ var binaryPart = handleBinaryValue(bodyKey, value, headers);
1053
+ bodyParts.push(binaryPart);
1054
+ continue;
1055
+ }
1056
+ }
1057
+
1058
+ // Step 13.3: Handle special data/body case
1059
+ } catch (err) {
1060
+ _iterator6.e(err);
1061
+ } finally {
1062
+ _iterator6.f();
1063
+ }
1064
+ var specialPart = handleSpecialDataBodyCase(obj, hasSpecialDataBody);
1065
+ if (specialPart) {
1066
+ bodyParts.push(specialPart);
1067
+ }
1068
+
1069
+ // Step 13.4: Return body parts
1070
+ return bodyParts;
1071
+ }
1072
+
1073
+ // Step 14: Generate multipart boundary
1074
+ function generateBoundary(_x9) {
1075
+ return _generateBoundary.apply(this, arguments);
1076
+ } // Step 15: Assemble final multipart body
1077
+ function _generateBoundary() {
1078
+ _generateBoundary = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(bodyParts) {
1079
+ var partsContent, allContent, boundaryHash, boundary;
1080
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1081
+ while (1) switch (_context6.prev = _context6.next) {
1082
+ case 0:
1083
+ _context6.next = 2;
1084
+ return Promise.all(bodyParts.map(function (part) {
1085
+ return part.text();
1086
+ }));
1087
+ case 2:
1088
+ partsContent = _context6.sent;
1089
+ allContent = partsContent.join("");
1090
+ _context6.next = 6;
1091
+ return (0, _encodeUtils.sha256)(new TextEncoder().encode(allContent));
1092
+ case 6:
1093
+ boundaryHash = _context6.sent;
1094
+ boundary = _base64url["default"].encode(Buffer.from(boundaryHash));
1095
+ return _context6.abrupt("return", boundary);
1096
+ case 9:
1097
+ case "end":
1098
+ return _context6.stop();
1099
+ }
1100
+ }, _callee6);
1101
+ }));
1102
+ return _generateBoundary.apply(this, arguments);
1103
+ }
1104
+ function assembleMultipartBody(bodyParts, boundary) {
1105
+ var finalParts = [];
1106
+ for (var i = 0; i < bodyParts.length; i++) {
1107
+ if (i === 0) {
1108
+ finalParts.push(new Blob(["--".concat(boundary, "\r\n")]));
1109
+ } else {
1110
+ finalParts.push(new Blob(["\r\n--".concat(boundary, "\r\n")]));
1111
+ }
1112
+ finalParts.push(bodyParts[i]);
1113
+ }
1114
+ finalParts.push(new Blob(["\r\n--".concat(boundary, "--")]));
1115
+ return new Blob(finalParts);
1116
+ }
1117
+
1118
+ // Step 16: Calculate content digest
1119
+ function calculateContentDigest(_x10) {
1120
+ return _calculateContentDigest.apply(this, arguments);
1121
+ } // Step 17: Set final headers (content-type, content-length)
1122
+ function _calculateContentDigest() {
1123
+ _calculateContentDigest = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(body) {
1124
+ var finalContent, contentDigest, base64;
1125
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1126
+ while (1) switch (_context7.prev = _context7.next) {
1127
+ case 0:
1128
+ _context7.next = 2;
1129
+ return body.arrayBuffer();
1130
+ case 2:
1131
+ finalContent = _context7.sent;
1132
+ if (!(finalContent.byteLength > 0)) {
1133
+ _context7.next = 9;
1134
+ break;
1135
+ }
1136
+ _context7.next = 6;
1137
+ return (0, _encodeUtils.sha256)(finalContent);
1138
+ case 6:
1139
+ contentDigest = _context7.sent;
1140
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
1141
+ return _context7.abrupt("return", {
1142
+ digest: base64,
1143
+ byteLength: finalContent.byteLength
1144
+ });
1145
+ case 9:
1146
+ return _context7.abrupt("return", {
1147
+ digest: null,
1148
+ byteLength: finalContent.byteLength
1149
+ });
1150
+ case 10:
1151
+ case "end":
1152
+ return _context7.stop();
1153
+ }
1154
+ }, _callee7);
1155
+ }));
1156
+ return _calculateContentDigest.apply(this, arguments);
1157
+ }
1158
+ function setFinalHeaders(headers, boundary, contentDigest, byteLength) {
1159
+ headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
1160
+ if (contentDigest) {
1161
+ headers["content-digest"] = "sha-256=:".concat(contentDigest, ":");
1162
+ }
1163
+ headers["content-length"] = String(byteLength);
667
1164
  }
668
1165
  function encode() {
669
1166
  return _encode.apply(this, arguments);
670
1167
  }
671
1168
  function _encode() {
672
- _encode = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1169
+ _encode = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
673
1170
  var obj,
674
- _processValue,
675
1171
  processedObj,
676
- _i9,
677
- _Object$entries8,
678
- _Object$entries8$_i,
679
- k,
680
- v,
1172
+ emptyResult,
1173
+ emptyBinaryResult,
1174
+ singleBinaryResult,
1175
+ primitiveResult,
1176
+ nonEmptyBinaryResult,
1177
+ nonAsciiResult,
1178
+ bodyKeys,
681
1179
  objKeys,
682
- fieldName,
683
- fieldValue,
684
- _headers,
685
- hasBodyBinary,
686
- otherFields,
687
- _headers2,
688
- bodyBuffer,
689
- bodyArrayBuffer,
690
- contentDigest,
691
- base64,
692
- _fieldName,
693
- _fieldValue,
694
- _headers3,
695
- _bodyBuffer,
696
- _bodyArrayBuffer,
697
- _contentDigest,
698
- _base,
699
- _headers4,
700
- bodyContent,
701
- encoder,
702
- encoded,
703
- _contentDigest2,
704
- _base2,
705
- _headers5,
706
- _encoder,
707
- _encoded,
708
- _contentDigest3,
709
- _base3,
710
1180
  headers,
711
1181
  headerTypes,
712
- bodyKeys,
713
- _loop3,
714
- _i10,
715
- _Object$entries9,
716
- _loop4,
717
- _i11,
718
- _Object$entries10,
719
- allBodyKeysAreEmptyBinaries,
720
- singleKey,
721
- pathParts,
722
- value,
723
- _iterator4,
724
- _step4,
725
- part,
726
- otherFieldsAreEmpty,
727
- _bodyBuffer2,
728
- _bodyArrayBuffer2,
729
- _contentDigest4,
730
- _base4,
1182
+ emptyBinaryBodyResult,
1183
+ singleBodyKeyResult,
731
1184
  sortedBodyKeys,
732
1185
  hasSpecialDataBody,
1186
+ bodyValue,
733
1187
  bodyParts,
734
- _iterator5,
735
- _step5,
736
- _loop5,
737
- _ret,
738
- buffer,
739
- specialPart,
740
- partsContent,
741
- allContent,
742
- boundaryHash,
743
1188
  boundary,
744
- finalParts,
745
- i,
746
1189
  body,
747
- finalContent,
748
- _contentDigest5,
749
- _base5,
750
- _args6 = arguments;
751
- return _regeneratorRuntime().wrap(function _callee3$(_context6) {
752
- while (1) switch (_context6.prev = _context6.next) {
1190
+ _yield$calculateConte,
1191
+ contentDigest,
1192
+ byteLength,
1193
+ _args8 = arguments;
1194
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1195
+ while (1) switch (_context8.prev = _context8.next) {
753
1196
  case 0:
754
- obj = _args6.length > 0 && _args6[0] !== undefined ? _args6[0] : {};
755
- console.log("\n=== ENCODE START ===");
756
- console.log("Encoding object:", JSON.stringify(obj));
757
- _processValue = function processValue(value) {
758
- if (_typeof(value) === "symbol") {
759
- return value.description || "Symbol.for()";
760
- } else if (Array.isArray(value)) {
761
- return value.map(_processValue);
762
- } else if (isPojo(value)) {
763
- var result = {};
764
- for (var _i8 = 0, _Object$entries7 = Object.entries(value); _i8 < _Object$entries7.length; _i8++) {
765
- var _Object$entries7$_i = _slicedToArray(_Object$entries7[_i8], 2),
766
- k = _Object$entries7$_i[0],
767
- v = _Object$entries7$_i[1];
768
- result[k] = _processValue(v);
769
- }
770
- return result;
771
- }
772
- return value;
773
- };
774
- processedObj = {};
775
- for (_i9 = 0, _Object$entries8 = Object.entries(obj); _i9 < _Object$entries8.length; _i9++) {
776
- _Object$entries8$_i = _slicedToArray(_Object$entries8[_i9], 2), k = _Object$entries8$_i[0], v = _Object$entries8$_i[1];
777
- processedObj[k] = _processValue(v);
1197
+ obj = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : {};
1198
+ // Step 1: Process and normalize input values
1199
+ processedObj = processInputValues(obj); // Step 2: Handle empty object case
1200
+ emptyResult = handleEmptyObject(processedObj);
1201
+ if (!emptyResult) {
1202
+ _context8.next = 5;
1203
+ break;
778
1204
  }
779
- if (!(Object.keys(obj).length === 0)) {
780
- _context6.next = 8;
1205
+ return _context8.abrupt("return", emptyResult);
1206
+ case 5:
1207
+ // Step 3: Handle single field with empty binary
1208
+ emptyBinaryResult = handleSingleEmptyBinaryField(processedObj);
1209
+ if (!emptyBinaryResult) {
1210
+ _context8.next = 8;
781
1211
  break;
782
1212
  }
783
- return _context6.abrupt("return", {
784
- headers: {},
785
- body: undefined
786
- });
1213
+ return _context8.abrupt("return", emptyBinaryResult);
787
1214
  case 8:
788
- objKeys = Object.keys(obj);
789
- if (!(objKeys.length === 1)) {
790
- _context6.next = 16;
1215
+ _context8.next = 10;
1216
+ return handleSingleBinaryField(processedObj);
1217
+ case 10:
1218
+ singleBinaryResult = _context8.sent;
1219
+ if (!singleBinaryResult) {
1220
+ _context8.next = 13;
791
1221
  break;
792
1222
  }
793
- fieldName = objKeys[0];
794
- fieldValue = obj[fieldName];
795
- if (!(isBytes(fieldValue) && (fieldValue.length === 0 || fieldValue.byteLength === 0))) {
796
- _context6.next = 16;
1223
+ return _context8.abrupt("return", singleBinaryResult);
1224
+ case 13:
1225
+ _context8.next = 15;
1226
+ return handleSinglePrimitiveField(processedObj);
1227
+ case 15:
1228
+ primitiveResult = _context8.sent;
1229
+ if (!primitiveResult) {
1230
+ _context8.next = 18;
797
1231
  break;
798
1232
  }
799
- _headers = {};
800
- _headers["ao-types"] = "".concat(fieldName.toLowerCase(), "=\"empty-binary\"");
801
- return _context6.abrupt("return", {
802
- headers: _headers,
803
- body: undefined
804
- });
805
- case 16:
806
- if (obj.body && isBytes(obj.body) && (obj.body.length === 0 || obj.body.byteLength === 0) && objKeys.length > 1) {}
807
- hasBodyBinary = obj.body && isBytes(obj.body);
808
- otherFields = Object.keys(obj).filter(function (k) {
809
- return k !== "body";
810
- });
811
- if (!(hasBodyBinary && otherFields.length === 0)) {
812
- _context6.next = 29;
1233
+ return _context8.abrupt("return", primitiveResult);
1234
+ case 18:
1235
+ _context8.next = 20;
1236
+ return handleSingleNonEmptyBinaryField(processedObj);
1237
+ case 20:
1238
+ nonEmptyBinaryResult = _context8.sent;
1239
+ if (!nonEmptyBinaryResult) {
1240
+ _context8.next = 23;
813
1241
  break;
814
1242
  }
815
- _headers2 = {};
816
- bodyBuffer = toBuffer(obj.body);
817
- bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
818
- _context6.next = 25;
819
- return sha256(bodyArrayBuffer);
1243
+ return _context8.abrupt("return", nonEmptyBinaryResult);
1244
+ case 23:
1245
+ _context8.next = 25;
1246
+ return handleSingleNonAsciiStringField(processedObj);
820
1247
  case 25:
821
- contentDigest = _context6.sent;
822
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
823
- _headers2["content-digest"] = "sha-256=:".concat(base64, ":");
824
- return _context6.abrupt("return", {
825
- headers: _headers2,
826
- body: obj.body
827
- });
828
- case 29:
829
- if (!(objKeys.length === 1)) {
830
- _context6.next = 71;
831
- break;
832
- }
833
- _fieldName = objKeys[0];
834
- _fieldValue = obj[_fieldName];
835
- if (!(isBytes(_fieldValue) && _fieldValue.length > 0)) {
836
- _context6.next = 45;
837
- break;
838
- }
839
- _headers3 = {};
840
- _bodyBuffer = toBuffer(_fieldValue);
841
- _bodyArrayBuffer = _bodyBuffer.buffer.slice(_bodyBuffer.byteOffset, _bodyBuffer.byteOffset + _bodyBuffer.byteLength);
842
- _context6.next = 38;
843
- return sha256(_bodyArrayBuffer);
844
- case 38:
845
- _contentDigest = _context6.sent;
846
- _base = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest));
847
- _headers3["content-digest"] = "sha-256=:".concat(_base, ":");
848
- if (_fieldName !== "body") {
849
- _headers3["inline-body-key"] = _fieldName;
850
- }
851
- return _context6.abrupt("return", {
852
- headers: _headers3,
853
- body: _fieldValue
854
- });
855
- case 45:
856
- if (!((_fieldName === "data" || _fieldName === "body") && (typeof _fieldValue === "string" || typeof _fieldValue === "boolean" || typeof _fieldValue === "number" || _fieldValue === null || _fieldValue === undefined || _typeof(_fieldValue) === "symbol"))) {
857
- _context6.next = 60;
1248
+ nonAsciiResult = _context8.sent;
1249
+ if (!nonAsciiResult) {
1250
+ _context8.next = 28;
858
1251
  break;
859
1252
  }
860
- _headers4 = {};
861
- if (typeof _fieldValue === "string") {
862
- bodyContent = _fieldValue;
863
- } else if (typeof _fieldValue === "boolean") {
864
- bodyContent = "\"".concat(_fieldValue, "\"");
865
- } else if (typeof _fieldValue === "number") {
866
- bodyContent = String(_fieldValue);
867
- } else if (_fieldValue === null) {
868
- bodyContent = '"null"';
869
- } else if (_fieldValue === undefined) {
870
- bodyContent = '"undefined"';
871
- } else if (_typeof(_fieldValue) === "symbol") {
872
- bodyContent = "\"".concat(_fieldValue.description || "Symbol.for()", "\"");
873
- }
874
- encoder = new TextEncoder();
875
- encoded = encoder.encode(bodyContent);
876
- _context6.next = 52;
877
- return sha256(encoded.buffer);
878
- case 52:
879
- _contentDigest2 = _context6.sent;
880
- _base2 = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest2));
881
- _headers4["content-digest"] = "sha-256=:".concat(_base2, ":");
882
- if (typeof _fieldValue === "boolean" || _fieldValue === null || _fieldValue === undefined || _typeof(_fieldValue) === "symbol") {
883
- _headers4["ao-types"] = "".concat(_fieldName.toLowerCase(), "=\"atom\"");
884
- } else if (typeof _fieldValue === "number") {
885
- _headers4["ao-types"] = "".concat(_fieldName.toLowerCase(), "=\"").concat(Number.isInteger(_fieldValue) ? "integer" : "float", "\"");
886
- }
887
- if (_fieldName !== "body") {
888
- _headers4["inline-body-key"] = _fieldName;
889
- }
890
- return _context6.abrupt("return", {
891
- headers: _headers4,
892
- body: bodyContent
893
- });
894
- case 60:
895
- if (!(typeof _fieldValue === "string" && hasNonAscii(_fieldValue))) {
896
- _context6.next = 71;
897
- break;
898
- }
899
- _headers5 = {};
900
- _encoder = new TextEncoder();
901
- _encoded = _encoder.encode(_fieldValue);
902
- _context6.next = 66;
903
- return sha256(_encoded.buffer);
904
- case 66:
905
- _contentDigest3 = _context6.sent;
906
- _base3 = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest3));
907
- _headers5["content-digest"] = "sha-256=:".concat(_base3, ":");
908
- if (_fieldName !== "body") {
909
- _headers5["inline-body-key"] = _fieldName;
910
- }
911
- return _context6.abrupt("return", {
912
- headers: _headers5,
913
- body: _fieldValue
914
- });
915
- case 71:
1253
+ return _context8.abrupt("return", nonAsciiResult);
1254
+ case 28:
1255
+ // Step 7: Collect all keys that need to go in body
1256
+ bodyKeys = collectBodyKeysStep(processedObj);
1257
+ objKeys = Object.keys(obj);
916
1258
  headers = {};
917
- headerTypes = [];
918
- bodyKeys = collectBodyKeys(obj);
919
- _loop3 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop3() {
920
- var _Object$entries9$_i, key, value, needsBody, hasNonAsciiItems, encodedItems;
921
- return _regeneratorRuntime().wrap(function _loop3$(_context3) {
922
- while (1) switch (_context3.prev = _context3.next) {
923
- case 0:
924
- _Object$entries9$_i = _slicedToArray(_Object$entries9[_i10], 2), key = _Object$entries9$_i[0], value = _Object$entries9$_i[1];
925
- needsBody = bodyKeys.includes(key) || bodyKeys.some(function (k) {
926
- return k.startsWith("".concat(key, "/"));
927
- });
928
- if (needsBody) {
929
- _context3.next = 43;
930
- break;
931
- }
932
- if (!(value === null)) {
933
- _context3.next = 8;
934
- break;
935
- }
936
- headers[key] = '"null"';
937
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
938
- _context3.next = 41;
939
- break;
940
- case 8:
941
- if (!(value === undefined)) {
942
- _context3.next = 13;
943
- break;
944
- }
945
- headers[key] = '"undefined"';
946
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
947
- _context3.next = 41;
948
- break;
949
- case 13:
950
- if (!(typeof value === "boolean")) {
951
- _context3.next = 18;
952
- break;
953
- }
954
- headers[key] = "\"".concat(value, "\"");
955
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
956
- _context3.next = 41;
957
- break;
958
- case 18:
959
- if (!(_typeof(value) === "symbol")) {
960
- _context3.next = 23;
961
- break;
962
- }
963
- headers[key] = "\"".concat(value.description || "Symbol.for()", "\"");
964
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
965
- _context3.next = 41;
966
- break;
967
- case 23:
968
- if (!(typeof value === "number")) {
969
- _context3.next = 28;
970
- break;
971
- }
972
- headers[key] = String(value);
973
- headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
974
- _context3.next = 41;
975
- break;
976
- case 28:
977
- if (!(typeof value === "string")) {
978
- _context3.next = 40;
979
- break;
980
- }
981
- if (!(value.length === 0)) {
982
- _context3.next = 33;
983
- break;
984
- }
985
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
986
- _context3.next = 38;
987
- break;
988
- case 33:
989
- if (!hasNonAscii(value)) {
990
- _context3.next = 37;
991
- break;
992
- }
993
- return _context3.abrupt("return", 1);
994
- case 37:
995
- headers[key] = value;
996
- case 38:
997
- _context3.next = 41;
998
- break;
999
- case 40:
1000
- if (Array.isArray(value) && value.length === 0) {
1001
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-list\""));
1002
- } else if (Array.isArray(value) && !value.some(function (item) {
1003
- return isPojo(item);
1004
- })) {
1005
- hasNonAsciiItems = value.some(function (item) {
1006
- return typeof item === "string" && hasNonAscii(item);
1007
- });
1008
- if (!hasNonAsciiItems) {
1009
- encodedItems = value.map(function (item) {
1010
- return encodeArrayItem(item);
1011
- }).join(", ");
1012
- headers[key] = encodedItems;
1013
- headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
1014
- }
1015
- } else if (isBytes(value) && (value.length === 0 || value.byteLength === 0)) {
1016
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
1017
- } else if (isPojo(value) && Object.keys(value).length === 0) {
1018
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-message\""));
1019
- }
1020
- case 41:
1021
- _context3.next = 44;
1022
- break;
1023
- case 43:
1024
- if (isBytes(value) && (value.length === 0 || value.byteLength === 0)) {
1025
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
1026
- } else if (typeof value === "string" && value.length === 0) {
1027
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
1028
- } else if (Array.isArray(value) && value.length === 0) {
1029
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-list\""));
1030
- } else if (isPojo(value) && Object.keys(value).length === 0) {
1031
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-message\""));
1032
- } else if (typeof value === "boolean" || value === null || value === undefined || _typeof(value) === "symbol") {
1033
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
1034
- } else if (typeof value === "number") {
1035
- headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
1036
- }
1037
- case 44:
1038
- case "end":
1039
- return _context3.stop();
1040
- }
1041
- }, _loop3);
1042
- });
1043
- _i10 = 0, _Object$entries9 = Object.entries(obj);
1044
- case 76:
1045
- if (!(_i10 < _Object$entries9.length)) {
1046
- _context6.next = 83;
1047
- break;
1048
- }
1049
- return _context6.delegateYield(_loop3(), "t0", 78);
1050
- case 78:
1051
- if (!_context6.t0) {
1052
- _context6.next = 80;
1053
- break;
1054
- }
1055
- return _context6.abrupt("continue", 80);
1056
- case 80:
1057
- _i10++;
1058
- _context6.next = 76;
1059
- break;
1060
- case 83:
1061
- _loop4 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop4() {
1062
- var _Object$entries10$_i, key, value;
1063
- return _regeneratorRuntime().wrap(function _loop4$(_context4) {
1064
- while (1) switch (_context4.prev = _context4.next) {
1065
- case 0:
1066
- _Object$entries10$_i = _slicedToArray(_Object$entries10[_i11], 2), key = _Object$entries10$_i[0], value = _Object$entries10$_i[1];
1067
- if (Array.isArray(value)) {
1068
- if (bodyKeys.includes(key) || bodyKeys.some(function (k) {
1069
- return k.startsWith("".concat(key, "/"));
1070
- })) {
1071
- if (!headerTypes.some(function (t) {
1072
- return t.startsWith("".concat(key.toLowerCase(), "="));
1073
- })) {
1074
- headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
1075
- }
1076
- }
1077
- }
1078
- case 2:
1079
- case "end":
1080
- return _context4.stop();
1081
- }
1082
- }, _loop4);
1083
- });
1084
- _i11 = 0, _Object$entries10 = Object.entries(obj);
1085
- case 85:
1086
- if (!(_i11 < _Object$entries10.length)) {
1087
- _context6.next = 90;
1088
- break;
1089
- }
1090
- return _context6.delegateYield(_loop4(), "t1", 87);
1091
- case 87:
1092
- _i11++;
1093
- _context6.next = 85;
1094
- break;
1095
- case 90:
1096
- if (!(bodyKeys.length === 0)) {
1097
- _context6.next = 94;
1098
- break;
1099
- }
1100
- console.log("No bodyKeys, returning headers only");
1101
- if (headerTypes.length > 0) {
1102
- headers["ao-types"] = headerTypes.sort().join(", ");
1103
- }
1104
- return _context6.abrupt("return", {
1105
- headers: headers,
1106
- body: undefined
1107
- });
1108
- case 94:
1109
- allBodyKeysAreEmptyBinaries = bodyKeys.every(function (key) {
1110
- var pathParts = key.split("/");
1111
- var value = obj;
1112
- var _iterator3 = _createForOfIteratorHelper(pathParts),
1113
- _step3;
1114
- try {
1115
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1116
- var part = _step3.value;
1117
- if (/^\d+$/.test(part)) {
1118
- var index = parseInt(part) - 1;
1119
- console.log("[Body part] Getting array element at index ".concat(index, " from part ").concat(part));
1120
- value = value[index];
1121
- } else {
1122
- value = value[part];
1123
- }
1124
- }
1125
- } catch (err) {
1126
- _iterator3.e(err);
1127
- } finally {
1128
- _iterator3.f();
1129
- }
1130
- return isBytes(value) && (value.length === 0 || value.byteLength === 0);
1131
- });
1132
- if (!allBodyKeysAreEmptyBinaries) {
1133
- _context6.next = 98;
1134
- break;
1135
- }
1136
- if (headerTypes.length > 0) {
1137
- headers["ao-types"] = headerTypes.sort().join(", ");
1138
- }
1139
- return _context6.abrupt("return", {
1140
- headers: headers,
1141
- body: undefined
1142
- });
1143
- case 98:
1144
- if (!(bodyKeys.length === 1)) {
1145
- _context6.next = 116;
1259
+ headerTypes = []; // Step 8: Process fields that can go in headers
1260
+ processHeaderFields(obj, bodyKeys, headers, headerTypes);
1261
+
1262
+ // Step 9: Handle case where all body keys are empty binaries
1263
+ emptyBinaryBodyResult = handleAllEmptyBinaryBodyKeys(obj, bodyKeys, headers, headerTypes);
1264
+ if (!emptyBinaryBodyResult) {
1265
+ _context8.next = 36;
1146
1266
  break;
1147
1267
  }
1148
- singleKey = bodyKeys[0];
1149
- pathParts = singleKey.split("/");
1150
- value = obj;
1151
- _iterator4 = _createForOfIteratorHelper(pathParts);
1152
- try {
1153
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1154
- part = _step4.value;
1155
- if (/^\d+$/.test(part)) {
1156
- value = value[parseInt(part) - 1];
1157
- } else {
1158
- value = value[part];
1159
- }
1160
- }
1161
- } catch (err) {
1162
- _iterator4.e(err);
1163
- } finally {
1164
- _iterator4.f();
1165
- }
1166
- otherFieldsAreEmpty = Object.entries(obj).every(function (_ref5) {
1167
- var _ref6 = _slicedToArray(_ref5, 2),
1168
- key = _ref6[0],
1169
- val = _ref6[1];
1170
- if (key === singleKey) return true;
1171
- return Array.isArray(val) && val.length === 0 || isPojo(val) && Object.keys(val).length === 0 || isBytes(val) && (val.length === 0 || val.byteLength === 0) || typeof val === "string" && val.length === 0;
1172
- });
1173
- if (!(otherFieldsAreEmpty && isBytes(value) && value.length > 0)) {
1174
- _context6.next = 116;
1268
+ return _context8.abrupt("return", emptyBinaryBodyResult);
1269
+ case 36:
1270
+ _context8.next = 38;
1271
+ return handleSingleBodyKeyOptimization(obj, bodyKeys, headers, headerTypes);
1272
+ case 38:
1273
+ singleBodyKeyResult = _context8.sent;
1274
+ if (!singleBodyKeyResult) {
1275
+ _context8.next = 41;
1175
1276
  break;
1176
1277
  }
1177
- _bodyBuffer2 = toBuffer(value);
1178
- _bodyArrayBuffer2 = _bodyBuffer2.buffer.slice(_bodyBuffer2.byteOffset, _bodyBuffer2.byteOffset + _bodyBuffer2.byteLength);
1179
- _context6.next = 110;
1180
- return sha256(_bodyArrayBuffer2);
1181
- case 110:
1182
- _contentDigest4 = _context6.sent;
1183
- _base4 = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest4));
1184
- headers["content-digest"] = "sha-256=:".concat(_base4, ":");
1185
- if (singleKey !== "body") {
1186
- headers["inline-body-key"] = singleKey;
1187
- }
1188
- if (headerTypes.length > 0) {
1189
- headers["ao-types"] = headerTypes.sort().join(", ");
1278
+ return _context8.abrupt("return", singleBodyKeyResult);
1279
+ case 41:
1280
+ // Step 11: Sort body keys
1281
+ sortedBodyKeys = sortBodyKeys(bodyKeys); // Step 12: Check for special data/body case
1282
+ hasSpecialDataBody = checkSpecialDataBodyCase(obj, sortedBodyKeys); // Only add body-keys header if there are actual body keys
1283
+ if (sortedBodyKeys.length > 0) {
1284
+ headers["body-keys"] = sortedBodyKeys.map(function (k) {
1285
+ return "\"".concat(k, "\"");
1286
+ }).join(", ");
1190
1287
  }
1191
- return _context6.abrupt("return", {
1192
- headers: headers,
1193
- body: value
1194
- });
1195
- case 116:
1196
- // Sort body keys: main array comes first, then element parts by index
1197
- sortedBodyKeys = bodyKeys.sort(function (a, b) {
1198
- var aIsArrayElement = /\/\d+$/.test(a);
1199
- var bIsArrayElement = /\/\d+$/.test(b);
1200
- var aBase = a.split("/")[0];
1201
- var bBase = b.split("/")[0];
1202
-
1203
- // If both are for the same array
1204
- if (aBase === bBase) {
1205
- // Main array comes before element parts
1206
- if (!aIsArrayElement && bIsArrayElement) {
1207
- return -1; // main array comes first
1208
- }
1209
- if (aIsArrayElement && !bIsArrayElement) {
1210
- return 1; // element parts come after
1211
- }
1212
- // Both are elements - sort by index
1213
- if (aIsArrayElement && bIsArrayElement) {
1214
- var aIndex = parseInt(a.split("/")[1]);
1215
- var bIndex = parseInt(b.split("/")[1]);
1216
- return aIndex - bIndex;
1217
- }
1218
- return a.localeCompare(b);
1219
- }
1220
1288
 
1221
- // Different arrays, sort by base name
1222
- return a.localeCompare(b);
1223
- }); // Check if we have the special case where data contains body with bytes and body contains data with bytes
1224
- hasSpecialDataBody = sortedBodyKeys.includes("data") && sortedBodyKeys.includes("body") && obj.data && obj.data.body && isBytes(obj.data.body) && obj.body && obj.body.data && isBytes(obj.body.data);
1225
- headers["body-keys"] = sortedBodyKeys.map(function (k) {
1226
- return "\"".concat(k, "\"");
1227
- }).join(", ");
1228
- if (!hasSpecialDataBody) {
1229
- if (sortedBodyKeys.includes("body") && sortedBodyKeys.length === 1) {
1289
+ // Special case: single body key named "body" containing an object
1290
+ if (!hasSpecialDataBody && sortedBodyKeys.length === 1 && sortedBodyKeys[0] === "body") {
1291
+ bodyValue = obj.body;
1292
+ if ((0, _encodeUtils.isPojo)(bodyValue)) {
1230
1293
  headers["inline-body-key"] = "body";
1231
1294
  }
1232
1295
  }
1233
1296
  if (headerTypes.length > 0) {
1234
1297
  headers["ao-types"] = headerTypes.sort().join(", ");
1235
1298
  }
1236
- bodyParts = [];
1237
- _iterator5 = _createForOfIteratorHelper(sortedBodyKeys);
1238
- _context6.prev = 123;
1239
- _loop5 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop5() {
1240
- var bodyKey, lines, pathParts, value, parent, _i12, _part, hasOnlyEmptyElements, hasOnlyNonEmptyObjects, hasOnlyEmptyObjects, hasObjects, hasArrays, nonObjectItems, _fieldLines, _partTypes, _isInline, orderedLines, _orderedLines, isLastBodyPart, hasOnlyTypes, indicesWithOwnParts, hasNestedObjectParts, fieldLines, partTypes, hasEmptyStrings, hasEmptyObjects, hasObjectsWithOnlyEmptyValues, isMixedArray, _isInline2, _orderedLines2, _iterator6, _step6, line, _orderedLines3, _iterator7, _step7, _line, parentPath, parentValue, _iterator8, _step8, _part2, _hasEmptyStrings, _hasEmptyObjects, _hasObjects, _isInline3, objectTypes, _fieldLines2, binaryFields, hasOnlyEmptyCollections, hasArraysWithOnlyEmptyElements, arrayTypes, _i13, _Object$entries11, _Object$entries11$_i, _k, _v, _i14, _Object$entries12, _Object$entries12$_i, _k2, _v2, childPath, hasOnlyEmpty, desc, _buffer3, _childPath, _hasObjects2, encodedItems, allTypes, shouldSkipObject, onlyEmptyCollections, _orderedLines4, _iterator9, _step9, _line2, binaryFieldsForInline, parts, _iterator10, _step10, _step10$value, key, _buffer4, fullBody, _isLastBodyPart, _hasOnlyTypes, _orderedLines5, hasBinaryFields, _iterator11, _step11, _line3, _parts, headerText, _i15, _binaryFields$_i, _key, _buffer5, _fullBody, isInline, _buffer6, _headerText, content;
1241
- return _regeneratorRuntime().wrap(function _loop5$(_context5) {
1242
- while (1) switch (_context5.prev = _context5.next) {
1243
- case 0:
1244
- bodyKey = _step5.value;
1245
- console.log("\n[Body part] Processing bodyKey: ".concat(bodyKey));
1246
- lines = [];
1247
- pathParts = bodyKey.split("/");
1248
- value = obj;
1249
- parent = null;
1250
- for (_i12 = 0; _i12 < pathParts.length; _i12++) {
1251
- parent = value;
1252
- _part = pathParts[_i12];
1253
- if (/^\d+$/.test(_part)) {
1254
- value = value[parseInt(_part) - 1];
1255
- } else {
1256
- value = value[_part];
1257
- }
1258
- }
1259
- console.log("[Body part] Value at ".concat(bodyKey, ":"), JSON.stringify(value));
1260
-
1261
- // Special handling for empty strings in arrays
1262
- if (!(typeof value === "string" && value === "" && pathParts.length > 1)) {
1263
- _context5.next = 15;
1264
- break;
1265
- }
1266
- console.log("[Body part] Creating part for empty string at ".concat(bodyKey));
1267
- lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
1268
- lines.push("");
1269
- lines.push("");
1270
- bodyParts.push(new Blob([lines.join("\r\n")]));
1271
- return _context5.abrupt("return", 0);
1272
- case 15:
1273
- if (!Array.isArray(value)) {
1274
- _context5.next = 45;
1275
- break;
1276
- }
1277
- hasOnlyEmptyElements = value.length > 0 && value.every(function (item) {
1278
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
1279
- });
1280
- hasOnlyNonEmptyObjects = value.length > 0 && value.every(function (item) {
1281
- return isPojo(item) && Object.keys(item).length > 0;
1282
- });
1283
- hasOnlyEmptyObjects = value.length > 0 && value.every(function (item) {
1284
- return isPojo(item) && Object.keys(item).length === 0;
1285
- });
1286
- hasObjects = value.some(function (item) {
1287
- return isPojo(item);
1288
- });
1289
- hasArrays = value.some(function (item) {
1290
- return Array.isArray(item);
1291
- });
1292
- nonObjectItems = value.map(function (item, index) {
1293
- return {
1294
- item: item,
1295
- index: index + 1
1296
- };
1297
- }).filter(function (_ref7) {
1298
- var item = _ref7.item;
1299
- return !isPojo(item);
1300
- });
1301
- if (!hasOnlyNonEmptyObjects) {
1302
- _context5.next = 24;
1303
- break;
1304
- }
1305
- return _context5.abrupt("return", 0);
1306
- case 24:
1307
- if (!hasOnlyEmptyElements) {
1308
- _context5.next = 31;
1309
- break;
1310
- }
1311
- _fieldLines = [];
1312
- _partTypes = []; // Process items for type information
1313
- value.forEach(function (item, idx) {
1314
- var index = idx + 1;
1315
- if (Array.isArray(item) && item.length === 0) {
1316
- _partTypes.push("".concat(index, "=\"empty-list\""));
1317
- } else if (isPojo(item) && Object.keys(item).length === 0) {
1318
- _partTypes.push("".concat(index, "=\"empty-message\""));
1319
- } else if (typeof item === "string" && item === "") {
1320
- _partTypes.push("".concat(index, "=\"empty-binary\""));
1321
- }
1322
- });
1323
- _isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
1324
- if (_isInline) {
1325
- orderedLines = [];
1326
- if (_partTypes.length > 0) {
1327
- orderedLines.push("ao-types: ".concat(_partTypes.sort(function (a, b) {
1328
- var aNum = parseInt(a.split("=")[0]);
1329
- var bNum = parseInt(b.split("=")[0]);
1330
- return aNum - bNum;
1331
- }).join(", ")));
1332
- }
1333
- orderedLines.push("content-disposition: inline");
1334
- orderedLines.push("");
1335
- bodyParts.push(new Blob([orderedLines.join("\r\n")]));
1336
- } else {
1337
- _orderedLines = [];
1338
- if (_partTypes.length > 0) {
1339
- _orderedLines.push("ao-types: ".concat(_partTypes.sort(function (a, b) {
1340
- var aNum = parseInt(a.split("=")[0]);
1341
- var bNum = parseInt(b.split("=")[0]);
1342
- return aNum - bNum;
1343
- }).join(", ")));
1344
- }
1345
- _orderedLines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
1346
-
1347
- // Check if this is the last body part
1348
- isLastBodyPart = sortedBodyKeys.indexOf(bodyKey) === sortedBodyKeys.length - 1;
1349
- hasOnlyTypes = _partTypes.length > 0 && _fieldLines.length === 0;
1350
- if (isLastBodyPart && hasOnlyTypes) {
1351
- // Don't add empty line for last part with only types
1352
- bodyParts.push(new Blob([_orderedLines.join("\r\n")]));
1353
- } else {
1354
- _orderedLines.push("");
1355
- bodyParts.push(new Blob([_orderedLines.join("\r\n")]));
1356
- }
1357
- }
1358
- return _context5.abrupt("return", 0);
1359
- case 31:
1360
- // Build list of which indices have their own parts
1361
- indicesWithOwnParts = new Set();
1362
- sortedBodyKeys.forEach(function (key) {
1363
- if (key.startsWith(bodyKey + "/")) {
1364
- var subPath = key.substring(bodyKey.length + 1);
1365
- var match = subPath.match(/^(\d+)/);
1366
- if (match) {
1367
- indicesWithOwnParts.add(parseInt(match[1]));
1368
- }
1369
- }
1370
- });
1371
-
1372
- // Check if this array contains sub-arrays with objects that have their own parts
1373
- hasNestedObjectParts = sortedBodyKeys.some(function (key) {
1374
- return key.startsWith(bodyKey + "/") && key.split("/").length > pathParts.length + 1;
1375
- });
1376
- fieldLines = [];
1377
- partTypes = []; // For arrays that contain sub-arrays with objects, we need to add type info for the sub-arrays
1378
- if (hasNestedObjectParts) {
1379
- value.forEach(function (item, idx) {
1380
- var index = idx + 1;
1381
- if (Array.isArray(item)) {
1382
- partTypes.push("".concat(index, "=\"list\""));
1383
- }
1384
- });
1385
- }
1386
-
1387
- // Check if this array has mixed content with empty strings/objects
1388
- hasEmptyStrings = value.some(function (item) {
1389
- return typeof item === "string" && item === "";
1390
- });
1391
- hasEmptyObjects = value.some(function (item) {
1392
- return isPojo(item) && Object.keys(item).length === 0;
1393
- }); // Check if we have objects with only empty values (like {empty: ""})
1394
- hasObjectsWithOnlyEmptyValues = value.some(function (item) {
1395
- if (!isPojo(item) || Object.keys(item).length === 0) return false;
1396
- return Object.values(item).every(function (v) {
1397
- return typeof v === "string" && v === "" || Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0;
1398
- });
1399
- });
1400
- isMixedArray = hasObjects && (hasEmptyStrings || hasEmptyObjects) && !hasObjectsWithOnlyEmptyValues; // Process ALL items for type information
1401
- value.forEach(function (item, idx) {
1402
- var index = idx + 1;
1403
-
1404
- // Skip type info for elements that have their own parts
1405
- if (indicesWithOwnParts.has(index)) {
1406
- return;
1407
- }
1408
-
1409
- // If we have nested object parts and this is an array with objects, skip processing it inline
1410
- if (hasNestedObjectParts && Array.isArray(item) && item.some(function (subItem) {
1411
- return isPojo(subItem);
1412
- })) {
1413
- // Type info already added above
1414
- return;
1415
- }
1416
-
1417
- // For all arrays (not just mixed ones), we need to process all items
1418
- if (typeof item === "string" && item === "") {
1419
- // Empty strings get type annotation but no field line
1420
- partTypes.push("".concat(index, "=\"empty-binary\""));
1421
- } else if (isPojo(item) && Object.keys(item).length === 0) {
1422
- // Empty objects don't get field lines but do get type annotations
1423
- partTypes.push("".concat(index, "=\"empty-message\""));
1424
- } else if (isPojo(item)) {
1425
- // Non-empty objects might have parts
1426
- } else if (Array.isArray(item)) {
1427
- if (item.length === 0) {
1428
- // Empty arrays don't get field lines but do get type annotations
1429
- partTypes.push("".concat(index, "=\"empty-list\""));
1430
- } else {
1431
- partTypes.push("".concat(index, "=\"list\""));
1432
- // Encode array
1433
- var encodedItems = item.map(function (subItem) {
1434
- if (typeof subItem === "number") {
1435
- if (Number.isInteger(subItem)) {
1436
- return "\"(ao-type-integer) ".concat(subItem, "\"");
1437
- } else {
1438
- return "\"(ao-type-float) ".concat(formatFloat(subItem), "\"");
1439
- }
1440
- } else if (typeof subItem === "string") {
1441
- return "\"".concat(subItem, "\"");
1442
- } else if (subItem === null) {
1443
- return "\"(ao-type-atom) \\\"null\\\"\"";
1444
- } else if (subItem === undefined) {
1445
- return "\"(ao-type-atom) \\\"undefined\\\"\"";
1446
- } else if (_typeof(subItem) === "symbol") {
1447
- var desc = subItem.description || "Symbol.for()";
1448
- return "\"(ao-type-atom) \\\"".concat(desc, "\\\"\"");
1449
- } else if (typeof subItem === "boolean") {
1450
- return "\"(ao-type-atom) \\\"".concat(subItem, "\\\"\"");
1451
- } else if (Array.isArray(subItem)) {
1452
- // Use the full encodeArrayItem for nested arrays
1453
- return encodeArrayItem(subItem);
1454
- } else if (isBytes(subItem)) {
1455
- var _buffer = toBuffer(subItem);
1456
- if (_buffer.length === 0 || _buffer.byteLength === 0) {
1457
- return "\"\"";
1458
- }
1459
- return "\"(ao-type-binary)\"";
1460
- } else if (isPojo(subItem)) {
1461
- var json = JSON.stringify(subItem);
1462
- var escaped = json.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1463
- return "\"(ao-type-map) ".concat(escaped, "\"");
1464
- } else {
1465
- return "\"".concat(String(subItem), "\"");
1466
- }
1467
- }).join(", ");
1468
- fieldLines.push("".concat(index, ": ").concat(encodedItems));
1469
- }
1470
- } else if (typeof item === "number") {
1471
- if (Number.isInteger(item)) {
1472
- partTypes.push("".concat(index, "=\"integer\""));
1473
- fieldLines.push("".concat(index, ": ").concat(item));
1474
- } else {
1475
- partTypes.push("".concat(index, "=\"float\""));
1476
- fieldLines.push("".concat(index, ": ").concat(formatFloat(item)));
1477
- }
1478
- } else if (typeof item === "string") {
1479
- // Non-empty strings just get field lines, no type annotation
1480
- fieldLines.push("".concat(index, ": ").concat(item));
1481
- } else if (item === null || item === undefined || _typeof(item) === "symbol" || typeof item === "boolean") {
1482
- partTypes.push("".concat(index, "=\"atom\""));
1483
- if (item === null) {
1484
- fieldLines.push("".concat(index, ": null"));
1485
- } else if (item === undefined) {
1486
- fieldLines.push("".concat(index, ": undefined"));
1487
- } else if (_typeof(item) === "symbol") {
1488
- var desc = item.description || "Symbol.for()";
1489
- fieldLines.push("".concat(index, ": ").concat(desc));
1490
- } else {
1491
- fieldLines.push("".concat(index, ": ").concat(item));
1492
- }
1493
- } else if (isBytes(item)) {
1494
- var _buffer2 = toBuffer(item);
1495
- if (_buffer2.length === 0) {
1496
- partTypes.push("".concat(index, "=\"empty-binary\""));
1497
- } else {
1498
- partTypes.push("".concat(index, "=\"binary\""));
1499
- }
1500
- }
1501
- });
1502
- _isInline2 = bodyKey === "body" && headers["inline-body-key"] === "body";
1503
- if (_isInline2) {
1504
- _orderedLines2 = [];
1505
- if (partTypes.length > 0) {
1506
- _orderedLines2.push("ao-types: ".concat(partTypes.sort(function (a, b) {
1507
- var aNum = parseInt(a.split("=")[0]);
1508
- var bNum = parseInt(b.split("=")[0]);
1509
- return aNum - bNum;
1510
- }).join(", ")));
1511
- }
1512
- _orderedLines2.push("content-disposition: inline");
1513
- if (fieldLines.length > 0) {
1514
- _orderedLines2.push("");
1515
- _iterator6 = _createForOfIteratorHelper(fieldLines);
1516
- try {
1517
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1518
- line = _step6.value;
1519
- _orderedLines2.push(line);
1520
- }
1521
- } catch (err) {
1522
- _iterator6.e(err);
1523
- } finally {
1524
- _iterator6.f();
1525
- }
1526
- }
1527
- bodyParts.push(new Blob([_orderedLines2.join("\r\n") + "\r\n"]));
1528
- } else {
1529
- // Put ao-types first, then content-disposition, then field lines
1530
- _orderedLines3 = [];
1531
- if (partTypes.length > 0) {
1532
- _orderedLines3.push("ao-types: ".concat(partTypes.sort(function (a, b) {
1533
- var aNum = parseInt(a.split("=")[0]);
1534
- var bNum = parseInt(b.split("=")[0]);
1535
- return aNum - bNum;
1536
- }).join(", ")));
1537
- }
1538
- _orderedLines3.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
1539
-
1540
- // Add field lines directly without blank line
1541
- _iterator7 = _createForOfIteratorHelper(fieldLines);
1542
- try {
1543
- for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
1544
- _line = _step7.value;
1545
- _orderedLines3.push(_line);
1546
- }
1547
1299
 
1548
- // Add trailing blank line if we have field lines
1549
- } catch (err) {
1550
- _iterator7.e(err);
1551
- } finally {
1552
- _iterator7.f();
1553
- }
1554
- if (fieldLines.length > 0) {
1555
- bodyParts.push(new Blob([_orderedLines3.join("\r\n") + "\r\n"]));
1556
- } else {
1557
- bodyParts.push(new Blob([_orderedLines3.join("\r\n")]));
1558
- }
1559
- }
1560
- return _context5.abrupt("return", 0);
1561
- case 45:
1562
- if (!isPojo(value)) {
1563
- _context5.next = 126;
1564
- break;
1565
- }
1566
- if (!(Object.keys(value).length === 0)) {
1567
- _context5.next = 60;
1568
- break;
1569
- }
1570
- // Check if this is a parent array context where empty objects should get parts
1571
- parentPath = pathParts.slice(0, -1).join("/");
1572
- parentValue = obj;
1573
- _iterator8 = _createForOfIteratorHelper(pathParts.slice(0, -1));
1574
- try {
1575
- for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1576
- _part2 = _step8.value;
1577
- if (/^\d+$/.test(_part2)) {
1578
- parentValue = parentValue[parseInt(_part2) - 1];
1579
- } else {
1580
- parentValue = parentValue[_part2];
1581
- }
1582
- }
1583
- } catch (err) {
1584
- _iterator8.e(err);
1585
- } finally {
1586
- _iterator8.f();
1587
- }
1588
- if (!Array.isArray(parentValue)) {
1589
- _context5.next = 58;
1590
- break;
1591
- }
1592
- // Check if parent array has mixed content
1593
- _hasEmptyStrings = parentValue.some(function (item) {
1594
- return typeof item === "string" && item === "";
1595
- });
1596
- _hasEmptyObjects = parentValue.some(function (item) {
1597
- return isPojo(item) && Object.keys(item).length === 0;
1598
- });
1599
- _hasObjects = parentValue.some(function (item) {
1600
- return isPojo(item);
1601
- });
1602
- if (!(_hasObjects && (_hasEmptyStrings || _hasEmptyObjects))) {
1603
- _context5.next = 58;
1604
- break;
1605
- }
1606
- // Special mixed array case - empty objects don't get parts
1607
- console.log("[Body part] Skipping empty object in mixed array at ".concat(bodyKey));
1608
- return _context5.abrupt("return", 0);
1609
- case 58:
1610
- // Normal case - empty objects might get parts
1611
- console.log("[Body part] Empty object at ".concat(bodyKey));
1612
- // For now, skip empty objects
1613
- return _context5.abrupt("return", 0);
1614
- case 60:
1615
- if (!(hasSpecialDataBody && bodyKey === "data" && Object.keys(value).length === 1 && value.body && isBytes(value.body))) {
1616
- _context5.next = 62;
1617
- break;
1618
- }
1619
- return _context5.abrupt("return", 0);
1620
- case 62:
1621
- // Handle non-empty objects
1622
- _isInline3 = bodyKey === "body" && headers["inline-body-key"] === "body";
1623
- if (_isInline3) {
1624
- lines.push("content-disposition: inline");
1625
- } else {
1626
- lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
1627
- }
1628
-
1629
- // Continue with object processing...
1630
- objectTypes = [];
1631
- _fieldLines2 = [];
1632
- binaryFields = []; // First check if this object only contains empty collections
1633
- hasOnlyEmptyCollections = Object.entries(value).every(function (_ref8) {
1634
- var _ref9 = _slicedToArray(_ref8, 2),
1635
- k = _ref9[0],
1636
- v = _ref9[1];
1637
- return Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0 || isBytes(v) && (v.length === 0 || v.byteLength === 0) || typeof v === "string" && v.length === 0;
1638
- }); // Also check if it contains arrays with only empty elements
1639
- hasArraysWithOnlyEmptyElements = Object.entries(value).some(function (_ref10) {
1640
- var _ref11 = _slicedToArray(_ref10, 2),
1641
- k = _ref11[0],
1642
- v = _ref11[1];
1643
- return Array.isArray(v) && v.length > 0 && v.every(function (item) {
1644
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
1645
- });
1646
- }); // Collect type information for arrays in the object BEFORE processing fields
1647
- arrayTypes = [];
1648
- for (_i13 = 0, _Object$entries11 = Object.entries(value); _i13 < _Object$entries11.length; _i13++) {
1649
- _Object$entries11$_i = _slicedToArray(_Object$entries11[_i13], 2), _k = _Object$entries11$_i[0], _v = _Object$entries11$_i[1];
1650
- if (Array.isArray(_v)) {
1651
- arrayTypes.push("".concat(_k.toLowerCase(), "=\"").concat(_v.length === 0 ? "empty-list" : "list", "\""));
1652
- }
1653
- }
1654
- _i14 = 0, _Object$entries12 = Object.entries(value);
1655
- case 72:
1656
- if (!(_i14 < _Object$entries12.length)) {
1657
- _context5.next = 119;
1658
- break;
1659
- }
1660
- _Object$entries12$_i = _slicedToArray(_Object$entries12[_i14], 2), _k2 = _Object$entries12$_i[0], _v2 = _Object$entries12$_i[1];
1661
- childPath = "".concat(bodyKey, "/").concat(_k2);
1662
- if (!sortedBodyKeys.includes(childPath)) {
1663
- _context5.next = 77;
1664
- break;
1665
- }
1666
- return _context5.abrupt("continue", 116);
1667
- case 77:
1668
- if (!(Array.isArray(_v2) && _v2.some(function (item) {
1669
- return isPojo(item);
1670
- }))) {
1671
- _context5.next = 83;
1672
- break;
1673
- }
1674
- if (!sortedBodyKeys.includes(childPath)) {
1675
- _context5.next = 80;
1676
- break;
1677
- }
1678
- return _context5.abrupt("continue", 116);
1679
- case 80:
1680
- // Check if array has only empty elements
1681
- hasOnlyEmpty = _v2.every(function (item) {
1682
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
1683
- });
1684
- if (!hasOnlyEmpty) {
1685
- _context5.next = 83;
1686
- break;
1687
- }
1688
- return _context5.abrupt("continue", 116);
1689
- case 83:
1690
- if (Array.isArray(_v2)) {
1691
- // Type info already added above in arrayTypes
1692
- } else if (_v2 === null || _v2 === undefined || _typeof(_v2) === "symbol" || typeof _v2 === "boolean") {
1693
- objectTypes.push("".concat(_k2.toLowerCase(), "=\"atom\""));
1694
- } else if (typeof _v2 === "number") {
1695
- objectTypes.push("".concat(_k2.toLowerCase(), "=\"").concat(Number.isInteger(_v2) ? "integer" : "float", "\""));
1696
- } else if (typeof _v2 === "string" && _v2.length === 0) {
1697
- objectTypes.push("".concat(_k2.toLowerCase(), "=\"empty-binary\""));
1698
- } else if (isBytes(_v2) && (_v2.length === 0 || _v2.byteLength === 0)) {
1699
- objectTypes.push("".concat(_k2.toLowerCase(), "=\"empty-binary\""));
1700
- } else if (isPojo(_v2) && Object.keys(_v2).length === 0) {
1701
- objectTypes.push("".concat(_k2.toLowerCase(), "=\"empty-message\""));
1702
- }
1703
- if (!(typeof _v2 === "string")) {
1704
- _context5.next = 88;
1705
- break;
1706
- }
1707
- if (_v2.length === 0) {
1708
- // Empty strings are shown as "empty: " (with trailing space)
1709
- _fieldLines2.push("".concat(_k2, ": "));
1710
- } else {
1711
- _fieldLines2.push("".concat(_k2, ": ").concat(_v2));
1712
- }
1713
- _context5.next = 116;
1714
- break;
1715
- case 88:
1716
- if (!(typeof _v2 === "number")) {
1717
- _context5.next = 92;
1718
- break;
1719
- }
1720
- _fieldLines2.push("".concat(_k2, ": ").concat(_v2));
1721
- _context5.next = 116;
1722
- break;
1723
- case 92:
1724
- if (!(typeof _v2 === "boolean")) {
1725
- _context5.next = 96;
1726
- break;
1727
- }
1728
- _fieldLines2.push("".concat(_k2, ": \"").concat(_v2, "\""));
1729
- _context5.next = 116;
1730
- break;
1731
- case 96:
1732
- if (!(_v2 === null)) {
1733
- _context5.next = 100;
1734
- break;
1735
- }
1736
- _fieldLines2.push("".concat(_k2, ": \"null\""));
1737
- _context5.next = 116;
1738
- break;
1739
- case 100:
1740
- if (!(_v2 === undefined)) {
1741
- _context5.next = 104;
1742
- break;
1743
- }
1744
- _fieldLines2.push("".concat(_k2, ": \"undefined\""));
1745
- _context5.next = 116;
1746
- break;
1747
- case 104:
1748
- if (!(_typeof(_v2) === "symbol")) {
1749
- _context5.next = 109;
1750
- break;
1751
- }
1752
- desc = _v2.description || "Symbol.for()";
1753
- _fieldLines2.push("".concat(_k2, ": \"").concat(desc, "\""));
1754
- _context5.next = 116;
1755
- break;
1756
- case 109:
1757
- if (!isBytes(_v2)) {
1758
- _context5.next = 115;
1759
- break;
1760
- }
1761
- _buffer3 = toBuffer(_v2);
1762
- binaryFields.push({
1763
- key: _k2,
1764
- buffer: _buffer3
1765
- });
1766
- return _context5.abrupt("continue", 116);
1767
- case 115:
1768
- if (Array.isArray(_v2)) {
1769
- if (_v2.length === 0) {
1770
- // Don't add field line for empty array
1771
- } else {
1772
- // Check if this array will have its own body part
1773
- _childPath = "".concat(bodyKey, "/").concat(_k2);
1774
- if (!sortedBodyKeys.includes(_childPath)) {
1775
- // Check if this array contains objects - if so, don't add field line
1776
- _hasObjects2 = _v2.some(function (item) {
1777
- return isPojo(item);
1778
- });
1779
- if (!_hasObjects2) {
1780
- encodedItems = _v2.map(function (item) {
1781
- return encodeArrayItem(item);
1782
- }).join(", ");
1783
- _fieldLines2.push("".concat(_k2, ": ").concat(encodedItems));
1784
- }
1785
- }
1786
- }
1787
- } else if (isPojo(_v2) && Object.keys(_v2).length === 0) {
1788
- // Empty object - don't add field line
1789
- }
1790
- case 116:
1791
- _i14++;
1792
- _context5.next = 72;
1793
- break;
1794
- case 119:
1795
- // Combine arrayTypes with objectTypes
1796
- allTypes = [].concat(arrayTypes, objectTypes); // Check if this object should be skipped entirely
1797
- shouldSkipObject = Object.entries(value).every(function (_ref12) {
1798
- var _ref13 = _slicedToArray(_ref12, 2),
1799
- k = _ref13[0],
1800
- v = _ref13[1];
1801
- var childPath = "".concat(bodyKey, "/").concat(k);
1802
- if (sortedBodyKeys.includes(childPath)) return true;
1803
- if (Array.isArray(v) && v.some(function (item) {
1804
- return isPojo(item);
1805
- })) {
1806
- // Check if array has only empty elements
1807
- var _hasOnlyEmpty = v.every(function (item) {
1808
- return Array.isArray(item) && item.length === 0 || isPojo(item) && Object.keys(item).length === 0 || typeof item === "string" && item === "";
1809
- });
1810
- return _hasOnlyEmpty || sortedBodyKeys.includes(childPath);
1811
- }
1812
- return false;
1813
- });
1814
- if (!(shouldSkipObject && !hasOnlyEmptyCollections && !hasArraysWithOnlyEmptyElements)) {
1815
- _context5.next = 123;
1816
- break;
1817
- }
1818
- return _context5.abrupt("return", 0);
1819
- case 123:
1820
- onlyEmptyCollections = Object.entries(value).every(function (_ref14) {
1821
- var _ref15 = _slicedToArray(_ref14, 2),
1822
- k = _ref15[0],
1823
- v = _ref15[1];
1824
- var childPath = "".concat(bodyKey, "/").concat(k);
1825
- if (sortedBodyKeys.includes(childPath)) return true;
1826
- if (Array.isArray(v) && v.some(function (item) {
1827
- return isPojo(item);
1828
- })) return true;
1829
- return Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0 || isBytes(v) && (v.length === 0 || v.byteLength === 0);
1830
- });
1831
- if (_isInline3) {
1832
- _orderedLines4 = []; // FIXED: For inline body, put field lines FIRST
1833
- _iterator9 = _createForOfIteratorHelper(_fieldLines2);
1834
- try {
1835
- for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1836
- _line2 = _step9.value;
1837
- _orderedLines4.push(_line2);
1838
- }
1839
- } catch (err) {
1840
- _iterator9.e(err);
1841
- } finally {
1842
- _iterator9.f();
1843
- }
1844
- if (allTypes.length > 0) {
1845
- _orderedLines4.push("ao-types: ".concat(allTypes.sort().join(", ")));
1846
- }
1847
- _orderedLines4.push("content-disposition: inline");
1848
- binaryFieldsForInline = Object.entries(value).filter(function (_ref16) {
1849
- var _ref17 = _slicedToArray(_ref16, 2),
1850
- k = _ref17[0],
1851
- v = _ref17[1];
1852
- return isBytes(v) && !sortedBodyKeys.includes("".concat(bodyKey, "/").concat(k));
1853
- }).map(function (_ref18) {
1854
- var _ref19 = _slicedToArray(_ref18, 2),
1855
- k = _ref19[0],
1856
- v = _ref19[1];
1857
- return {
1858
- key: k,
1859
- buffer: toBuffer(v)
1860
- };
1861
- });
1862
- if (binaryFieldsForInline.length > 0) {
1863
- parts = [];
1864
- parts.push(Buffer.from(_orderedLines4.join("\r\n")));
1865
- _iterator10 = _createForOfIteratorHelper(binaryFieldsForInline);
1866
- try {
1867
- for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
1868
- _step10$value = _step10.value, key = _step10$value.key, _buffer4 = _step10$value.buffer;
1869
- parts.push(Buffer.from("\r\n".concat(key, ": ")));
1870
- parts.push(_buffer4);
1871
- }
1872
- } catch (err) {
1873
- _iterator10.e(err);
1874
- } finally {
1875
- _iterator10.f();
1876
- }
1877
- parts.push(Buffer.from("\r\n"));
1878
- fullBody = Buffer.concat(parts);
1879
- bodyParts.push(new Blob([fullBody]));
1880
- } else {
1881
- // Check if this is the last body part for special handling
1882
- _isLastBodyPart = sortedBodyKeys.indexOf(bodyKey) === sortedBodyKeys.length - 1;
1883
- _hasOnlyTypes = allTypes.length > 0 && _fieldLines2.length === 0;
1884
- if (_isLastBodyPart && _hasOnlyTypes) {
1885
- // Don't add empty line for last part with only types
1886
- bodyParts.push(new Blob([_orderedLines4.join("\r\n")]));
1887
- } else if (_fieldLines2.length === 0) {
1888
- bodyParts.push(new Blob([_orderedLines4.join("\r\n")]));
1889
- } else {
1890
- bodyParts.push(new Blob([_orderedLines4.join("\r\n") + "\r\n"]));
1891
- }
1892
- }
1893
- } else {
1894
- // Put ao-types first, then content-disposition, then field lines
1895
- _orderedLines5 = [];
1896
- if (allTypes.length > 0) {
1897
- _orderedLines5.push("ao-types: ".concat(allTypes.sort().join(", ")));
1898
- }
1899
- _orderedLines5.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
1900
-
1901
- // Check if we have any binary fields
1902
- hasBinaryFields = binaryFields && binaryFields.length > 0; // Add blank line before field lines if we have binary fields or no field lines
1903
- if (hasBinaryFields || _fieldLines2.length === 0) {
1904
- _orderedLines5.push("");
1905
- }
1906
-
1907
- // Add field lines
1908
- _iterator11 = _createForOfIteratorHelper(_fieldLines2);
1909
- try {
1910
- for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
1911
- _line3 = _step11.value;
1912
- _orderedLines5.push(_line3);
1913
- }
1914
- } catch (err) {
1915
- _iterator11.e(err);
1916
- } finally {
1917
- _iterator11.f();
1918
- }
1919
- if (binaryFields && binaryFields.length > 0) {
1920
- _parts = [];
1921
- headerText = _orderedLines5.join("\r\n");
1922
- _parts.push(Buffer.from(headerText));
1923
- for (_i15 = 0; _i15 < binaryFields.length; _i15++) {
1924
- _binaryFields$_i = binaryFields[_i15], _key = _binaryFields$_i.key, _buffer5 = _binaryFields$_i.buffer;
1925
- if (_i15 > 0) {
1926
- _parts.push(Buffer.from("\r\n"));
1927
- }
1928
- _parts.push(Buffer.from("".concat(_key, ": ")));
1929
- _parts.push(_buffer5);
1930
- }
1931
- _parts.push(Buffer.from("\r\n"));
1932
- _fullBody = Buffer.concat(_parts);
1933
- bodyParts.push(new Blob([_fullBody]));
1934
- } else {
1935
- // Add trailing blank line if we have field lines
1936
- if (_fieldLines2.length > 0) {
1937
- bodyParts.push(new Blob([_orderedLines5.join("\r\n") + "\r\n"]));
1938
- } else {
1939
- bodyParts.push(new Blob([_orderedLines5.join("\r\n")]));
1940
- }
1941
- }
1942
- }
1943
- return _context5.abrupt("return", 0);
1944
- case 126:
1945
- isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
1946
- if (isInline) {
1947
- lines.push("content-disposition: inline");
1948
- } else {
1949
- lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
1950
- }
1951
- if (isBytes(value)) {
1952
- _buffer6 = toBuffer(value);
1953
- _headerText = lines.join("\r\n") + "\r\n\r\n";
1954
- bodyParts.push(new Blob([_headerText, _buffer6]));
1955
- } else if (typeof value === "string") {
1956
- lines.push("");
1957
- lines.push(value);
1958
- bodyParts.push(new Blob([lines.join("\r\n")]));
1959
- } else if (typeof value === "boolean" || typeof value === "number" || value === null || value === undefined || _typeof(value) === "symbol") {
1960
- if (typeof value === "boolean") {
1961
- content = "\"".concat(value, "\"");
1962
- } else if (typeof value === "number") {
1963
- content = String(value);
1964
- } else if (value === null) {
1965
- content = '"null"';
1966
- } else if (value === undefined) {
1967
- content = '"undefined"';
1968
- } else if (_typeof(value) === "symbol") {
1969
- content = "\"".concat(value.description || "Symbol.for()", "\"");
1970
- }
1971
- lines.push("");
1972
- lines.push(content);
1973
- bodyParts.push(new Blob([lines.join("\r\n")]));
1974
- }
1975
- case 129:
1976
- case "end":
1977
- return _context5.stop();
1978
- }
1979
- }, _loop5);
1980
- });
1981
- _iterator5.s();
1982
- case 126:
1983
- if ((_step5 = _iterator5.n()).done) {
1984
- _context6.next = 133;
1300
+ // Step 13: Build body parts for each body key
1301
+ bodyParts = buildBodyParts(obj, sortedBodyKeys, headers, hasSpecialDataBody); // If no body parts were created, return headers only
1302
+ if (!(bodyParts.length === 0)) {
1303
+ _context8.next = 49;
1985
1304
  break;
1986
1305
  }
1987
- return _context6.delegateYield(_loop5(), "t2", 128);
1988
- case 128:
1989
- _ret = _context6.t2;
1990
- if (!(_ret === 0)) {
1991
- _context6.next = 131;
1992
- break;
1993
- }
1994
- return _context6.abrupt("continue", 131);
1995
- case 131:
1996
- _context6.next = 126;
1997
- break;
1998
- case 133:
1999
- _context6.next = 138;
2000
- break;
2001
- case 135:
2002
- _context6.prev = 135;
2003
- _context6.t3 = _context6["catch"](123);
2004
- _iterator5.e(_context6.t3);
2005
- case 138:
2006
- _context6.prev = 138;
2007
- _iterator5.f();
2008
- return _context6.finish(138);
2009
- case 141:
2010
- // Add the special data/body part if needed
2011
- if (hasSpecialDataBody && obj.data && obj.data.body && isBytes(obj.data.body)) {
2012
- buffer = toBuffer(obj.data.body);
2013
- specialPart = ["content-disposition: form-data;name=\"data/body\"", "", ""].join("\r\n");
2014
- bodyParts.push(new Blob([specialPart, buffer]));
2015
- }
2016
- _context6.next = 144;
2017
- return Promise.all(bodyParts.map(function (part) {
2018
- return part.text();
2019
- }));
2020
- case 144:
2021
- partsContent = _context6.sent;
2022
- allContent = partsContent.join("");
2023
- _context6.next = 148;
2024
- return sha256(new TextEncoder().encode(allContent));
2025
- case 148:
2026
- boundaryHash = _context6.sent;
2027
- boundary = _base64url["default"].encode(Buffer.from(boundaryHash));
2028
- finalParts = [];
2029
- for (i = 0; i < bodyParts.length; i++) {
2030
- if (i === 0) {
2031
- finalParts.push(new Blob(["--".concat(boundary, "\r\n")]));
2032
- } else {
2033
- finalParts.push(new Blob(["\r\n--".concat(boundary, "\r\n")]));
2034
- }
2035
- finalParts.push(bodyParts[i]);
2036
- }
2037
- finalParts.push(new Blob(["\r\n--".concat(boundary, "--")]));
2038
- headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
2039
- body = new Blob(finalParts);
2040
- _context6.next = 157;
2041
- return body.arrayBuffer();
2042
- case 157:
2043
- finalContent = _context6.sent;
2044
- if (!(finalContent.byteLength > 0)) {
2045
- _context6.next = 164;
2046
- break;
2047
- }
2048
- _context6.next = 161;
2049
- return sha256(finalContent);
2050
- case 161:
2051
- _contentDigest5 = _context6.sent;
2052
- _base5 = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest5));
2053
- headers["content-digest"] = "sha-256=:".concat(_base5, ":");
2054
- case 164:
2055
- headers["content-length"] = String(finalContent.byteLength);
2056
- console.log("=== ENCODE END ===\n");
2057
- return _context6.abrupt("return", {
1306
+ return _context8.abrupt("return", {
1307
+ headers: headers,
1308
+ body: undefined
1309
+ });
1310
+ case 49:
1311
+ _context8.next = 51;
1312
+ return generateBoundary(bodyParts);
1313
+ case 51:
1314
+ boundary = _context8.sent;
1315
+ // Step 15: Assemble final multipart body
1316
+ body = assembleMultipartBody(bodyParts, boundary); // Step 16: Calculate content digest
1317
+ _context8.next = 55;
1318
+ return calculateContentDigest(body);
1319
+ case 55:
1320
+ _yield$calculateConte = _context8.sent;
1321
+ contentDigest = _yield$calculateConte.digest;
1322
+ byteLength = _yield$calculateConte.byteLength;
1323
+ // Step 17: Set final headers (content-type, content-length)
1324
+ setFinalHeaders(headers, boundary, contentDigest, byteLength);
1325
+
1326
+ // Step 18: Return result
1327
+ return _context8.abrupt("return", {
2058
1328
  headers: headers,
2059
1329
  body: body
2060
1330
  });
2061
- case 167:
1331
+ case 60:
2062
1332
  case "end":
2063
- return _context6.stop();
1333
+ return _context8.stop();
2064
1334
  }
2065
- }, _callee3, null, [[123, 135, 138, 141]]);
1335
+ }, _callee8);
2066
1336
  }));
2067
1337
  return _encode.apply(this, arguments);
2068
1338
  }
2069
- function enc(_x3) {
1339
+ function enc(_x11) {
2070
1340
  return _enc.apply(this, arguments);
2071
1341
  }
2072
1342
  function _enc() {
2073
- _enc = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(fields) {
2074
- return _regeneratorRuntime().wrap(function _callee4$(_context7) {
2075
- while (1) switch (_context7.prev = _context7.next) {
1343
+ _enc = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(fields) {
1344
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1345
+ while (1) switch (_context9.prev = _context9.next) {
2076
1346
  case 0:
2077
- _context7.next = 2;
1347
+ _context9.next = 2;
2078
1348
  return encode(fields);
2079
1349
  case 2:
2080
- return _context7.abrupt("return", _context7.sent);
1350
+ return _context9.abrupt("return", _context9.sent);
2081
1351
  case 3:
2082
1352
  case "end":
2083
- return _context7.stop();
1353
+ return _context9.stop();
2084
1354
  }
2085
- }, _callee4);
1355
+ }, _callee9);
2086
1356
  }));
2087
1357
  return _enc.apply(this, arguments);
2088
1358
  }