wao 0.27.0 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/cjs/encode.js +1292 -817
  2. package/esm/encode.js +1008 -510
  3. package/package.json +1 -1
package/cjs/encode.js CHANGED
@@ -7,106 +7,28 @@ exports.enc = enc;
7
7
  var _base64url = _interopRequireDefault(require("base64url"));
8
8
  var _fastSha = require("fast-sha256");
9
9
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
10
- 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; } } }; }
11
10
  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; }
12
- 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); }
13
- 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); }); }; }
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
+ 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
16
  function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
15
17
  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."); }
16
18
  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; } }
17
19
  function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
18
20
  function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
19
21
  function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
22
+ 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
+ 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); }); }; }
20
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); }
21
25
  function isBytes(value) {
22
- return value instanceof ArrayBuffer || ArrayBuffer.isView(value) || Buffer.isBuffer(value);
26
+ return value instanceof ArrayBuffer || ArrayBuffer.isView(value) || Buffer.isBuffer(value) || value && _typeof(value) === "object" && value.type === "Buffer" && Array.isArray(value.data);
23
27
  }
24
28
  function isPojo(value) {
25
29
  return !isBytes(value) && !Array.isArray(value) && !(value instanceof Blob) && _typeof(value) === "object" && value !== null;
26
30
  }
27
- function hbEncodeValue(value) {
28
- if (isBytes(value)) {
29
- var length = value.byteLength || value.length || 0;
30
- if (length === 0) return ["empty-binary", ""];
31
- return [undefined, value];
32
- }
33
- if (typeof value === "string") {
34
- if (value.length === 0) return ["empty-string", ""];
35
- return [undefined, value];
36
- }
37
- if (Array.isArray(value)) {
38
- if (value.length === 0) return ["empty-list", "[]"];
39
- var hasObjects = value.some(function (item) {
40
- return isPojo(item);
41
- });
42
- if (hasObjects) {
43
- return ["list_with_objects", value];
44
- }
45
- var items = value.map(function (item) {
46
- if (typeof item === "string") {
47
- return "\"".concat(item, "\"");
48
- } else if (typeof item === "number") {
49
- if (Number.isInteger(item)) {
50
- return "\"(ao-type-integer) ".concat(item, "\"");
51
- } else {
52
- return "\"(ao-type-float) ".concat(item.toExponential(20).replace("e+0", "e+00"), "\"");
53
- }
54
- } else if (typeof item === "boolean") {
55
- return "\"(ao-type-atom) \\\"".concat(item ? "true" : "false", "\\\"\"");
56
- } else if (_typeof(item) === "symbol") {
57
- var desc = item.description || "symbol";
58
- return "\"(ao-type-atom) \\\"".concat(desc, "\\\"\"");
59
- } else if (item === null) {
60
- return "\"(ao-type-atom) \\\"null\\\"\"";
61
- } else if (item === undefined) {
62
- return "\"(ao-type-atom) \\\"undefined\\\"\"";
63
- } else if (isBytes(item)) {
64
- var _length = item.byteLength || item.length || 0;
65
- if (_length === 0) {
66
- return "\"\"";
67
- } else {
68
- var base64 = _base64url["default"].encode(Buffer.from(item));
69
- return "\"(ao-type-binary) ".concat(base64, "\"");
70
- }
71
- } else if (Array.isArray(item)) {
72
- var _hbEncodeValue = hbEncodeValue(item),
73
- _hbEncodeValue2 = _slicedToArray(_hbEncodeValue, 2),
74
- encoded = _hbEncodeValue2[1];
75
- var escapedEncoded = encoded.replace(/"/g, '\\"');
76
- return "\"(ao-type-list) ".concat(escapedEncoded, "\"");
77
- } else {
78
- return "\"".concat(String(item), "\"");
79
- }
80
- });
81
- return ["list", items.join(", ")];
82
- }
83
- if (typeof value === "number") {
84
- if (!Number.isInteger(value)) return ["float", "".concat(value)];
85
- return ["integer", String(value)];
86
- }
87
- if (typeof value === "boolean") {
88
- return ["atom", value ? "true" : "false"];
89
- }
90
- if (_typeof(value) === "symbol") {
91
- var desc = value.description || "symbol";
92
- return ["atom", desc];
93
- }
94
- if (value === null) return ["atom", "null"];
95
- if (value === undefined) return ["atom", "undefined"];
96
- if (isPojo(value)) {
97
- throw new Error("Objects must be lifted");
98
- }
99
- throw new Error("Cannot encode value: ".concat(String(value)));
100
- }
101
31
  var MAX_HEADER_LENGTH = 4096;
102
- function encode_body_keys(bodyKeys) {
103
- if (!bodyKeys || bodyKeys.length === 0) return "";
104
- var items = bodyKeys.map(function (key) {
105
- var escaped = key.replace(/"/g, '\\"');
106
- return "\"".concat(escaped, "\"");
107
- });
108
- return items.join(", ");
109
- }
110
32
  function hasNewline(_x) {
111
33
  return _hasNewline.apply(this, arguments);
112
34
  }
@@ -191,139 +113,237 @@ function _sha() {
191
113
  }));
192
114
  return _sha.apply(this, arguments);
193
115
  }
194
- function collectParts(obj) {
195
- var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
196
- var parts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
197
- var types = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
198
- var _loop = function _loop() {
199
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
200
- key = _Object$entries$_i[0],
201
- value = _Object$entries$_i[1];
202
- var currentPath = path ? "".concat(path, "/").concat(key) : key;
203
- if (value === null || value === undefined) {
204
- if (!parts[path]) parts[path] = {};
205
- parts[path][key] = value === null ? '"null"' : '"undefined"';
206
- types[currentPath] = "atom";
207
- } else if (isBytes(value)) {
208
- if (!parts[path]) parts[path] = {};
209
- parts[path][key] = value;
210
- var length = value.byteLength || value.length || 0;
211
- if (length === 0) {
212
- types[currentPath] = "empty-binary";
213
- }
214
- } else if (typeof value === "string") {
215
- if (value.length === 0) {
216
- types[currentPath] = "empty-binary";
217
- if (!parts[path]) parts[path] = {};
218
- parts[path][key] = "";
116
+ function formatFloat(num) {
117
+ // Format float in scientific notation with proper padding
118
+ var exp = num.toExponential(20);
119
+ // Replace "1.23e+0" with "1.23e+00"
120
+ exp = exp.replace(/e\+(\d)$/, "e+0$1");
121
+ exp = exp.replace(/e-(\d)$/, "e-0$1");
122
+ return exp;
123
+ }
124
+ function encodeArrayItem(item) {
125
+ if (typeof item === "number") {
126
+ if (Number.isInteger(item)) {
127
+ return "\"(ao-type-integer) ".concat(item, "\"");
128
+ } else {
129
+ return "\"(ao-type-float) ".concat(formatFloat(item), "\"");
130
+ }
131
+ } else if (typeof item === "string") {
132
+ return "\"".concat(item, "\"");
133
+ } else if (item === null) {
134
+ return "\"(ao-type-atom) \\\"null\\\"\"";
135
+ } else if (item === undefined) {
136
+ return "\"(ao-type-atom) \\\"undefined\\\"\"";
137
+ } else if (_typeof(item) === "symbol") {
138
+ var desc = item.description || "Symbol.for()";
139
+ return "\"(ao-type-atom) \\\"".concat(desc, "\\\"\"");
140
+ } else if (typeof item === "boolean") {
141
+ return "\"(ao-type-atom) \\\"".concat(item, "\\\"\"");
142
+ } else if (Array.isArray(item)) {
143
+ // Nested array
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), "\\\"");
150
+ }
151
+ } else if (typeof nestedItem === "string") {
152
+ return "\\\"".concat(nestedItem, "\\\"");
153
+ } else if (nestedItem === null) {
154
+ return "\\\"(ao-type-atom) \\\\\\\"null\\\\\\\"\\\"";
155
+ } else if (_typeof(nestedItem) === "symbol") {
156
+ var _desc = nestedItem.description || "Symbol.for()";
157
+ return "\\\"(ao-type-atom) \\\\\\\"".concat(_desc, "\\\\\\\"\\\"");
219
158
  } else {
220
- if (!parts[path]) parts[path] = {};
221
- parts[path][key] = value;
159
+ return "\\\"".concat(String(nestedItem), "\\\"");
222
160
  }
223
- } else if (Array.isArray(value)) {
224
- if (value.length === 0) {
225
- types[currentPath] = "empty-list";
226
- if (!parts[path]) parts[path] = {};
227
- parts[path][key] = "[]";
228
- } else {
161
+ }).join(", ");
162
+ return "\"(ao-type-list) ".concat(nestedItems, "\"");
163
+ } else if (isBytes(item)) {
164
+ // For empty binaries in arrays, return empty string
165
+ var buffer = toBuffer(item);
166
+ if (buffer.length === 0 || buffer.byteLength === 0) {
167
+ return "\"\"";
168
+ }
169
+ // For non-empty binaries, we can't include them in headers
170
+ return "\"(ao-type-binary)\"";
171
+ } else if (isPojo(item)) {
172
+ var json = JSON.stringify(item);
173
+ var escaped = json.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
174
+ return "\"(ao-type-map) ".concat(escaped, "\"");
175
+ } else {
176
+ return "\"".concat(String(item), "\"");
177
+ }
178
+ }
179
+ function needsOwnBodyPart(value) {
180
+ if (Array.isArray(value)) return true;
181
+ if (isBytes(value)) return true;
182
+ if (isPojo(value)) {
183
+ // Check if object has complex fields
184
+ return Object.values(value).some(function (v) {
185
+ return Array.isArray(v) || isPojo(v) || isBytes(v) || v === null || v === undefined || _typeof(v) === "symbol";
186
+ });
187
+ }
188
+ return false;
189
+ }
190
+ function collectBodyKeys(obj) {
191
+ var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
192
+ var keys = [];
193
+ function traverse(current, path) {
194
+ // Track if current level has simple fields or empty objects
195
+ var hasSimpleFields = false;
196
+ // Track nested paths that need body parts
197
+ var nestedPaths = [];
198
+ var _loop = function _loop() {
199
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
200
+ key = _Object$entries$_i[0],
201
+ value = _Object$entries$_i[1];
202
+ var fullPath = path ? "".concat(path, "/").concat(key) : key;
203
+ if (Array.isArray(value)) {
229
204
  var hasObjects = value.some(function (item) {
230
205
  return isPojo(item);
231
206
  });
207
+ var hasNonObjects = value.some(function (item) {
208
+ return !isPojo(item);
209
+ });
232
210
  if (hasObjects) {
233
- // Arrays with objects: create separate parts for each indexed item
234
- types[currentPath] = "list";
211
+ // Each object in array gets its own key
235
212
  value.forEach(function (item, index) {
236
- var indexKey = String(index + 1);
237
- var indexPath = "".concat(currentPath, "/").concat(indexKey);
238
213
  if (isPojo(item)) {
239
- // Each object in the array becomes a separate part
240
- if (!parts[indexPath]) parts[indexPath] = {};
241
- for (var _i2 = 0, _Object$entries2 = Object.entries(item); _i2 < _Object$entries2.length; _i2++) {
242
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
243
- objKey = _Object$entries2$_i[0],
244
- objValue = _Object$entries2$_i[1];
245
- parts[indexPath][objKey] = objValue;
246
-
247
- // Set types for object fields
248
- var fieldPath = "".concat(indexPath, "/").concat(objKey);
249
- if (typeof objValue === "number") {
250
- types[fieldPath] = Number.isInteger(objValue) ? "integer" : "float";
251
- } else if (typeof objValue === "boolean") {
252
- types[fieldPath] = "atom";
253
- } else if (_typeof(objValue) === "symbol") {
254
- types[fieldPath] = "atom";
255
- // Store the symbol's description for later use
256
- parts[indexPath][objKey] = objValue;
257
- } else if (typeof objValue === "string" && objValue.length === 0) {
258
- types[fieldPath] = "empty-binary";
259
- } else if (Array.isArray(objValue) && objValue.length === 0) {
260
- types[fieldPath] = "empty-list";
261
- } else if (isPojo(objValue) && Object.keys(objValue).length === 0) {
262
- types[fieldPath] = "empty-message";
263
- }
264
- }
265
- } else {
266
- // Non-object items in the array
267
- if (!parts[currentPath]) parts[currentPath] = {};
268
- parts[currentPath][indexKey] = item;
269
- if (typeof item === "number") {
270
- types["".concat(currentPath, "/").concat(indexKey)] = Number.isInteger(item) ? "integer" : "float";
271
- } else if (typeof item === "boolean") {
272
- types["".concat(currentPath, "/").concat(indexKey)] = "atom";
273
- }
214
+ nestedPaths.push("".concat(fullPath, "/").concat(index + 1));
274
215
  }
275
216
  });
217
+
218
+ // If array ALSO has non-object items, it needs its own body part
219
+ if (hasNonObjects) {
220
+ hasSimpleFields = true;
221
+ }
222
+ } else {
223
+ // Simple array - parent needs body part
224
+ hasSimpleFields = true;
225
+ }
226
+ } else if (isPojo(value)) {
227
+ // Check if this is an empty object
228
+ if (Object.keys(value).length === 0) {
229
+ // Empty objects need a body part
230
+ hasSimpleFields = true;
276
231
  } else {
277
- // Simple arrays without objects
278
- var _hbEncodeValue3 = hbEncodeValue(value),
279
- _hbEncodeValue4 = _slicedToArray(_hbEncodeValue3, 2),
280
- type = _hbEncodeValue4[0],
281
- encoded = _hbEncodeValue4[1];
282
- if (!parts[path]) parts[path] = {};
283
- parts[path][key] = encoded;
284
- types[currentPath] = type || "list";
232
+ // Non-empty objects are processed recursively
233
+ nestedPaths.push(fullPath);
285
234
  }
235
+ } else if (isBytes(value)) {
236
+ hasSimpleFields = true;
237
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === undefined || _typeof(value) === "symbol") {
238
+ hasSimpleFields = true;
286
239
  }
287
- } else if (isPojo(value)) {
288
- if (Object.keys(value).length === 0) {
289
- types[currentPath] = "empty-message";
290
- if (!parts[path]) parts[path] = {};
291
- parts[path][key] = "{}";
292
- } else {
293
- var hasOnlyEmptyChildren = Object.entries(value).every(function (_ref) {
294
- var _ref2 = _slicedToArray(_ref, 2),
295
- k = _ref2[0],
296
- v = _ref2[1];
297
- return Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0;
298
- });
299
- if (hasOnlyEmptyChildren) {
300
- if (!parts[currentPath]) parts[currentPath] = {};
240
+ };
241
+ for (var _i = 0, _Object$entries = Object.entries(current); _i < _Object$entries.length; _i++) {
242
+ _loop();
243
+ }
244
+
245
+ // Add current path if it has simple fields or empty objects
246
+ if (hasSimpleFields) {
247
+ keys.push(path);
248
+ }
249
+
250
+ // Process nested paths
251
+ for (var _i2 = 0, _nestedPaths = nestedPaths; _i2 < _nestedPaths.length; _i2++) {
252
+ var nestedPath = _nestedPaths[_i2];
253
+ var parts = nestedPath.split("/");
254
+ var nestedObj = obj;
255
+ var _iterator = _createForOfIteratorHelper(parts),
256
+ _step;
257
+ try {
258
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
259
+ var part = _step.value;
260
+ if (/^\d+$/.test(part)) {
261
+ nestedObj = nestedObj[parseInt(part) - 1];
262
+ } else {
263
+ nestedObj = nestedObj[part];
264
+ }
301
265
  }
302
- collectParts(value, currentPath, parts, types);
266
+ } catch (err) {
267
+ _iterator.e(err);
268
+ } finally {
269
+ _iterator.f();
303
270
  }
304
- } else if (_typeof(value) === "symbol") {
305
- if (!parts[path]) parts[path] = {};
306
- parts[path][key] = value.description || "symbol";
307
- types[currentPath] = "atom";
308
- } else if (typeof value === "boolean") {
309
- if (!parts[path]) parts[path] = {};
310
- parts[path][key] = value;
311
- types[currentPath] = "atom";
312
- } else {
313
- if (!parts[path]) parts[path] = {};
314
- parts[path][key] = value;
315
- if (typeof value === "number") {
316
- types[currentPath] = Number.isInteger(value) ? "integer" : "float";
271
+ if (isPojo(nestedObj)) {
272
+ traverse(nestedObj, nestedPath);
317
273
  }
318
274
  }
319
- };
320
- for (var _i = 0, _Object$entries = Object.entries(obj); _i < _Object$entries.length; _i++) {
321
- _loop();
322
275
  }
323
- return {
324
- parts: parts,
325
- types: types
276
+
277
+ // Handle top-level fields
278
+ var _loop2 = function _loop2() {
279
+ var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i3], 2),
280
+ key = _Object$entries2$_i[0],
281
+ value = _Object$entries2$_i[1];
282
+ if (Array.isArray(value)) {
283
+ var hasObjects = value.some(function (item) {
284
+ return isPojo(item);
285
+ });
286
+ var hasArrays = value.some(function (item) {
287
+ return Array.isArray(item);
288
+ });
289
+ var hasNonObjects = value.some(function (item) {
290
+ return !isPojo(item);
291
+ });
292
+ if (hasObjects) {
293
+ value.forEach(function (item, index) {
294
+ if (isPojo(item)) {
295
+ keys.push("".concat(key, "/").concat(index + 1));
296
+ // Also need to traverse into nested objects within array items
297
+ for (var _i4 = 0, _Object$entries3 = Object.entries(item); _i4 < _Object$entries3.length; _i4++) {
298
+ var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i4], 2),
299
+ nestedKey = _Object$entries3$_i[0],
300
+ nestedValue = _Object$entries3$_i[1];
301
+ if (isPojo(nestedValue)) {
302
+ keys.push("".concat(key, "/").concat(index + 1, "/").concat(nestedKey));
303
+ }
304
+ }
305
+ }
306
+ });
307
+
308
+ // Mixed arrays also need their own body part
309
+ if (hasNonObjects) {
310
+ keys.push(key);
311
+ }
312
+ } else if (hasArrays) {
313
+ // Array containing arrays needs body part
314
+ keys.push(key);
315
+ } else {
316
+ // Simple array at top level - DO NOT add to body keys
317
+ // It will go in headers instead
318
+ }
319
+ } else if (isPojo(value)) {
320
+ // Top-level object that may have nested structures
321
+ traverse(value, key);
322
+ } else if (isBytes(value)) {
323
+ // All binary data needs body parts, even empty ones
324
+ keys.push(key);
325
+ } else if (typeof value === "string" && value.includes("\n")) {
326
+ // Multiline string
327
+ keys.push(key);
328
+ }
326
329
  };
330
+ for (var _i3 = 0, _Object$entries2 = Object.entries(obj); _i3 < _Object$entries2.length; _i3++) {
331
+ _loop2();
332
+ }
333
+ return _toConsumableArray(new Set(keys)).filter(function (k) {
334
+ return k !== "";
335
+ });
336
+ }
337
+ function toBuffer(value) {
338
+ if (Buffer.isBuffer(value)) {
339
+ return value;
340
+ } else if (value && _typeof(value) === "object" && value.type === "Buffer" && Array.isArray(value.data)) {
341
+ return Buffer.from(value.data);
342
+ } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
343
+ return Buffer.from(value);
344
+ } else {
345
+ return Buffer.from(value);
346
+ }
327
347
  }
328
348
  function encode() {
329
349
  return _encode.apply(this, arguments);
@@ -331,717 +351,1172 @@ function encode() {
331
351
  function _encode() {
332
352
  _encode = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
333
353
  var obj,
354
+ _processValue,
355
+ processedObj,
356
+ _i6,
357
+ _Object$entries5,
358
+ _Object$entries5$_i,
359
+ k,
360
+ v,
361
+ hasBodyBinary,
362
+ otherFields,
363
+ allOthersSimpleOrEmptyBinary,
364
+ _headers,
365
+ _headerTypes,
366
+ _i7,
367
+ _Object$entries6,
368
+ _Object$entries6$_i,
369
+ key,
370
+ value,
371
+ encodedItems,
372
+ bodyBuffer,
373
+ bodyArrayBuffer,
374
+ _contentDigest,
375
+ _base,
334
376
  objKeys,
335
377
  fieldName,
336
378
  binaryData,
379
+ _headers2,
380
+ _bodyBuffer,
381
+ _bodyArrayBuffer,
382
+ _contentDigest2,
383
+ _base2,
337
384
  headers,
338
- bodyBuffer,
339
- bodyArrayBuffer,
385
+ headerTypes,
386
+ bodyKeys,
387
+ _loop3,
388
+ _i8,
389
+ _Object$entries7,
390
+ _loop4,
391
+ _i9,
392
+ _Object$entries8,
393
+ allBodyKeysAreEmptyBinaries,
394
+ sortedBodyKeys,
395
+ hasSpecialDataBody,
396
+ inlineKey,
397
+ bodyParts,
398
+ _iterator3,
399
+ _step3,
400
+ _loop5,
401
+ _ret,
402
+ buffer,
403
+ specialPart,
404
+ partsContent,
405
+ allContent,
406
+ boundaryHash,
407
+ boundary,
408
+ finalParts,
409
+ i,
410
+ body,
411
+ finalContent,
340
412
  contentDigest,
341
413
  base64,
342
- _headers,
343
- types,
344
- needsMultipart,
345
- _i3,
346
- _Object$entries3,
347
- _Object$entries3$_i,
348
- key,
349
- value,
350
- _hbEncodeValue5,
351
- _hbEncodeValue6,
352
- type,
353
- encoded,
354
- body,
355
- _bodyBuffer,
356
- _bodyArrayBuffer,
357
- _contentDigest,
358
- _base,
359
- _args3 = arguments;
360
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
361
- while (1) switch (_context3.prev = _context3.next) {
414
+ bodyText,
415
+ boundaryMatch,
416
+ debugBoundary,
417
+ parts,
418
+ lines,
419
+ _args6 = arguments;
420
+ return _regeneratorRuntime().wrap(function _callee3$(_context6) {
421
+ while (1) switch (_context6.prev = _context6.next) {
362
422
  case 0:
363
- obj = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {};
364
- console.log("[encode] START with obj:", JSON.stringify(obj));
423
+ obj = _args6.length > 0 && _args6[0] !== undefined ? _args6[0] : {};
424
+ // Convert symbols to strings for logging
425
+ _processValue = function processValue(value) {
426
+ if (_typeof(value) === "symbol") {
427
+ return value.description || "Symbol.for()";
428
+ } else if (Array.isArray(value)) {
429
+ return value.map(_processValue);
430
+ } else if (isPojo(value)) {
431
+ var result = {};
432
+ for (var _i5 = 0, _Object$entries4 = Object.entries(value); _i5 < _Object$entries4.length; _i5++) {
433
+ var _Object$entries4$_i = _slicedToArray(_Object$entries4[_i5], 2),
434
+ k = _Object$entries4$_i[0],
435
+ v = _Object$entries4$_i[1];
436
+ result[k] = _processValue(v);
437
+ }
438
+ return result;
439
+ }
440
+ return value;
441
+ };
442
+ processedObj = {};
443
+ for (_i6 = 0, _Object$entries5 = Object.entries(obj); _i6 < _Object$entries5.length; _i6++) {
444
+ _Object$entries5$_i = _slicedToArray(_Object$entries5[_i6], 2), k = _Object$entries5$_i[0], v = _Object$entries5$_i[1];
445
+ processedObj[k] = _processValue(v);
446
+ }
447
+
448
+ // Remove debug logging for cleaner output
449
+ console.log("[encode] START with obj:", JSON.stringify(processedObj));
365
450
  if (!(Object.keys(obj).length === 0)) {
366
- _context3.next = 4;
451
+ _context6.next = 7;
367
452
  break;
368
453
  }
369
- return _context3.abrupt("return", {
454
+ return _context6.abrupt("return", {
370
455
  headers: {},
371
456
  body: undefined
372
457
  });
373
- case 4:
374
- // Check if we have a simple binary field
375
- objKeys = Object.keys(obj);
376
- if (!(objKeys.length === 1 && isBytes(obj[objKeys[0]]))) {
377
- _context3.next = 18;
378
- break;
379
- }
380
- // Single binary field - return it directly
381
- fieldName = objKeys[0];
382
- binaryData = obj[fieldName];
383
- headers = {};
384
- bodyBuffer = Buffer.isBuffer(binaryData) ? binaryData : Buffer.from(binaryData);
385
- bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
386
- _context3.next = 13;
387
- return sha256(bodyArrayBuffer);
388
- case 13:
389
- contentDigest = _context3.sent;
390
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
391
- headers["content-digest"] = "sha-256=:".concat(base64, ":");
392
- console.log("[encode] FINAL (simple binary field) - headers:", headers, "body:", binaryData);
393
- return _context3.abrupt("return", {
394
- headers: headers,
395
- body: binaryData
458
+ case 7:
459
+ // Check for special case: body field with binary + other simple fields or empty binaries
460
+ hasBodyBinary = obj.body && isBytes(obj.body);
461
+ otherFields = Object.keys(obj).filter(function (k) {
462
+ return k !== "body";
463
+ });
464
+ allOthersSimpleOrEmptyBinary = otherFields.every(function (k) {
465
+ var v = obj[k];
466
+ // Allow empty binaries as "simple"
467
+ if (isBytes(v) && (v.length === 0 || v.byteLength === 0)) return true;
468
+ return !isBytes(v) && !isPojo(v) && !(Array.isArray(v) && v.some(function (item) {
469
+ return isPojo(item) || isBytes(item);
470
+ }));
396
471
  });
397
- case 18:
398
- if (!("body" in obj && isBytes(obj.body))) {
399
- _context3.next = 108;
472
+ if (!(hasBodyBinary && allOthersSimpleOrEmptyBinary)) {
473
+ _context6.next = 34;
400
474
  break;
401
475
  }
476
+ console.log("[encode] Special case: body with binary + simple fields");
477
+ // Special case: body with binary + other simple fields
402
478
  _headers = {};
403
- types = [];
404
- needsMultipart = false;
405
- _i3 = 0, _Object$entries3 = Object.entries(obj);
406
- case 23:
407
- if (!(_i3 < _Object$entries3.length)) {
408
- _context3.next = 95;
479
+ _headerTypes = []; // Process other fields into headers
480
+ _i7 = 0, _Object$entries6 = Object.entries(obj);
481
+ case 15:
482
+ if (!(_i7 < _Object$entries6.length)) {
483
+ _context6.next = 24;
409
484
  break;
410
485
  }
411
- _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2), key = _Object$entries3$_i[0], value = _Object$entries3$_i[1];
486
+ _Object$entries6$_i = _slicedToArray(_Object$entries6[_i7], 2), key = _Object$entries6$_i[0], value = _Object$entries6$_i[1];
412
487
  if (!(key === "body")) {
413
- _context3.next = 27;
414
- break;
415
- }
416
- return _context3.abrupt("continue", 92);
417
- case 27:
418
- if (!(value === null)) {
419
- _context3.next = 32;
420
- break;
421
- }
422
- _headers[key] = "null";
423
- types.push("".concat(key, "=\"atom\""));
424
- _context3.next = 92;
425
- break;
426
- case 32:
427
- if (!(value === undefined)) {
428
- _context3.next = 37;
429
- break;
430
- }
431
- _headers[key] = "undefined";
432
- types.push("".concat(key, "=\"atom\""));
433
- _context3.next = 92;
434
- break;
435
- case 37:
436
- if (!(typeof value === "string" && value.length === 0)) {
437
- _context3.next = 41;
438
- break;
439
- }
440
- types.push("".concat(key, "=\"empty-binary\""));
441
- _context3.next = 92;
442
- break;
443
- case 41:
444
- if (!Array.isArray(value)) {
445
- _context3.next = 57;
446
- break;
447
- }
448
- if (!(value.length === 0)) {
449
- _context3.next = 46;
488
+ _context6.next = 19;
450
489
  break;
451
490
  }
452
- types.push("".concat(key, "=\"empty-list\""));
453
- _context3.next = 55;
454
- break;
455
- case 46:
456
- if (!value.some(function (item) {
491
+ return _context6.abrupt("continue", 21);
492
+ case 19:
493
+ console.log("[encode] Processing special case field: ".concat(key, " = ").concat(JSON.stringify(value)));
494
+ if (value === null) {
495
+ _headers[key] = '"null"';
496
+ _headerTypes.push("".concat(key, "=\"atom\""));
497
+ } else if (value === undefined) {
498
+ _headers[key] = '"undefined"';
499
+ _headerTypes.push("".concat(key, "=\"atom\""));
500
+ } else if (typeof value === "boolean") {
501
+ _headers[key] = "\"".concat(value, "\"");
502
+ _headerTypes.push("".concat(key, "=\"atom\""));
503
+ } else if (_typeof(value) === "symbol") {
504
+ _headers[key] = "\"".concat(value.description || "Symbol.for()", "\"");
505
+ _headerTypes.push("".concat(key, "=\"atom\""));
506
+ } else if (typeof value === "number") {
507
+ _headers[key] = String(value);
508
+ _headerTypes.push("".concat(key, "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
509
+ } else if (typeof value === "string") {
510
+ if (value.length === 0) {
511
+ // Empty strings only go in ao-types, not as headers
512
+ console.log("[encode] Adding empty string type for key: ".concat(key));
513
+ _headerTypes.push("".concat(key, "=\"empty-binary\""));
514
+ } else {
515
+ _headers[key] = value;
516
+ }
517
+ } else if (Array.isArray(value) && value.length === 0) {
518
+ // Empty array only goes in ao-types, not as a header
519
+ _headerTypes.push("".concat(key, "=\"empty-list\""));
520
+ } else if (Array.isArray(value) && !value.some(function (item) {
457
521
  return isPojo(item);
458
522
  })) {
459
- _context3.next = 52;
460
- break;
461
- }
462
- // Arrays with objects need multipart
463
- types.push("".concat(key, "=\"list\""));
464
- needsMultipart = true;
465
- return _context3.abrupt("break", 95);
466
- case 52:
467
- _hbEncodeValue5 = hbEncodeValue(value), _hbEncodeValue6 = _slicedToArray(_hbEncodeValue5, 2), type = _hbEncodeValue6[0], encoded = _hbEncodeValue6[1];
468
- _headers[key] = encoded;
469
- types.push("".concat(key, "=\"").concat(type, "\""));
470
- case 55:
471
- _context3.next = 92;
472
- break;
473
- case 57:
474
- if (!isBytes(value)) {
475
- _context3.next = 66;
476
- break;
477
- }
478
- if (!(value.length === 0 || value.byteLength === 0)) {
479
- _context3.next = 62;
480
- break;
481
- }
482
- types.push("".concat(key, "=\"empty-binary\""));
483
- _context3.next = 64;
484
- break;
485
- case 62:
486
- needsMultipart = true;
487
- return _context3.abrupt("break", 95);
488
- case 64:
489
- _context3.next = 92;
490
- break;
491
- case 66:
492
- if (!(typeof value === "boolean")) {
493
- _context3.next = 71;
494
- break;
495
- }
496
- _headers[key] = "\"".concat(value, "\"");
497
- types.push("".concat(key, "=\"atom\""));
498
- _context3.next = 92;
499
- break;
500
- case 71:
501
- if (!(_typeof(value) === "symbol")) {
502
- _context3.next = 76;
503
- break;
504
- }
505
- _headers[key] = value.description || "symbol";
506
- types.push("".concat(key, "=\"atom\""));
507
- _context3.next = 92;
508
- break;
509
- case 76:
510
- if (!(typeof value === "number")) {
511
- _context3.next = 81;
512
- break;
513
- }
514
- _headers[key] = String(value);
515
- types.push("".concat(key, "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
516
- _context3.next = 92;
517
- break;
518
- case 81:
519
- if (!(typeof value === "string")) {
520
- _context3.next = 85;
521
- break;
523
+ encodedItems = value.map(function (item) {
524
+ return encodeArrayItem(item);
525
+ }).join(", ");
526
+ _headers[key] = encodedItems;
527
+ _headerTypes.push("".concat(key, "=\"list\""));
528
+ } else if (isBytes(value) && (value.length === 0 || value.byteLength === 0)) {
529
+ // Empty binary goes in ao-types only
530
+ _headerTypes.push("".concat(key, "=\"empty-binary\""));
522
531
  }
523
- _headers[key] = value;
524
- _context3.next = 92;
525
- break;
526
- case 85:
527
- if (!(isPojo(value) && Object.keys(value).length === 0)) {
528
- _context3.next = 89;
529
- break;
530
- }
531
- types.push("".concat(key, "=\"empty-message\""));
532
- _context3.next = 92;
533
- break;
534
- case 89:
535
- if (!isPojo(value)) {
536
- _context3.next = 92;
537
- break;
538
- }
539
- needsMultipart = true;
540
- return _context3.abrupt("break", 95);
541
- case 92:
542
- _i3++;
543
- _context3.next = 23;
532
+ case 21:
533
+ _i7++;
534
+ _context6.next = 15;
544
535
  break;
545
- case 95:
546
- if (!needsMultipart) {
547
- _context3.next = 97;
548
- break;
549
- }
550
- return _context3.abrupt("return", encodeMultipart(obj));
551
- case 97:
552
- if (types.length > 0) {
553
- _headers["ao-types"] = types.sort().join(", ");
536
+ case 24:
537
+ // Add ao-types if needed
538
+ if (_headerTypes.length > 0) {
539
+ _headers["ao-types"] = _headerTypes.sort().join(", ");
554
540
  }
555
- body = obj.body;
556
- _bodyBuffer = Buffer.isBuffer(body) ? body : Buffer.from(body);
557
- _bodyArrayBuffer = _bodyBuffer.buffer.slice(_bodyBuffer.byteOffset, _bodyBuffer.byteOffset + _bodyBuffer.byteLength);
558
- _context3.next = 103;
559
- return sha256(_bodyArrayBuffer);
560
- case 103:
561
- _contentDigest = _context3.sent;
541
+
542
+ // Set body to binary
543
+ bodyBuffer = toBuffer(obj.body);
544
+ bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
545
+ _context6.next = 29;
546
+ return sha256(bodyArrayBuffer);
547
+ case 29:
548
+ _contentDigest = _context6.sent;
562
549
  _base = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest));
563
550
  _headers["content-digest"] = "sha-256=:".concat(_base, ":");
564
- console.log("[encode] FINAL (simple body encoding) - headers:", _headers, "body:", body);
565
- return _context3.abrupt("return", {
551
+ console.log("[encode] FINAL (body with binary) - headers:", _headers, "body:", obj.body);
552
+ return _context6.abrupt("return", {
566
553
  headers: _headers,
567
- body: body
554
+ body: obj.body
568
555
  });
569
- case 108:
570
- return _context3.abrupt("return", encodeMultipart(obj));
571
- case 109:
572
- case "end":
573
- return _context3.stop();
574
- }
575
- }, _callee3);
576
- }));
577
- return _encode.apply(this, arguments);
578
- }
579
- function encodeMultipart(_x3) {
580
- return _encodeMultipart.apply(this, arguments);
581
- }
582
- function _encodeMultipart() {
583
- _encodeMultipart = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(obj) {
584
- var _collectParts, parts, types, headers, bodyParts, bodyKeys, headerTypes, _i4, _Object$entries4, _Object$entries4$_i, key, value, _i5, _Object$entries5, _Object$entries5$_i, path, content, _i6, _Object$entries6, _Object$entries6$_i, _key, _value, length, valueStr, type, _i7, _Object$entries7, _Object$entries7$_i, _key2, _value2, _type, _i8, _Object$entries8, _Object$entries8$_i, _key3, _type2, inlineKey, _iterator, _step, _path, fieldValue, headerStr, headerBlob, dataBlob, _lines, _isInlineKey, _type3, _content, lines, binaryParts, isInlineKey, sortedKeys, partTypes, _iterator3, _step3, _key4, fullPath, _type4, _iterator4, _step4, _key5, _value3, _fullPath, _type5, symbolValue, allParts, _iterator5, _step5, binaryPart, partsForBoundary, _iterator2, _step2, part, partContent, allPartsContent, allPartsBuffer, hashResult, boundary, finalParts, i, body, finalContent, contentDigest, base64;
585
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
586
- while (1) switch (_context4.prev = _context4.next) {
587
- case 0:
588
- _collectParts = collectParts(obj), parts = _collectParts.parts, types = _collectParts.types;
589
- console.log("[encode] Parts:", parts, "Types:", types);
590
- headers = {};
591
- bodyParts = [];
592
- bodyKeys = []; // Collect header types for arrays with objects
593
- headerTypes = [];
594
- for (_i4 = 0, _Object$entries4 = Object.entries(obj); _i4 < _Object$entries4.length; _i4++) {
595
- _Object$entries4$_i = _slicedToArray(_Object$entries4[_i4], 2), key = _Object$entries4$_i[0], value = _Object$entries4$_i[1];
596
- if (Array.isArray(value) && value.some(function (item) {
597
- return isPojo(item);
598
- })) {
599
- headerTypes.push("".concat(key, "=\"list\""));
600
- }
601
- }
602
- _i5 = 0, _Object$entries5 = Object.entries(parts);
603
- case 8:
604
- if (!(_i5 < _Object$entries5.length)) {
605
- _context4.next = 57;
606
- break;
607
- }
608
- _Object$entries5$_i = _slicedToArray(_Object$entries5[_i5], 2), path = _Object$entries5$_i[0], content = _Object$entries5$_i[1];
609
- if (!(path === "")) {
610
- _context4.next = 53;
611
- break;
612
- }
613
- _i6 = 0, _Object$entries6 = Object.entries(content);
614
- case 12:
615
- if (!(_i6 < _Object$entries6.length)) {
616
- _context4.next = 51;
556
+ case 34:
557
+ // Check if single binary field
558
+ objKeys = Object.keys(obj);
559
+ if (!(objKeys.length === 1 && isBytes(obj[objKeys[0]]))) {
560
+ _context6.next = 49;
617
561
  break;
618
562
  }
619
- _Object$entries6$_i = _slicedToArray(_Object$entries6[_i6], 2), _key = _Object$entries6$_i[0], _value = _Object$entries6$_i[1];
620
- if (!isBytes(_value)) {
621
- _context4.next = 25;
622
- break;
563
+ fieldName = objKeys[0];
564
+ binaryData = obj[fieldName];
565
+ _headers2 = {};
566
+ _bodyBuffer = toBuffer(binaryData);
567
+ _bodyArrayBuffer = _bodyBuffer.buffer.slice(_bodyBuffer.byteOffset, _bodyBuffer.byteOffset + _bodyBuffer.byteLength);
568
+ _context6.next = 43;
569
+ return sha256(_bodyArrayBuffer);
570
+ case 43:
571
+ _contentDigest2 = _context6.sent;
572
+ _base2 = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest2));
573
+ _headers2["content-digest"] = "sha-256=:".concat(_base2, ":");
574
+
575
+ // Add inline-body-key header to preserve the field name
576
+ if (fieldName !== "body") {
577
+ _headers2["inline-body-key"] = fieldName;
623
578
  }
624
- length = _value.byteLength || _value.length || 0;
625
- if (!(length === 0)) {
626
- _context4.next = 21;
579
+ console.log("[encode] FINAL (simple binary field) - headers:", _headers2, "body:", binaryData);
580
+ return _context6.abrupt("return", {
581
+ headers: _headers2,
582
+ body: binaryData
583
+ });
584
+ case 49:
585
+ // Continue with normal multipart processing
586
+ headers = {};
587
+ headerTypes = []; // Collect all body keys
588
+ bodyKeys = collectBodyKeys(obj); // Process simple header fields AND collect types for body fields
589
+ _loop3 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop3() {
590
+ var _Object$entries7$_i, key, value, needsBody, _encodedItems;
591
+ return _regeneratorRuntime().wrap(function _loop3$(_context3) {
592
+ while (1) switch (_context3.prev = _context3.next) {
593
+ case 0:
594
+ _Object$entries7$_i = _slicedToArray(_Object$entries7[_i8], 2), key = _Object$entries7$_i[0], value = _Object$entries7$_i[1];
595
+ console.log("[encode] Processing field: ".concat(key, " = ").concat(JSON.stringify(value), ", type: ").concat(_typeof(value)));
596
+ needsBody = bodyKeys.includes(key) || bodyKeys.some(function (k) {
597
+ return k.startsWith("".concat(key, "/"));
598
+ });
599
+ if (!needsBody) {
600
+ console.log("[encode] Field ".concat(key, " doesn't need body, adding to headers"));
601
+ // Simple value goes in header
602
+ if (value === null) {
603
+ headers[key] = '"null"';
604
+ headerTypes.push("".concat(key, "=\"atom\""));
605
+ } else if (value === undefined) {
606
+ headers[key] = '"undefined"';
607
+ headerTypes.push("".concat(key, "=\"atom\""));
608
+ } else if (typeof value === "boolean") {
609
+ headers[key] = "\"".concat(value, "\"");
610
+ headerTypes.push("".concat(key, "=\"atom\""));
611
+ } else if (_typeof(value) === "symbol") {
612
+ headers[key] = "\"".concat(value.description || "Symbol.for()", "\"");
613
+ headerTypes.push("".concat(key, "=\"atom\""));
614
+ } else if (typeof value === "number") {
615
+ headers[key] = String(value);
616
+ headerTypes.push("".concat(key, "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
617
+ } else if (typeof value === "string") {
618
+ if (value.length === 0) {
619
+ headerTypes.push("".concat(key, "=\"empty-binary\""));
620
+ // Don't add empty strings as headers
621
+ } else {
622
+ headers[key] = value;
623
+ }
624
+ } else if (Array.isArray(value) && !value.some(function (item) {
625
+ return isPojo(item);
626
+ })) {
627
+ // Simple array (no objects) goes in header
628
+ _encodedItems = value.map(function (item) {
629
+ return encodeArrayItem(item);
630
+ }).join(", ");
631
+ headers[key] = _encodedItems;
632
+ headerTypes.push("".concat(key, "=\"list\""));
633
+ }
634
+ } else {
635
+ // Field needs body - still need to add type info to ao-types
636
+ if (isBytes(value) && (value.length === 0 || value.byteLength === 0)) {
637
+ headerTypes.push("".concat(key, "=\"empty-binary\""));
638
+ } else if (typeof value === "string" && value.length === 0) {
639
+ headerTypes.push("".concat(key, "=\"empty-binary\""));
640
+ } else if (Array.isArray(value) && value.length === 0) {
641
+ headerTypes.push("".concat(key, "=\"empty-list\""));
642
+ } else if (isPojo(value) && Object.keys(value).length === 0) {
643
+ headerTypes.push("".concat(key, "=\"empty-message\""));
644
+ }
645
+ }
646
+ case 4:
647
+ case "end":
648
+ return _context3.stop();
649
+ }
650
+ }, _loop3);
651
+ });
652
+ _i8 = 0, _Object$entries7 = Object.entries(obj);
653
+ case 54:
654
+ if (!(_i8 < _Object$entries7.length)) {
655
+ _context6.next = 59;
627
656
  break;
628
657
  }
629
- // Empty binaries stay in headers
630
- console.log("[encode] Empty binary field ".concat(_key, " staying in headers"));
631
- return _context4.abrupt("continue", 48);
632
- case 21:
633
- console.log("[encode] Binary field ".concat(_key, " going to body"));
634
- bodyKeys.push(_key);
635
- case 23:
636
- _context4.next = 48;
658
+ return _context6.delegateYield(_loop3(), "t0", 56);
659
+ case 56:
660
+ _i8++;
661
+ _context6.next = 54;
637
662
  break;
638
- case 25:
639
- valueStr = String(_value);
640
- type = types[_key];
641
- if (!(type === "empty-binary" && valueStr === "")) {
642
- _context4.next = 29;
643
- break;
644
- }
645
- return _context4.abrupt("continue", 48);
646
- case 29:
647
- _context4.next = 31;
648
- return hasNewline(valueStr);
649
- case 31:
650
- _context4.t3 = !_context4.sent;
651
- if (!_context4.t3) {
652
- _context4.next = 34;
653
- break;
654
- }
655
- _context4.t3 = !_key.includes("/");
656
- case 34:
657
- _context4.t2 = _context4.t3;
658
- if (!_context4.t2) {
659
- _context4.next = 37;
663
+ case 59:
664
+ _loop4 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop4() {
665
+ var _Object$entries8$_i, key, value;
666
+ return _regeneratorRuntime().wrap(function _loop4$(_context4) {
667
+ while (1) switch (_context4.prev = _context4.next) {
668
+ case 0:
669
+ _Object$entries8$_i = _slicedToArray(_Object$entries8[_i9], 2), key = _Object$entries8$_i[0], value = _Object$entries8$_i[1];
670
+ if (Array.isArray(value)) {
671
+ // Check if this array goes in the body
672
+ if (bodyKeys.includes(key) || bodyKeys.some(function (k) {
673
+ return k.startsWith("".concat(key, "/"));
674
+ })) {
675
+ // Don't add list type if it's already been added
676
+ if (!headerTypes.some(function (t) {
677
+ return t.startsWith("".concat(key, "="));
678
+ })) {
679
+ headerTypes.push("".concat(key, "=\"list\""));
680
+ }
681
+ }
682
+ }
683
+ case 2:
684
+ case "end":
685
+ return _context4.stop();
686
+ }
687
+ }, _loop4);
688
+ });
689
+ _i9 = 0, _Object$entries8 = Object.entries(obj);
690
+ case 61:
691
+ if (!(_i9 < _Object$entries8.length)) {
692
+ _context6.next = 66;
660
693
  break;
661
694
  }
662
- _context4.t2 = Buffer.from(valueStr).byteLength <= MAX_HEADER_LENGTH;
663
- case 37:
664
- _context4.t1 = _context4.t2;
665
- if (!_context4.t1) {
666
- _context4.next = 40;
695
+ return _context6.delegateYield(_loop4(), "t1", 63);
696
+ case 63:
697
+ _i9++;
698
+ _context6.next = 61;
699
+ break;
700
+ case 66:
701
+ if (!(bodyKeys.length === 0)) {
702
+ _context6.next = 70;
667
703
  break;
668
704
  }
669
- _context4.t1 = !isPojo(_value);
670
- case 40:
671
- _context4.t0 = _context4.t1;
672
- if (!_context4.t0) {
673
- _context4.next = 43;
674
- break;
705
+ if (headerTypes.length > 0) {
706
+ headers["ao-types"] = headerTypes.sort().join(", ");
675
707
  }
676
- _context4.t0 = !(_key === "data" || _key === "body");
677
- case 43:
678
- if (!_context4.t0) {
679
- _context4.next = 47;
708
+ console.log("[encode] FINAL - headers:", headers, "body:", undefined);
709
+ return _context6.abrupt("return", {
710
+ headers: headers,
711
+ body: undefined
712
+ });
713
+ case 70:
714
+ // Check if all body keys are for empty binaries - if so, treat as no body needed
715
+ allBodyKeysAreEmptyBinaries = bodyKeys.every(function (key) {
716
+ var pathParts = key.split("/");
717
+ var value = obj;
718
+ var _iterator2 = _createForOfIteratorHelper(pathParts),
719
+ _step2;
720
+ try {
721
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
722
+ var part = _step2.value;
723
+ if (/^\d+$/.test(part)) {
724
+ value = value[parseInt(part) - 1];
725
+ } else {
726
+ value = value[part];
727
+ }
728
+ }
729
+ } catch (err) {
730
+ _iterator2.e(err);
731
+ } finally {
732
+ _iterator2.f();
733
+ }
734
+ return isBytes(value) && (value.length === 0 || value.byteLength === 0);
735
+ });
736
+ if (!allBodyKeysAreEmptyBinaries) {
737
+ _context6.next = 75;
680
738
  break;
681
739
  }
682
- if (typeof _value === "number") {
683
- headers[_key] = String(_value);
684
- } else if (typeof _value === "boolean") {
685
- headers[_key] = "\"".concat(_value, "\"");
686
- } else if (_value === "[]" && type === "empty_list") {
687
- headers[_key] = "[]";
688
- } else if (_value === '"null"' || _value === '"undefined"') {
689
- headers[_key] = _value;
690
- } else {
691
- headers[_key] = _value;
740
+ // Treat as header-only encoding
741
+ if (headerTypes.length > 0) {
742
+ headers["ao-types"] = headerTypes.sort().join(", ");
692
743
  }
693
- _context4.next = 48;
694
- break;
695
- case 47:
696
- bodyKeys.push(_key);
697
- case 48:
698
- _i6++;
699
- _context4.next = 12;
700
- break;
701
- case 51:
702
- _context4.next = 54;
703
- break;
704
- case 53:
705
- bodyKeys.push(path);
706
- case 54:
707
- _i5++;
708
- _context4.next = 8;
709
- break;
710
- case 57:
711
- console.log("[encode] Headers before filtering:", headers, "BodyKeys:", bodyKeys);
712
- bodyKeys.sort();
744
+ console.log("[encode] FINAL (all empty binaries) - headers:", headers, "body:", undefined);
745
+ return _context6.abrupt("return", {
746
+ headers: headers,
747
+ body: undefined
748
+ });
749
+ case 75:
750
+ // Sort body keys and add to headers
751
+ sortedBodyKeys = bodyKeys.sort(function (a, b) {
752
+ // Special sorting to ensure parent paths come before child paths
753
+ if (a.startsWith(b + "/")) return 1;
754
+ if (b.startsWith(a + "/")) return -1;
755
+ return a.localeCompare(b);
756
+ }); // Special case: if we have both 'data' and 'body' keys where data.body is binary
757
+ // then we need special handling per Erlang behavior
758
+ 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);
759
+ headers["body-keys"] = sortedBodyKeys.map(function (k) {
760
+ return "\"".concat(k, "\"");
761
+ }).join(", ");
713
762
 
714
- // Add types for values in headers
715
- for (_i7 = 0, _Object$entries7 = Object.entries(headers); _i7 < _Object$entries7.length; _i7++) {
716
- _Object$entries7$_i = _slicedToArray(_Object$entries7[_i7], 2), _key2 = _Object$entries7$_i[0], _value2 = _Object$entries7$_i[1];
717
- _type = types[_key2];
718
- if (_type) {
719
- headerTypes.push("".concat(_key2, "=\"").concat(_type, "\""));
763
+ // Check for inline keys - but not in the special data/body case
764
+ if (!hasSpecialDataBody) {
765
+ inlineKey = headers["inline-body-key"];
766
+ if (!inlineKey) {
767
+ // Only set inline-body-key if we have ONLY body (not data)
768
+ if (sortedBodyKeys.includes("body") && !sortedBodyKeys.includes("data")) {
769
+ headers["inline-body-key"] = "body";
770
+ }
720
771
  }
721
772
  }
722
773
 
723
- // Add types for empty values not in headers
724
- for (_i8 = 0, _Object$entries8 = Object.entries(types); _i8 < _Object$entries8.length; _i8++) {
725
- _Object$entries8$_i = _slicedToArray(_Object$entries8[_i8], 2), _key3 = _Object$entries8$_i[0], _type2 = _Object$entries8$_i[1];
726
- if (!_key3.includes("/") && _type2.startsWith("empty") && !headers[_key3]) {
727
- headerTypes.push("".concat(_key3, "=\"").concat(_type2.replace("empty_", "empty-"), "\""));
728
- }
729
- }
774
+ // Add ao-types header if needed
730
775
  if (headerTypes.length > 0) {
731
776
  headers["ao-types"] = headerTypes.sort().join(", ");
732
777
  }
733
- if (!(bodyKeys.length > 0)) {
734
- _context4.next = 185;
735
- break;
736
- }
737
- headers["body-keys"] = encode_body_keys(bodyKeys);
738
- if (bodyKeys.includes("data") || bodyKeys.includes("body")) {
739
- inlineKey = bodyKeys.find(function (k) {
740
- return k === "data" || k === "body";
741
- });
742
- headers["inline-body-key"] = inlineKey;
743
- }
744
778
 
745
779
  // Create multipart body parts
746
- _iterator = _createForOfIteratorHelper(bodyKeys);
747
- _context4.prev = 66;
748
- _iterator.s();
749
- case 68:
750
- if ((_step = _iterator.n()).done) {
751
- _context4.next = 133;
752
- break;
753
- }
754
- _path = _step.value;
755
- console.log("[encode] Processing bodyKey: ".concat(_path));
780
+ bodyParts = [];
781
+ _iterator3 = _createForOfIteratorHelper(sortedBodyKeys);
782
+ _context6.prev = 82;
783
+ _loop5 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop5() {
784
+ var bodyKey, lines, pathParts, value, parent, _i10, part, isInline, _buffer, textPart, _textPart, objectTypes, fieldLines, binaryFields, _i11, _Object$entries9, _Object$entries9$_i, _k, _v, childPath, _buffer2, _encodedItems2, onlyEmptyCollections, orderedLines, _iterator4, _step4, line, _binaryFields, _parts, _iterator5, _step5, _step5$value, _key, _buffer3, fullBody, _iterator6, _step6, _line, _parts2, headerText, _iterator7, _step7, _step7$value, _key2, _buffer4, _fullBody, hasObjects, hasArrays, nonObjectItems, _fieldLines, partTypes, _iterator8, _step8, _step8$value, item, index, _buffer5, _encodedItems3, _orderedLines, _iterator9, _step9, _line2, _iterator10, _step10, _line3, _fieldLines2, _partTypes, _orderedLines2, _iterator11, _step11, _line4, _iterator12, _step12, _line5, _fieldName, _partTypes2;
785
+ return _regeneratorRuntime().wrap(function _loop5$(_context5) {
786
+ while (1) switch (_context5.prev = _context5.next) {
787
+ case 0:
788
+ bodyKey = _step3.value;
789
+ lines = []; // Parse the path to get to the value
790
+ pathParts = bodyKey.split("/");
791
+ value = obj;
792
+ parent = null; // Get the actual value at this path
793
+ for (_i10 = 0; _i10 < pathParts.length; _i10++) {
794
+ parent = value;
795
+ part = pathParts[_i10];
796
+ if (/^\d+$/.test(part)) {
797
+ value = value[parseInt(part) - 1];
798
+ } else {
799
+ value = value[part];
800
+ }
801
+ }
802
+ console.log("[encode] Processing body key:", bodyKey, "value type:", Array.isArray(value) ? "array" : _typeof(value));
756
803
 
757
- // Handle root-level fields
758
- if (_path.includes("/")) {
759
- _context4.next = 94;
760
- break;
761
- }
762
- // This is a root-level field
763
- fieldValue = parts[""] && parts[""][_path];
764
- console.log("[encode] Root field ".concat(_path, " value:"), fieldValue);
765
- if (!(fieldValue !== undefined)) {
766
- _context4.next = 94;
767
- break;
768
- }
769
- if (!isBytes(fieldValue)) {
770
- _context4.next = 84;
771
- break;
772
- }
773
- // Binary field - create a simple multipart section
774
- // The format should be:
775
- // content-disposition: form-data;name="fieldname"
776
- // [empty line]
777
- // [binary data]
778
- headerStr = "content-disposition: form-data;name=\"".concat(_path, "\"\r\n\r\n");
779
- headerBlob = new Blob([headerStr]);
780
- dataBlob = new Blob([fieldValue]);
781
- bodyParts.push(new Blob([headerBlob, dataBlob]));
782
- console.log("[encode] Added binary field ".concat(_path, " to bodyParts"));
783
- return _context4.abrupt("continue", 131);
784
- case 84:
785
- // Non-binary root field that needs to go in body
786
- _lines = []; // Check if this is an inline key
787
- _isInlineKey = _path === "data" || _path === "body";
788
- if (_isInlineKey) {
789
- _lines.push("content-disposition: inline");
790
- } else {
791
- _lines.push("content-disposition: form-data;name=\"".concat(_path, "\""));
792
- }
804
+ // Skip if value is an array with only objects (no content for this body part)
805
+ if (!(Array.isArray(value) && value.every(function (item) {
806
+ return isPojo(item);
807
+ }))) {
808
+ _context5.next = 9;
809
+ break;
810
+ }
811
+ return _context5.abrupt("return", 0);
812
+ case 9:
813
+ if (!(isPojo(value) && Object.keys(value).length === 0)) {
814
+ _context5.next = 11;
815
+ break;
816
+ }
817
+ return _context5.abrupt("return", 0);
818
+ case 11:
819
+ if (!(hasSpecialDataBody && bodyKey === "data" && isPojo(value) && Object.keys(value).length === 1 && value.body && isBytes(value.body))) {
820
+ _context5.next = 13;
821
+ break;
822
+ }
823
+ return _context5.abrupt("return", 0);
824
+ case 13:
825
+ console.log("[encode] Creating body part for key:", bodyKey, "value type:", _typeof(value), "isBytes:", isBytes(value));
793
826
 
794
- // Add the field type if available
795
- _type3 = types[_path];
796
- if (_type3) {
797
- _lines.push("ao-types: ".concat(_path, "=\"").concat(_type3, "\""));
798
- }
827
+ // Determine content-disposition
828
+ isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
829
+ if (isInline) {
830
+ lines.push("content-disposition: inline");
831
+ } else {
832
+ lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
833
+ }
834
+ console.log("[encode] Value type checks:", {
835
+ isBytes: isBytes(value),
836
+ isPojo: isPojo(value),
837
+ isArray: Array.isArray(value),
838
+ valueType: _typeof(value)
839
+ });
840
+ if (!isBytes(value)) {
841
+ _context5.next = 23;
842
+ break;
843
+ }
844
+ console.log("[encode] Processing binary value for key:", bodyKey);
845
+ // Binary data
846
+ _buffer = toBuffer(value); // Check if this is a nested path like "data/body"
847
+ if (bodyKey.includes("/")) {
848
+ // For nested binary, we need to replace the disposition
849
+ lines[lines.length - 1] = "content-disposition: form-data;name=\"".concat(bodyKey, "\"");
850
+ lines.push(""); // Empty line
851
+ lines.push(""); // Another empty line before binary
852
+ textPart = lines.join("\r\n");
853
+ bodyParts.push(new Blob([textPart, _buffer]));
854
+ } else {
855
+ lines.push(""); // Empty line after headers
856
+ lines.push(""); // Another empty line before binary data
857
+ _textPart = lines.join("\r\n");
858
+ bodyParts.push(new Blob([_textPart, _buffer]));
859
+ }
860
+ _context5.next = 80;
861
+ break;
862
+ case 23:
863
+ if (!isPojo(value)) {
864
+ _context5.next = 79;
865
+ break;
866
+ }
867
+ console.log("[encode] Processing object value");
868
+ // Object - only include fields that aren't handled by nested body parts
869
+ objectTypes = [];
870
+ fieldLines = [];
871
+ binaryFields = [];
872
+ _i11 = 0, _Object$entries9 = Object.entries(value);
873
+ case 29:
874
+ if (!(_i11 < _Object$entries9.length)) {
875
+ _context5.next = 75;
876
+ break;
877
+ }
878
+ _Object$entries9$_i = _slicedToArray(_Object$entries9[_i11], 2), _k = _Object$entries9$_i[0], _v = _Object$entries9$_i[1];
879
+ childPath = "".concat(bodyKey, "/").concat(_k); // Skip if this field has its own body part
880
+ if (!sortedBodyKeys.includes(childPath)) {
881
+ _context5.next = 34;
882
+ break;
883
+ }
884
+ return _context5.abrupt("continue", 72);
885
+ case 34:
886
+ if (!(Array.isArray(_v) && _v.some(function (item) {
887
+ return isPojo(item);
888
+ }))) {
889
+ _context5.next = 36;
890
+ break;
891
+ }
892
+ return _context5.abrupt("continue", 72);
893
+ case 36:
894
+ // Add type info
895
+ if (Array.isArray(_v)) {
896
+ objectTypes.push("".concat(_k, "=\"").concat(_v.length === 0 ? "empty-list" : "list", "\""));
897
+ } else if (_v === null || _v === undefined || _typeof(_v) === "symbol" || typeof _v === "boolean") {
898
+ objectTypes.push("".concat(_k, "=\"atom\""));
899
+ } else if (typeof _v === "number") {
900
+ objectTypes.push("".concat(_k, "=\"").concat(Number.isInteger(_v) ? "integer" : "float", "\""));
901
+ } else if (typeof _v === "string" && _v.length === 0) {
902
+ objectTypes.push("".concat(_k, "=\"empty-binary\""));
903
+ } else if (isBytes(_v) && (_v.length === 0 || _v.byteLength === 0)) {
904
+ objectTypes.push("".concat(_k, "=\"empty-binary\""));
905
+ } else if (isPojo(_v) && Object.keys(_v).length === 0) {
906
+ objectTypes.push("".concat(_k, "=\"empty-message\""));
907
+ }
799
908
 
800
- // Add empty line before content
801
- _lines.push("");
909
+ // Add field value
910
+ if (!(typeof _v === "string")) {
911
+ _context5.next = 41;
912
+ break;
913
+ }
914
+ fieldLines.push("".concat(_k, ": ").concat(_v));
915
+ _context5.next = 72;
916
+ break;
917
+ case 41:
918
+ if (!(typeof _v === "number")) {
919
+ _context5.next = 45;
920
+ break;
921
+ }
922
+ fieldLines.push("".concat(_k, ": ").concat(_v));
923
+ _context5.next = 72;
924
+ break;
925
+ case 45:
926
+ if (!(typeof _v === "boolean")) {
927
+ _context5.next = 49;
928
+ break;
929
+ }
930
+ fieldLines.push("".concat(_k, ": \"").concat(_v, "\""));
931
+ _context5.next = 72;
932
+ break;
933
+ case 49:
934
+ if (!(_v === null)) {
935
+ _context5.next = 53;
936
+ break;
937
+ }
938
+ fieldLines.push("".concat(_k, ": \"null\""));
939
+ _context5.next = 72;
940
+ break;
941
+ case 53:
942
+ if (!(_v === undefined)) {
943
+ _context5.next = 57;
944
+ break;
945
+ }
946
+ fieldLines.push("".concat(_k, ": \"undefined\""));
947
+ _context5.next = 72;
948
+ break;
949
+ case 57:
950
+ if (!(_typeof(_v) === "symbol")) {
951
+ _context5.next = 61;
952
+ break;
953
+ }
954
+ fieldLines.push("".concat(_k, ": \"").concat(_v.description || "Symbol.for()", "\""));
955
+ _context5.next = 72;
956
+ break;
957
+ case 61:
958
+ if (!isBytes(_v)) {
959
+ _context5.next = 71;
960
+ break;
961
+ }
962
+ _buffer2 = toBuffer(_v); // For inline data/body parts, binary fields get raw bytes
963
+ if (!isInline) {
964
+ _context5.next = 67;
965
+ break;
966
+ }
967
+ return _context5.abrupt("continue", 72);
968
+ case 67:
969
+ // For non-inline parts, we need to add raw bytes, not base64
970
+ // Store the binary field for later processing
971
+ binaryFields.push({
972
+ key: _k,
973
+ buffer: _buffer2
974
+ });
975
+ return _context5.abrupt("continue", 72);
976
+ case 69:
977
+ _context5.next = 72;
978
+ break;
979
+ case 71:
980
+ if (Array.isArray(_v)) {
981
+ if (_v.length === 0) {
982
+ fieldLines.push("".concat(_k, ": "));
983
+ } else {
984
+ _encodedItems2 = _v.map(function (item) {
985
+ return encodeArrayItem(item);
986
+ }).join(", ");
987
+ fieldLines.push("".concat(_k, ": ").concat(_encodedItems2));
988
+ }
989
+ } else if (isPojo(_v) && Object.keys(_v).length === 0) {
990
+ // Empty object - no content line needed, just ao-type
991
+ }
992
+ case 72:
993
+ _i11++;
994
+ _context5.next = 29;
995
+ break;
996
+ case 75:
997
+ // Check if this object only has empty collections
998
+ onlyEmptyCollections = Object.entries(value).every(function (_ref) {
999
+ var _ref2 = _slicedToArray(_ref, 2),
1000
+ k = _ref2[0],
1001
+ v = _ref2[1];
1002
+ var childPath = "".concat(bodyKey, "/").concat(k);
1003
+ if (sortedBodyKeys.includes(childPath)) return true;
1004
+ if (Array.isArray(v) && v.some(function (item) {
1005
+ return isPojo(item);
1006
+ })) return true;
1007
+ return Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0 || isBytes(v) && (v.length === 0 || v.byteLength === 0);
1008
+ }); // Special handling for inline body
1009
+ if (isInline) {
1010
+ // For inline: fields first, then ao-types, then content-disposition
1011
+ orderedLines = []; // First: field lines
1012
+ if (!onlyEmptyCollections) {
1013
+ _iterator4 = _createForOfIteratorHelper(fieldLines);
1014
+ try {
1015
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1016
+ line = _step4.value;
1017
+ orderedLines.push(line);
1018
+ }
1019
+ } catch (err) {
1020
+ _iterator4.e(err);
1021
+ } finally {
1022
+ _iterator4.f();
1023
+ }
1024
+ }
802
1025
 
803
- // Add the actual value
804
- _lines.push(String(fieldValue));
805
- bodyParts.push(new Blob([_lines.join("\r\n")]));
806
- console.log("[encode] Added non-binary field ".concat(_path, " to bodyParts"));
807
- return _context4.abrupt("continue", 131);
808
- case 94:
809
- // Handle nested paths
810
- _content = parts[_path];
811
- if (_content) {
812
- _context4.next = 98;
813
- break;
814
- }
815
- console.log("[encode] No content found for path: ".concat(_path));
816
- return _context4.abrupt("continue", 131);
817
- case 98:
818
- lines = [];
819
- binaryParts = [];
820
- isInlineKey = (_path === "data" || _path === "body") && !_path.includes("/");
821
- sortedKeys = Object.keys(_content).sort(); // Collect ao-types for this part
822
- partTypes = [];
823
- _iterator3 = _createForOfIteratorHelper(sortedKeys);
824
- try {
825
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
826
- _key4 = _step3.value;
827
- fullPath = _path ? "".concat(_path, "/").concat(_key4) : _key4;
828
- _type4 = types[fullPath];
829
- if (_type4) {
830
- partTypes.push("".concat(_key4, "=\"").concat(_type4, "\""));
831
- }
832
- }
833
- } catch (err) {
834
- _iterator3.e(err);
835
- } finally {
836
- _iterator3.f();
837
- }
838
- if (partTypes.length > 0) {
839
- lines.push("ao-types: ".concat(partTypes.sort().join(", ")));
840
- }
841
- if (isInlineKey) {
842
- lines.push("content-disposition: inline");
843
- } else {
844
- lines.push("content-disposition: form-data;name=\"".concat(_path, "\""));
845
- }
1026
+ // Then: ao-types
1027
+ if (objectTypes.length > 0) {
1028
+ orderedLines.push("ao-types: ".concat(objectTypes.sort().join(", ")));
1029
+ }
846
1030
 
847
- // Add content fields
848
- _iterator4 = _createForOfIteratorHelper(sortedKeys);
849
- _context4.prev = 108;
850
- _iterator4.s();
851
- case 110:
852
- if ((_step4 = _iterator4.n()).done) {
853
- _context4.next = 122;
854
- break;
855
- }
856
- _key5 = _step4.value;
857
- _value3 = _content[_key5];
858
- _fullPath = _path ? "".concat(_path, "/").concat(_key5) : _key5;
859
- _type5 = types[_fullPath];
860
- if (!(_type5 === "empty-message" || _type5 === "empty-list" || _type5 === "empty-binary")) {
861
- _context4.next = 117;
862
- break;
863
- }
864
- return _context4.abrupt("continue", 120);
865
- case 117:
866
- if (!((_value3 === "[]" || _value3 === "{}" || _value3 === "") && _type5 && _type5.startsWith("empty"))) {
867
- _context4.next = 119;
868
- break;
869
- }
870
- return _context4.abrupt("continue", 120);
871
- case 119:
872
- if (isBytes(_value3)) {
873
- binaryParts.push({
874
- key: _key5,
875
- value: _value3
876
- });
877
- } else if (_type5 === "atom" && typeof _value3 === "boolean") {
878
- lines.push("".concat(_key5, ": \"").concat(_value3, "\""));
879
- } else if (_typeof(_value3) === "symbol") {
880
- // Handle Symbol values
881
- symbolValue = _value3.description || "symbol";
882
- lines.push("".concat(_key5, ": ").concat(symbolValue));
883
- } else {
884
- lines.push("".concat(_key5, ": ").concat(_value3));
885
- }
886
- case 120:
887
- _context4.next = 110;
888
- break;
889
- case 122:
890
- _context4.next = 127;
891
- break;
892
- case 124:
893
- _context4.prev = 124;
894
- _context4.t4 = _context4["catch"](108);
895
- _iterator4.e(_context4.t4);
896
- case 127:
897
- _context4.prev = 127;
898
- _iterator4.f();
899
- return _context4.finish(127);
900
- case 130:
901
- if (lines.length >= 1 || binaryParts.length > 0) {
902
- if (binaryParts.length > 0) {
903
- allParts = []; // Add text headers first
904
- if (lines.length > 0) {
905
- allParts.push(lines.join("\r\n"));
906
- allParts.push("\r\n");
907
- }
1031
+ // Finally: content-disposition
1032
+ orderedLines.push("content-disposition: inline");
908
1033
 
909
- // Add binary data
910
- _iterator5 = _createForOfIteratorHelper(binaryParts);
911
- try {
912
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
913
- binaryPart = _step5.value;
914
- allParts.push("".concat(binaryPart.key, ": "));
915
- allParts.push(binaryPart.value);
916
- if (binaryParts.indexOf(binaryPart) < binaryParts.length - 1) {
917
- allParts.push("\r\n");
1034
+ // Check if this has binary fields
1035
+ _binaryFields = Object.entries(value).filter(function (_ref3) {
1036
+ var _ref4 = _slicedToArray(_ref3, 2),
1037
+ k = _ref4[0],
1038
+ v = _ref4[1];
1039
+ return isBytes(v) && !sortedBodyKeys.includes("".concat(bodyKey, "/").concat(k));
1040
+ }).map(function (_ref5) {
1041
+ var _ref6 = _slicedToArray(_ref5, 2),
1042
+ k = _ref6[0],
1043
+ v = _ref6[1];
1044
+ return {
1045
+ key: k,
1046
+ buffer: toBuffer(v)
1047
+ };
1048
+ });
1049
+ if (_binaryFields.length > 0) {
1050
+ // Build the parts
1051
+ _parts = []; // Add the text part
1052
+ _parts.push(Buffer.from(orderedLines.join("\r\n")));
1053
+
1054
+ // Add binary fields with raw bytes
1055
+ _iterator5 = _createForOfIteratorHelper(_binaryFields);
1056
+ try {
1057
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
1058
+ _step5$value = _step5.value, _key = _step5$value.key, _buffer3 = _step5$value.buffer;
1059
+ _parts.push(Buffer.from("\r\n".concat(_key, ": ")));
1060
+ _parts.push(_buffer3);
1061
+ }
1062
+
1063
+ // Add trailing \r\n for inline parts with binary
1064
+ } catch (err) {
1065
+ _iterator5.e(err);
1066
+ } finally {
1067
+ _iterator5.f();
1068
+ }
1069
+ _parts.push(Buffer.from("\r\n"));
1070
+ fullBody = Buffer.concat(_parts);
1071
+ bodyParts.push(new Blob([fullBody]));
1072
+ } else {
1073
+ orderedLines.push(""); // Add empty line for trailing \r\n
1074
+ bodyParts.push(new Blob([orderedLines.join("\r\n")]));
1075
+ }
1076
+ } else {
1077
+ // Normal handling (non-inline)
1078
+ // ao-types first if needed
1079
+ if (objectTypes.length > 0) {
1080
+ lines.unshift("ao-types: ".concat(objectTypes.sort().join(", ")));
1081
+ }
1082
+
1083
+ // Only add field lines if not all collections are empty
1084
+ if (!onlyEmptyCollections) {
1085
+ _iterator6 = _createForOfIteratorHelper(fieldLines);
1086
+ try {
1087
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1088
+ _line = _step6.value;
1089
+ lines.push(_line);
1090
+ }
1091
+ } catch (err) {
1092
+ _iterator6.e(err);
1093
+ } finally {
1094
+ _iterator6.f();
1095
+ }
1096
+ }
1097
+
1098
+ // Then handle binary fields with raw bytes if any
1099
+ if (binaryFields && binaryFields.length > 0) {
1100
+ // Create parts array for proper ordering
1101
+ _parts2 = []; // Add headers and text fields
1102
+ headerText = lines.join("\r\n") + "\r\n";
1103
+ _parts2.push(Buffer.from(headerText));
1104
+
1105
+ // Add binary fields with raw bytes
1106
+ _iterator7 = _createForOfIteratorHelper(binaryFields);
1107
+ try {
1108
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
1109
+ _step7$value = _step7.value, _key2 = _step7$value.key, _buffer4 = _step7$value.buffer;
1110
+ _parts2.push(Buffer.from("".concat(_key2, ": ")));
1111
+ _parts2.push(_buffer4);
1112
+ _parts2.push(Buffer.from("\r\n"));
1113
+ }
1114
+ } catch (err) {
1115
+ _iterator7.e(err);
1116
+ } finally {
1117
+ _iterator7.f();
1118
+ }
1119
+ _fullBody = Buffer.concat(_parts2);
1120
+ bodyParts.push(new Blob([_fullBody]));
1121
+ } else {
1122
+ lines.push("");
1123
+ bodyParts.push(new Blob([lines.join("\r\n")]));
1124
+ }
918
1125
  }
919
- }
920
- } catch (err) {
921
- _iterator5.e(err);
922
- } finally {
923
- _iterator5.f();
1126
+ _context5.next = 80;
1127
+ break;
1128
+ case 79:
1129
+ if (Array.isArray(value)) {
1130
+ // Array field - check if it's a mixed array or array of arrays
1131
+ hasObjects = value.some(function (item) {
1132
+ return isPojo(item);
1133
+ });
1134
+ hasArrays = value.some(function (item) {
1135
+ return Array.isArray(item);
1136
+ });
1137
+ nonObjectItems = value.map(function (item, index) {
1138
+ return {
1139
+ item: item,
1140
+ index: index + 1
1141
+ };
1142
+ }).filter(function (_ref7) {
1143
+ var item = _ref7.item;
1144
+ return !isPojo(item);
1145
+ });
1146
+ if (hasObjects && nonObjectItems.length > 0) {
1147
+ // Mixed array - only include non-object items
1148
+ _fieldLines = [];
1149
+ partTypes = [];
1150
+ _iterator8 = _createForOfIteratorHelper(nonObjectItems);
1151
+ try {
1152
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1153
+ _step8$value = _step8.value, item = _step8$value.item, index = _step8$value.index;
1154
+ if (typeof item === "number") {
1155
+ if (Number.isInteger(item)) {
1156
+ partTypes.push("".concat(index, "=\"integer\""));
1157
+ _fieldLines.push("".concat(index, ": ").concat(item));
1158
+ } else {
1159
+ partTypes.push("".concat(index, "=\"float\""));
1160
+ _fieldLines.push("".concat(index, ": ").concat(formatFloat(item)));
1161
+ }
1162
+ } else if (typeof item === "string") {
1163
+ _fieldLines.push("".concat(index, ": ").concat(item));
1164
+ } else if (item === null || item === undefined || _typeof(item) === "symbol" || typeof item === "boolean") {
1165
+ partTypes.push("".concat(index, "=\"atom\""));
1166
+ if (item === null) {
1167
+ _fieldLines.push("".concat(index, ": \"null\""));
1168
+ } else if (item === undefined) {
1169
+ _fieldLines.push("".concat(index, ": \"undefined\""));
1170
+ } else if (_typeof(item) === "symbol") {
1171
+ _fieldLines.push("".concat(index, ": \"").concat(item.description || "Symbol.for()", "\""));
1172
+ } else {
1173
+ _fieldLines.push("".concat(index, ": \"").concat(item, "\""));
1174
+ }
1175
+ } else if (isBytes(item)) {
1176
+ // Binary items in arrays need special handling
1177
+ _buffer5 = toBuffer(item);
1178
+ if (_buffer5.length === 0) {
1179
+ partTypes.push("".concat(index, "=\"empty-binary\""));
1180
+ }
1181
+ // For now, skip binary items in mixed arrays
1182
+ // They should be handled differently
1183
+ partTypes.push("".concat(index, "=\"binary\""));
1184
+ } else if (Array.isArray(item)) {
1185
+ partTypes.push("".concat(index, "=\"list\""));
1186
+ _encodedItems3 = item.map(function (subItem) {
1187
+ return encodeArrayItem(subItem);
1188
+ }).join(", ");
1189
+ _fieldLines.push("".concat(index, ": ").concat(_encodedItems3));
1190
+ }
1191
+ }
1192
+
1193
+ // For inline arrays, use different order
1194
+ } catch (err) {
1195
+ _iterator8.e(err);
1196
+ } finally {
1197
+ _iterator8.f();
1198
+ }
1199
+ if (isInline) {
1200
+ console.log("[encode] Reordering for inline array:", {
1201
+ bodyKey: bodyKey,
1202
+ fieldLines: _fieldLines,
1203
+ partTypes: partTypes
1204
+ });
1205
+
1206
+ // Rebuild in correct order: field lines, ao-types, content-disposition
1207
+ _orderedLines = []; // First: field lines
1208
+ _iterator9 = _createForOfIteratorHelper(_fieldLines);
1209
+ try {
1210
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1211
+ _line2 = _step9.value;
1212
+ _orderedLines.push(_line2);
1213
+ }
1214
+
1215
+ // Then: ao-types
1216
+ } catch (err) {
1217
+ _iterator9.e(err);
1218
+ } finally {
1219
+ _iterator9.f();
1220
+ }
1221
+ if (partTypes.length > 0) {
1222
+ _orderedLines.push("ao-types: ".concat(partTypes.sort(function (a, b) {
1223
+ var aNum = parseInt(a.split("=")[0]);
1224
+ var bNum = parseInt(b.split("=")[0]);
1225
+ return aNum - bNum;
1226
+ }).join(", ")));
1227
+ }
1228
+
1229
+ // Finally: content-disposition (from lines[0])
1230
+ _orderedLines.push(lines[0]);
1231
+ _orderedLines.push("");
1232
+ console.log("[encode] Ordered lines:", _orderedLines);
1233
+ bodyParts.push(new Blob([_orderedLines.join("\r\n")]));
1234
+ } else {
1235
+ // Normal order for non-inline parts
1236
+ if (partTypes.length > 0) {
1237
+ lines.unshift("ao-types: ".concat(partTypes.sort(function (a, b) {
1238
+ var aNum = parseInt(a.split("=")[0]);
1239
+ var bNum = parseInt(b.split("=")[0]);
1240
+ return aNum - bNum;
1241
+ }).join(", ")));
1242
+ }
1243
+ _iterator10 = _createForOfIteratorHelper(_fieldLines);
1244
+ try {
1245
+ for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
1246
+ _line3 = _step10.value;
1247
+ lines.push(_line3);
1248
+ }
1249
+ } catch (err) {
1250
+ _iterator10.e(err);
1251
+ } finally {
1252
+ _iterator10.f();
1253
+ }
1254
+ lines.push("");
1255
+ bodyParts.push(new Blob([lines.join("\r\n")]));
1256
+ }
1257
+ } else if (hasArrays || !hasObjects && value.length > 0) {
1258
+ // Array of arrays or simple array - use indexed format
1259
+ _fieldLines2 = [];
1260
+ _partTypes = [];
1261
+ value.forEach(function (item, idx) {
1262
+ var index = idx + 1;
1263
+ if (Array.isArray(item)) {
1264
+ if (item.length === 0) {
1265
+ _partTypes.push("".concat(index, "=\"empty-list\""));
1266
+ } else {
1267
+ _partTypes.push("".concat(index, "=\"list\""));
1268
+ var _encodedItems4 = item.map(function (subItem) {
1269
+ return encodeArrayItem(subItem);
1270
+ }).join(", ");
1271
+ _fieldLines2.push("".concat(index, ": ").concat(_encodedItems4));
1272
+ }
1273
+ } else if (typeof item === "number") {
1274
+ if (Number.isInteger(item)) {
1275
+ _partTypes.push("".concat(index, "=\"integer\""));
1276
+ _fieldLines2.push("".concat(index, ": ").concat(item));
1277
+ } else {
1278
+ _partTypes.push("".concat(index, "=\"float\""));
1279
+ _fieldLines2.push("".concat(index, ": ").concat(formatFloat(item)));
1280
+ }
1281
+ } else if (typeof item === "string") {
1282
+ if (item.length === 0) {
1283
+ _partTypes.push("".concat(index, "=\"empty-binary\""));
1284
+ }
1285
+ _fieldLines2.push("".concat(index, ": ").concat(item));
1286
+ } else if (item === null || item === undefined || _typeof(item) === "symbol" || typeof item === "boolean") {
1287
+ _partTypes.push("".concat(index, "=\"atom\""));
1288
+ if (item === null) {
1289
+ _fieldLines2.push("".concat(index, ": \"null\""));
1290
+ } else if (item === undefined) {
1291
+ _fieldLines2.push("".concat(index, ": \"undefined\""));
1292
+ } else if (_typeof(item) === "symbol") {
1293
+ _fieldLines2.push("".concat(index, ": \"").concat(item.description || "Symbol.for()", "\""));
1294
+ } else {
1295
+ _fieldLines2.push("".concat(index, ": \"").concat(item, "\""));
1296
+ }
1297
+ } else if (isBytes(item)) {
1298
+ var _buffer6 = toBuffer(item);
1299
+ if (_buffer6.length === 0) {
1300
+ _partTypes.push("".concat(index, "=\"empty-binary\""));
1301
+ } else {
1302
+ _partTypes.push("".concat(index, "=\"binary\""));
1303
+ }
1304
+ // For indexed format, we also can't include raw bytes inline
1305
+ // This is a limitation of the format
1306
+ }
1307
+ });
1308
+
1309
+ // For inline arrays, use different order
1310
+ if (isInline) {
1311
+ console.log("[encode] Reordering for inline array - indexed format");
1312
+ _orderedLines2 = []; // First: field lines
1313
+ _iterator11 = _createForOfIteratorHelper(_fieldLines2);
1314
+ try {
1315
+ for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
1316
+ _line4 = _step11.value;
1317
+ _orderedLines2.push(_line4);
1318
+ }
1319
+
1320
+ // Then: ao-types
1321
+ } catch (err) {
1322
+ _iterator11.e(err);
1323
+ } finally {
1324
+ _iterator11.f();
1325
+ }
1326
+ if (_partTypes.length > 0) {
1327
+ _orderedLines2.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
+
1334
+ // Finally: content-disposition
1335
+ _orderedLines2.push(lines[0]);
1336
+ _orderedLines2.push("");
1337
+ console.log("[encode] Final ordered lines:", _orderedLines2);
1338
+ bodyParts.push(new Blob([_orderedLines2.join("\r\n")]));
1339
+ } else {
1340
+ // Normal order for non-inline parts
1341
+ if (_partTypes.length > 0) {
1342
+ console.log("[encode] Adding ao-types to beginning of lines array");
1343
+ lines.unshift("ao-types: ".concat(_partTypes.sort(function (a, b) {
1344
+ var aNum = parseInt(a.split("=")[0]);
1345
+ var bNum = parseInt(b.split("=")[0]);
1346
+ return aNum - bNum;
1347
+ }).join(", ")));
1348
+ }
1349
+ console.log("[encode] Adding field lines:", _fieldLines2);
1350
+ _iterator12 = _createForOfIteratorHelper(_fieldLines2);
1351
+ try {
1352
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
1353
+ _line5 = _step12.value;
1354
+ lines.push(_line5);
1355
+ }
1356
+ } catch (err) {
1357
+ _iterator12.e(err);
1358
+ } finally {
1359
+ _iterator12.f();
1360
+ }
1361
+ console.log("[encode] Final lines before blob:", lines);
1362
+ lines.push("");
1363
+ bodyParts.push(new Blob([lines.join("\r\n")]));
1364
+ }
1365
+ } else if (!hasObjects && value.length === 0) {
1366
+ // Empty array
1367
+ _fieldName = pathParts[pathParts.length - 1];
1368
+ _partTypes2 = ["".concat(_fieldName, "=\"empty-list\"")];
1369
+ lines.unshift("ao-types: ".concat(_partTypes2.join(", ")));
1370
+ lines.push("");
1371
+ bodyParts.push(new Blob([lines.join("\r\n")]));
1372
+ }
1373
+ } else if (typeof value === "string") {
1374
+ // String with newlines or too long
1375
+ lines.push("");
1376
+ lines.push(value);
1377
+ lines.push("");
1378
+ bodyParts.push(new Blob([lines.join("\r\n")]));
1379
+ }
1380
+ case 80:
1381
+ case "end":
1382
+ return _context5.stop();
924
1383
  }
925
- bodyParts.push(new Blob(allParts));
926
- } else {
927
- bodyParts.push(new Blob([lines.join("\r\n")]));
928
- }
1384
+ }, _loop5);
1385
+ });
1386
+ _iterator3.s();
1387
+ case 85:
1388
+ if ((_step3 = _iterator3.n()).done) {
1389
+ _context6.next = 92;
1390
+ break;
929
1391
  }
930
- case 131:
931
- _context4.next = 68;
932
- break;
933
- case 133:
934
- _context4.next = 138;
935
- break;
936
- case 135:
937
- _context4.prev = 135;
938
- _context4.t5 = _context4["catch"](66);
939
- _iterator.e(_context4.t5);
940
- case 138:
941
- _context4.prev = 138;
942
- _iterator.f();
943
- return _context4.finish(138);
944
- case 141:
945
- console.log("[encode] Total bodyParts: ".concat(bodyParts.length));
946
-
947
- // Create boundary based on parts content
948
- partsForBoundary = [];
949
- _iterator2 = _createForOfIteratorHelper(bodyParts);
950
- _context4.prev = 144;
951
- _iterator2.s();
952
- case 146:
953
- if ((_step2 = _iterator2.n()).done) {
954
- _context4.next = 154;
1392
+ return _context6.delegateYield(_loop5(), "t2", 87);
1393
+ case 87:
1394
+ _ret = _context6.t2;
1395
+ if (!(_ret === 0)) {
1396
+ _context6.next = 90;
955
1397
  break;
956
1398
  }
957
- part = _step2.value;
958
- _context4.next = 150;
959
- return part.text();
960
- case 150:
961
- partContent = _context4.sent;
962
- partsForBoundary.push(partContent);
963
- case 152:
964
- _context4.next = 146;
1399
+ return _context6.abrupt("continue", 90);
1400
+ case 90:
1401
+ _context6.next = 85;
965
1402
  break;
966
- case 154:
967
- _context4.next = 159;
1403
+ case 92:
1404
+ _context6.next = 97;
968
1405
  break;
969
- case 156:
970
- _context4.prev = 156;
971
- _context4.t6 = _context4["catch"](144);
972
- _iterator2.e(_context4.t6);
973
- case 159:
974
- _context4.prev = 159;
975
- _iterator2.f();
976
- return _context4.finish(159);
977
- case 162:
978
- allPartsContent = partsForBoundary.join("");
979
- console.log("[encode] All parts content length: ".concat(allPartsContent.length));
980
- allPartsBuffer = Buffer.from(allPartsContent);
981
- _context4.next = 167;
982
- return sha256(allPartsBuffer.buffer.slice(allPartsBuffer.byteOffset, allPartsBuffer.byteOffset + allPartsBuffer.byteLength));
983
- case 167:
984
- hashResult = _context4.sent;
985
- boundary = _base64url["default"].encode(Buffer.from(hashResult)); // Create final multipart body
1406
+ case 94:
1407
+ _context6.prev = 94;
1408
+ _context6.t3 = _context6["catch"](82);
1409
+ _iterator3.e(_context6.t3);
1410
+ case 97:
1411
+ _context6.prev = 97;
1412
+ _iterator3.f();
1413
+ return _context6.finish(97);
1414
+ case 100:
1415
+ // Special case: add data/body as a separate form-data part if needed
1416
+ if (hasSpecialDataBody && obj.data && obj.data.body && isBytes(obj.data.body)) {
1417
+ buffer = toBuffer(obj.data.body);
1418
+ specialPart = ["content-disposition: form-data;name=\"data/body\"", "", ""].join("\r\n");
1419
+ bodyParts.push(new Blob([specialPart, buffer]));
1420
+ }
1421
+
1422
+ // Calculate boundary from content
1423
+ _context6.next = 103;
1424
+ return Promise.all(bodyParts.map(function (part) {
1425
+ return part.text();
1426
+ }));
1427
+ case 103:
1428
+ partsContent = _context6.sent;
1429
+ allContent = partsContent.join("");
1430
+ _context6.next = 107;
1431
+ return sha256(new TextEncoder().encode(allContent));
1432
+ case 107:
1433
+ boundaryHash = _context6.sent;
1434
+ boundary = _base64url["default"].encode(Buffer.from(boundaryHash)); // Assemble final multipart body - NO newlines after each part except the last
986
1435
  finalParts = [];
987
1436
  for (i = 0; i < bodyParts.length; i++) {
988
- finalParts.push("--".concat(boundary));
989
- finalParts.push("\r\n");
990
- finalParts.push(bodyParts[i]);
991
- if (i < bodyParts.length - 1) {
992
- finalParts.push("\r\n");
1437
+ if (i === 0) {
1438
+ finalParts.push(new Blob(["--".concat(boundary, "\r\n")]));
1439
+ } else {
1440
+ finalParts.push(new Blob(["\r\n--".concat(boundary, "\r\n")]));
993
1441
  }
1442
+ finalParts.push(bodyParts[i]);
994
1443
  }
995
- finalParts.push("\r\n--".concat(boundary, "--"));
1444
+ finalParts.push(new Blob(["\r\n--".concat(boundary, "--")]));
996
1445
  headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
997
- body = new Blob(finalParts);
998
- _context4.next = 176;
1446
+ body = new Blob(finalParts); // Calculate content digest
1447
+ _context6.next = 116;
999
1448
  return body.arrayBuffer();
1000
- case 176:
1001
- finalContent = _context4.sent;
1002
- _context4.next = 179;
1449
+ case 116:
1450
+ finalContent = _context6.sent;
1451
+ _context6.next = 119;
1003
1452
  return sha256(finalContent);
1004
- case 179:
1005
- contentDigest = _context4.sent;
1453
+ case 119:
1454
+ contentDigest = _context6.sent;
1006
1455
  base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
1007
1456
  headers["content-digest"] = "sha-256=:".concat(base64, ":");
1008
1457
  headers["content-length"] = String(finalContent.byteLength);
1009
1458
  console.log("[encode] FINAL - headers:", headers, "body:", body);
1010
- return _context4.abrupt("return", {
1459
+
1460
+ // Debug: decode the multipart body to verify structure
1461
+ _context6.next = 126;
1462
+ return body.text();
1463
+ case 126:
1464
+ bodyText = _context6.sent;
1465
+ console.log("\n[encode] DEBUG - Full body text:");
1466
+ console.log(bodyText);
1467
+
1468
+ // Parse multipart body
1469
+ boundaryMatch = headers["content-type"].match(/boundary="([^"]+)"/);
1470
+ if (boundaryMatch) {
1471
+ debugBoundary = boundaryMatch[1];
1472
+ parts = bodyText.split("--".concat(debugBoundary));
1473
+ console.log("\n[encode] DEBUG - Multipart parts:");
1474
+ parts.forEach(function (part, idx) {
1475
+ console.log("Part ".concat(idx, ":"), JSON.stringify(part));
1476
+ });
1477
+
1478
+ // Show the actual content part
1479
+ if (parts[1]) {
1480
+ console.log("\n[encode] DEBUG - Content part structure:");
1481
+ lines = parts[1].trim().split("\r\n");
1482
+ lines.forEach(function (line, idx) {
1483
+ if (line.includes("\0")) {
1484
+ console.log("Line ".concat(idx, ": \"").concat(line.substring(0, line.indexOf("\0")), "\" + [").concat(line.length - line.indexOf("\0"), " bytes]"));
1485
+ } else {
1486
+ console.log("Line ".concat(idx, ": \"").concat(line, "\""));
1487
+ }
1488
+ });
1489
+ }
1490
+ }
1491
+ return _context6.abrupt("return", {
1011
1492
  headers: headers,
1012
1493
  body: body
1013
1494
  });
1014
- case 185:
1015
- console.log("[encode] FINAL - headers:", headers, "body:", undefined);
1016
- return _context4.abrupt("return", {
1017
- headers: headers,
1018
- body: undefined
1019
- });
1020
- case 187:
1495
+ case 132:
1021
1496
  case "end":
1022
- return _context4.stop();
1497
+ return _context6.stop();
1023
1498
  }
1024
- }, _callee4, null, [[66, 135, 138, 141], [108, 124, 127, 130], [144, 156, 159, 162]]);
1499
+ }, _callee3, null, [[82, 94, 97, 100]]);
1025
1500
  }));
1026
- return _encodeMultipart.apply(this, arguments);
1501
+ return _encode.apply(this, arguments);
1027
1502
  }
1028
- function enc(_x4) {
1503
+ function enc(_x3) {
1029
1504
  return _enc.apply(this, arguments);
1030
1505
  }
1031
1506
  function _enc() {
1032
- _enc = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(fields) {
1033
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1034
- while (1) switch (_context5.prev = _context5.next) {
1507
+ _enc = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(fields) {
1508
+ return _regeneratorRuntime().wrap(function _callee4$(_context7) {
1509
+ while (1) switch (_context7.prev = _context7.next) {
1035
1510
  case 0:
1036
- _context5.next = 2;
1511
+ _context7.next = 2;
1037
1512
  return encode(fields);
1038
1513
  case 2:
1039
- return _context5.abrupt("return", _context5.sent);
1514
+ return _context7.abrupt("return", _context7.sent);
1040
1515
  case 3:
1041
1516
  case "end":
1042
- return _context5.stop();
1517
+ return _context7.stop();
1043
1518
  }
1044
- }, _callee5);
1519
+ }, _callee4);
1045
1520
  }));
1046
1521
  return _enc.apply(this, arguments);
1047
1522
  }