wao 0.26.2 → 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.
package/cjs/encode.js ADDED
@@ -0,0 +1,1522 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.enc = enc;
7
+ var _base64url = _interopRequireDefault(require("base64url"));
8
+ var _fastSha = require("fast-sha256");
9
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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; }
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; } } }; }
16
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
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."); }
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; } }
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; }
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; } }
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); }); }; }
24
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
25
+ function isBytes(value) {
26
+ return value instanceof ArrayBuffer || ArrayBuffer.isView(value) || Buffer.isBuffer(value) || value && _typeof(value) === "object" && value.type === "Buffer" && Array.isArray(value.data);
27
+ }
28
+ function isPojo(value) {
29
+ return !isBytes(value) && !Array.isArray(value) && !(value instanceof Blob) && _typeof(value) === "object" && value !== null;
30
+ }
31
+ var MAX_HEADER_LENGTH = 4096;
32
+ function hasNewline(_x) {
33
+ return _hasNewline.apply(this, arguments);
34
+ }
35
+ function _hasNewline() {
36
+ _hasNewline = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(value) {
37
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
38
+ while (1) switch (_context.prev = _context.next) {
39
+ case 0:
40
+ if (!(typeof value === "string")) {
41
+ _context.next = 2;
42
+ break;
43
+ }
44
+ return _context.abrupt("return", value.includes("\n"));
45
+ case 2:
46
+ if (!(value instanceof Blob)) {
47
+ _context.next = 7;
48
+ break;
49
+ }
50
+ _context.next = 5;
51
+ return value.text();
52
+ case 5:
53
+ value = _context.sent;
54
+ return _context.abrupt("return", value.includes("\n"));
55
+ case 7:
56
+ if (!isBytes(value)) {
57
+ _context.next = 9;
58
+ break;
59
+ }
60
+ return _context.abrupt("return", Buffer.from(value).includes("\n"));
61
+ case 9:
62
+ return _context.abrupt("return", false);
63
+ case 10:
64
+ case "end":
65
+ return _context.stop();
66
+ }
67
+ }, _callee);
68
+ }));
69
+ return _hasNewline.apply(this, arguments);
70
+ }
71
+ function sha256(_x2) {
72
+ return _sha.apply(this, arguments);
73
+ }
74
+ function _sha() {
75
+ _sha = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(data) {
76
+ var uint8Array, hashResult;
77
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
78
+ while (1) switch (_context2.prev = _context2.next) {
79
+ case 0:
80
+ if (!(data instanceof ArrayBuffer)) {
81
+ _context2.next = 4;
82
+ break;
83
+ }
84
+ uint8Array = new Uint8Array(data);
85
+ _context2.next = 13;
86
+ break;
87
+ case 4:
88
+ if (!(data instanceof Uint8Array)) {
89
+ _context2.next = 8;
90
+ break;
91
+ }
92
+ uint8Array = data;
93
+ _context2.next = 13;
94
+ break;
95
+ case 8:
96
+ if (!ArrayBuffer.isView(data)) {
97
+ _context2.next = 12;
98
+ break;
99
+ }
100
+ uint8Array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
101
+ _context2.next = 13;
102
+ break;
103
+ case 12:
104
+ throw new Error("sha256 expects ArrayBuffer or ArrayBufferView");
105
+ case 13:
106
+ hashResult = (0, _fastSha.hash)(uint8Array);
107
+ return _context2.abrupt("return", hashResult.buffer.slice(hashResult.byteOffset, hashResult.byteOffset + hashResult.byteLength));
108
+ case 15:
109
+ case "end":
110
+ return _context2.stop();
111
+ }
112
+ }, _callee2);
113
+ }));
114
+ return _sha.apply(this, arguments);
115
+ }
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, "\\\\\\\"\\\"");
158
+ } else {
159
+ return "\\\"".concat(String(nestedItem), "\\\"");
160
+ }
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)) {
204
+ var hasObjects = value.some(function (item) {
205
+ return isPojo(item);
206
+ });
207
+ var hasNonObjects = value.some(function (item) {
208
+ return !isPojo(item);
209
+ });
210
+ if (hasObjects) {
211
+ // Each object in array gets its own key
212
+ value.forEach(function (item, index) {
213
+ if (isPojo(item)) {
214
+ nestedPaths.push("".concat(fullPath, "/").concat(index + 1));
215
+ }
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;
231
+ } else {
232
+ // Non-empty objects are processed recursively
233
+ nestedPaths.push(fullPath);
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;
239
+ }
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
+ }
265
+ }
266
+ } catch (err) {
267
+ _iterator.e(err);
268
+ } finally {
269
+ _iterator.f();
270
+ }
271
+ if (isPojo(nestedObj)) {
272
+ traverse(nestedObj, nestedPath);
273
+ }
274
+ }
275
+ }
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
+ }
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
+ }
347
+ }
348
+ function encode() {
349
+ return _encode.apply(this, arguments);
350
+ }
351
+ function _encode() {
352
+ _encode = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
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,
376
+ objKeys,
377
+ fieldName,
378
+ binaryData,
379
+ _headers2,
380
+ _bodyBuffer,
381
+ _bodyArrayBuffer,
382
+ _contentDigest2,
383
+ _base2,
384
+ headers,
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,
412
+ contentDigest,
413
+ base64,
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) {
422
+ case 0:
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));
450
+ if (!(Object.keys(obj).length === 0)) {
451
+ _context6.next = 7;
452
+ break;
453
+ }
454
+ return _context6.abrupt("return", {
455
+ headers: {},
456
+ body: undefined
457
+ });
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
+ }));
471
+ });
472
+ if (!(hasBodyBinary && allOthersSimpleOrEmptyBinary)) {
473
+ _context6.next = 34;
474
+ break;
475
+ }
476
+ console.log("[encode] Special case: body with binary + simple fields");
477
+ // Special case: body with binary + other simple fields
478
+ _headers = {};
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;
484
+ break;
485
+ }
486
+ _Object$entries6$_i = _slicedToArray(_Object$entries6[_i7], 2), key = _Object$entries6$_i[0], value = _Object$entries6$_i[1];
487
+ if (!(key === "body")) {
488
+ _context6.next = 19;
489
+ break;
490
+ }
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) {
521
+ return isPojo(item);
522
+ })) {
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\""));
531
+ }
532
+ case 21:
533
+ _i7++;
534
+ _context6.next = 15;
535
+ break;
536
+ case 24:
537
+ // Add ao-types if needed
538
+ if (_headerTypes.length > 0) {
539
+ _headers["ao-types"] = _headerTypes.sort().join(", ");
540
+ }
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;
549
+ _base = _base64url["default"].toBase64(_base64url["default"].encode(_contentDigest));
550
+ _headers["content-digest"] = "sha-256=:".concat(_base, ":");
551
+ console.log("[encode] FINAL (body with binary) - headers:", _headers, "body:", obj.body);
552
+ return _context6.abrupt("return", {
553
+ headers: _headers,
554
+ body: obj.body
555
+ });
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;
561
+ break;
562
+ }
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;
578
+ }
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;
656
+ break;
657
+ }
658
+ return _context6.delegateYield(_loop3(), "t0", 56);
659
+ case 56:
660
+ _i8++;
661
+ _context6.next = 54;
662
+ break;
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;
693
+ break;
694
+ }
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;
703
+ break;
704
+ }
705
+ if (headerTypes.length > 0) {
706
+ headers["ao-types"] = headerTypes.sort().join(", ");
707
+ }
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;
738
+ break;
739
+ }
740
+ // Treat as header-only encoding
741
+ if (headerTypes.length > 0) {
742
+ headers["ao-types"] = headerTypes.sort().join(", ");
743
+ }
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(", ");
762
+
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
+ }
771
+ }
772
+ }
773
+
774
+ // Add ao-types header if needed
775
+ if (headerTypes.length > 0) {
776
+ headers["ao-types"] = headerTypes.sort().join(", ");
777
+ }
778
+
779
+ // Create multipart body parts
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));
803
+
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));
826
+
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
+ }
908
+
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
+ }
1025
+
1026
+ // Then: ao-types
1027
+ if (objectTypes.length > 0) {
1028
+ orderedLines.push("ao-types: ".concat(objectTypes.sort().join(", ")));
1029
+ }
1030
+
1031
+ // Finally: content-disposition
1032
+ orderedLines.push("content-disposition: inline");
1033
+
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
+ }
1125
+ }
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();
1383
+ }
1384
+ }, _loop5);
1385
+ });
1386
+ _iterator3.s();
1387
+ case 85:
1388
+ if ((_step3 = _iterator3.n()).done) {
1389
+ _context6.next = 92;
1390
+ break;
1391
+ }
1392
+ return _context6.delegateYield(_loop5(), "t2", 87);
1393
+ case 87:
1394
+ _ret = _context6.t2;
1395
+ if (!(_ret === 0)) {
1396
+ _context6.next = 90;
1397
+ break;
1398
+ }
1399
+ return _context6.abrupt("continue", 90);
1400
+ case 90:
1401
+ _context6.next = 85;
1402
+ break;
1403
+ case 92:
1404
+ _context6.next = 97;
1405
+ break;
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
1435
+ finalParts = [];
1436
+ for (i = 0; i < bodyParts.length; i++) {
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")]));
1441
+ }
1442
+ finalParts.push(bodyParts[i]);
1443
+ }
1444
+ finalParts.push(new Blob(["\r\n--".concat(boundary, "--")]));
1445
+ headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
1446
+ body = new Blob(finalParts); // Calculate content digest
1447
+ _context6.next = 116;
1448
+ return body.arrayBuffer();
1449
+ case 116:
1450
+ finalContent = _context6.sent;
1451
+ _context6.next = 119;
1452
+ return sha256(finalContent);
1453
+ case 119:
1454
+ contentDigest = _context6.sent;
1455
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
1456
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
1457
+ headers["content-length"] = String(finalContent.byteLength);
1458
+ console.log("[encode] FINAL - headers:", headers, "body:", body);
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", {
1492
+ headers: headers,
1493
+ body: body
1494
+ });
1495
+ case 132:
1496
+ case "end":
1497
+ return _context6.stop();
1498
+ }
1499
+ }, _callee3, null, [[82, 94, 97, 100]]);
1500
+ }));
1501
+ return _encode.apply(this, arguments);
1502
+ }
1503
+ function enc(_x3) {
1504
+ return _enc.apply(this, arguments);
1505
+ }
1506
+ function _enc() {
1507
+ _enc = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(fields) {
1508
+ return _regeneratorRuntime().wrap(function _callee4$(_context7) {
1509
+ while (1) switch (_context7.prev = _context7.next) {
1510
+ case 0:
1511
+ _context7.next = 2;
1512
+ return encode(fields);
1513
+ case 2:
1514
+ return _context7.abrupt("return", _context7.sent);
1515
+ case 3:
1516
+ case "end":
1517
+ return _context7.stop();
1518
+ }
1519
+ }, _callee4);
1520
+ }));
1521
+ return _enc.apply(this, arguments);
1522
+ }