wao 0.32.2 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/encode.js DELETED
@@ -1,1338 +0,0 @@
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 _encodeUtils = require("./encode-utils.js");
9
- var _encodeArrayItem = _interopRequireDefault(require("./encode-array-item.js"));
10
- var _collectBodyKeys = _interopRequireDefault(require("./collect-body-keys.js"));
11
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
12
- function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
13
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
14
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
15
- function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
16
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
17
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
18
- 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; }
19
- 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; } }
20
- function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
21
- function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
22
- function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
23
- var MAX_HEADER_LENGTH = 4096;
24
-
25
- // Step 1: Process and normalize input values (handle symbols, nested objects/arrays)
26
- function processInputValues(obj) {
27
- // Currently this is a no-op, but will be used for input validation/normalization
28
- return obj;
29
- }
30
-
31
- // Step 2: Handle empty object case
32
- function handleEmptyObject(obj) {
33
- if (Object.keys(obj).length === 0) {
34
- return {
35
- headers: {},
36
- body: undefined
37
- };
38
- }
39
- return null;
40
- }
41
-
42
- // Step 3: Handle single field with empty binary
43
- function handleSingleEmptyBinaryField(obj) {
44
- var objKeys = Object.keys(obj);
45
- if (objKeys.length === 1) {
46
- var fieldName = objKeys[0];
47
- var fieldValue = obj[fieldName];
48
- if ((0, _encodeUtils.isBytes)(fieldValue) && (fieldValue.length === 0 || fieldValue.byteLength === 0)) {
49
- var headers = {};
50
- headers["ao-types"] = "".concat(fieldName.toLowerCase(), "=\"empty-binary\"");
51
- return {
52
- headers: headers,
53
- body: undefined
54
- };
55
- }
56
- }
57
- return null;
58
- }
59
-
60
- // Step 4: Handle single field with binary data
61
- function handleSingleBinaryField(_x) {
62
- return _handleSingleBinaryField.apply(this, arguments);
63
- } // Step 5: Handle single field with primitive value (string/number/boolean/null/undefined/symbol)
64
- function _handleSingleBinaryField() {
65
- _handleSingleBinaryField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(obj) {
66
- var hasBodyBinary, otherFields, headers, bodyBuffer, bodyArrayBuffer, contentDigest, base64;
67
- return _regeneratorRuntime().wrap(function _callee$(_context) {
68
- while (1) switch (_context.prev = _context.next) {
69
- case 0:
70
- hasBodyBinary = obj.body && (0, _encodeUtils.isBytes)(obj.body);
71
- otherFields = Object.keys(obj).filter(function (k) {
72
- return k !== "body";
73
- });
74
- if (!(hasBodyBinary && otherFields.length === 0)) {
75
- _context.next = 12;
76
- break;
77
- }
78
- headers = {};
79
- bodyBuffer = (0, _encodeUtils.toBuffer)(obj.body);
80
- bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
81
- _context.next = 8;
82
- return (0, _encodeUtils.sha256)(bodyArrayBuffer);
83
- case 8:
84
- contentDigest = _context.sent;
85
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
86
- headers["content-digest"] = "sha-256=:".concat(base64, ":");
87
- return _context.abrupt("return", {
88
- headers: headers,
89
- body: obj.body
90
- });
91
- case 12:
92
- return _context.abrupt("return", null);
93
- case 13:
94
- case "end":
95
- return _context.stop();
96
- }
97
- }, _callee);
98
- }));
99
- return _handleSingleBinaryField.apply(this, arguments);
100
- }
101
- function handleSinglePrimitiveField(_x2) {
102
- return _handleSinglePrimitiveField.apply(this, arguments);
103
- } // Step 6a: Handle single field with non-empty binary (not body field)
104
- function _handleSinglePrimitiveField() {
105
- _handleSinglePrimitiveField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(obj) {
106
- var objKeys, fieldName, fieldValue, headers, bodyContent, encoder, encoded, contentDigest, base64, aoType;
107
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
108
- while (1) switch (_context2.prev = _context2.next) {
109
- case 0:
110
- objKeys = Object.keys(obj);
111
- if (!(objKeys.length === 1)) {
112
- _context2.next = 18;
113
- break;
114
- }
115
- fieldName = objKeys[0];
116
- fieldValue = obj[fieldName];
117
- if (!((fieldName === "data" || fieldName === "body") && (typeof fieldValue === "string" || typeof fieldValue === "boolean" || typeof fieldValue === "number" || fieldValue === null || fieldValue === undefined || _typeof(fieldValue) === "symbol"))) {
118
- _context2.next = 18;
119
- break;
120
- }
121
- headers = {};
122
- bodyContent = (0, _encodeUtils.encodePrimitiveContent)(fieldValue);
123
- encoder = new TextEncoder();
124
- encoded = encoder.encode(bodyContent);
125
- _context2.next = 11;
126
- return (0, _encodeUtils.sha256)(encoded.buffer);
127
- case 11:
128
- contentDigest = _context2.sent;
129
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
130
- headers["content-digest"] = "sha-256=:".concat(base64, ":");
131
- aoType = (0, _encodeUtils.getAoType)(fieldValue);
132
- if (aoType === "atom" || aoType === "integer" || aoType === "float") {
133
- headers["ao-types"] = "".concat(fieldName.toLowerCase(), "=\"").concat(aoType, "\"");
134
- }
135
- if (fieldName !== "body") {
136
- headers["inline-body-key"] = fieldName;
137
- }
138
- return _context2.abrupt("return", {
139
- headers: headers,
140
- body: bodyContent
141
- });
142
- case 18:
143
- return _context2.abrupt("return", null);
144
- case 19:
145
- case "end":
146
- return _context2.stop();
147
- }
148
- }, _callee2);
149
- }));
150
- return _handleSinglePrimitiveField.apply(this, arguments);
151
- }
152
- function handleSingleNonEmptyBinaryField(_x3) {
153
- return _handleSingleNonEmptyBinaryField.apply(this, arguments);
154
- } // Step 6: Handle single field with non-ASCII string
155
- function _handleSingleNonEmptyBinaryField() {
156
- _handleSingleNonEmptyBinaryField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(obj) {
157
- var objKeys, fieldName, fieldValue, headers, bodyBuffer, bodyArrayBuffer, contentDigest, base64;
158
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
159
- while (1) switch (_context3.prev = _context3.next) {
160
- case 0:
161
- objKeys = Object.keys(obj);
162
- if (!(objKeys.length === 1)) {
163
- _context3.next = 15;
164
- break;
165
- }
166
- fieldName = objKeys[0];
167
- fieldValue = obj[fieldName];
168
- if (!((0, _encodeUtils.isBytes)(fieldValue) && fieldValue.length > 0)) {
169
- _context3.next = 15;
170
- break;
171
- }
172
- headers = {};
173
- bodyBuffer = (0, _encodeUtils.toBuffer)(fieldValue);
174
- bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
175
- _context3.next = 10;
176
- return (0, _encodeUtils.sha256)(bodyArrayBuffer);
177
- case 10:
178
- contentDigest = _context3.sent;
179
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
180
- headers["content-digest"] = "sha-256=:".concat(base64, ":");
181
- if (fieldName !== "body") {
182
- headers["inline-body-key"] = fieldName;
183
- }
184
- return _context3.abrupt("return", {
185
- headers: headers,
186
- body: fieldValue
187
- });
188
- case 15:
189
- return _context3.abrupt("return", null);
190
- case 16:
191
- case "end":
192
- return _context3.stop();
193
- }
194
- }, _callee3);
195
- }));
196
- return _handleSingleNonEmptyBinaryField.apply(this, arguments);
197
- }
198
- function handleSingleNonAsciiStringField(_x4) {
199
- return _handleSingleNonAsciiStringField.apply(this, arguments);
200
- } // Step 7: Collect all keys that need to go in body
201
- function _handleSingleNonAsciiStringField() {
202
- _handleSingleNonAsciiStringField = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(obj) {
203
- var objKeys, fieldName, fieldValue, headers, encoder, encoded, contentDigest, base64;
204
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
205
- while (1) switch (_context4.prev = _context4.next) {
206
- case 0:
207
- objKeys = Object.keys(obj);
208
- if (!(objKeys.length === 1)) {
209
- _context4.next = 15;
210
- break;
211
- }
212
- fieldName = objKeys[0];
213
- fieldValue = obj[fieldName];
214
- if (!(typeof fieldValue === "string" && (0, _encodeUtils.hasNonAscii)(fieldValue))) {
215
- _context4.next = 15;
216
- break;
217
- }
218
- headers = {};
219
- encoder = new TextEncoder();
220
- encoded = encoder.encode(fieldValue);
221
- _context4.next = 10;
222
- return (0, _encodeUtils.sha256)(encoded.buffer);
223
- case 10:
224
- contentDigest = _context4.sent;
225
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
226
- headers["content-digest"] = "sha-256=:".concat(base64, ":");
227
- if (fieldName !== "body") {
228
- headers["inline-body-key"] = fieldName;
229
- }
230
- return _context4.abrupt("return", {
231
- headers: headers,
232
- body: fieldValue
233
- });
234
- case 15:
235
- return _context4.abrupt("return", null);
236
- case 16:
237
- case "end":
238
- return _context4.stop();
239
- }
240
- }, _callee4);
241
- }));
242
- return _handleSingleNonAsciiStringField.apply(this, arguments);
243
- }
244
- function collectBodyKeysStep(obj) {
245
- return (0, _collectBodyKeys["default"])(obj);
246
- }
247
-
248
- // Step 8: Process fields that can go in headers
249
- function processHeaderFields(obj, bodyKeys, headers, headerTypes) {
250
- var _loop = function _loop() {
251
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
252
- key = _Object$entries$_i[0],
253
- value = _Object$entries$_i[1];
254
- var needsBody = bodyKeys.includes(key) || bodyKeys.some(function (k) {
255
- return k.startsWith("".concat(key, "/"));
256
- });
257
- if (!needsBody) {
258
- if (value === null) {
259
- headers[key] = '"null"';
260
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
261
- } else if (value === undefined) {
262
- headers[key] = '"undefined"';
263
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
264
- } else if (typeof value === "boolean") {
265
- headers[key] = "\"".concat(value, "\"");
266
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
267
- } else if (_typeof(value) === "symbol") {
268
- headers[key] = "\"".concat(value.description || "Symbol.for()", "\"");
269
- headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
270
- } else if (typeof value === "number") {
271
- headers[key] = String(value);
272
- headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
273
- } else if (typeof value === "string") {
274
- if (value.length === 0) {
275
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
276
- } else if ((0, _encodeUtils.hasNonAscii)(value)) {
277
- return 1; // continue
278
- } else {
279
- headers[key] = value;
280
- }
281
- } else if (Array.isArray(value) && value.length === 0) {
282
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-list\""));
283
- } else if (Array.isArray(value) && !value.some(function (item) {
284
- return (0, _encodeUtils.isPojo)(item);
285
- })) {
286
- var hasNonAsciiItems = value.some(function (item) {
287
- return typeof item === "string" && (0, _encodeUtils.hasNonAscii)(item);
288
- });
289
- if (!hasNonAsciiItems) {
290
- var encodedItems = value.map(function (item) {
291
- return (0, _encodeArrayItem["default"])(item);
292
- }).join(", ");
293
- headers[key] = encodedItems;
294
- headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
295
- }
296
- } else if ((0, _encodeUtils.isBytes)(value) && (value.length === 0 || value.byteLength === 0)) {
297
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
298
- } else if ((0, _encodeUtils.isPojo)(value) && Object.keys(value).length === 0) {
299
- headerTypes.push("".concat(key.toLowerCase(), "=\"empty-message\""));
300
- }
301
- } else {
302
- // Fields that need body still get type annotations
303
- var aoType = (0, _encodeUtils.getAoType)(value);
304
- if (aoType) {
305
- headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(aoType, "\""));
306
- }
307
- }
308
- };
309
- for (var _i = 0, _Object$entries = Object.entries(obj); _i < _Object$entries.length; _i++) {
310
- if (_loop()) continue;
311
- }
312
-
313
- // Second pass for array type annotations
314
- var _loop2 = function _loop2() {
315
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
316
- key = _Object$entries2$_i[0],
317
- value = _Object$entries2$_i[1];
318
- if (Array.isArray(value)) {
319
- if (bodyKeys.includes(key) || bodyKeys.some(function (k) {
320
- return k.startsWith("".concat(key, "/"));
321
- })) {
322
- if (!headerTypes.some(function (t) {
323
- return t.startsWith("".concat(key.toLowerCase(), "="));
324
- })) {
325
- headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
326
- }
327
- }
328
- }
329
- };
330
- for (var _i2 = 0, _Object$entries2 = Object.entries(obj); _i2 < _Object$entries2.length; _i2++) {
331
- _loop2();
332
- }
333
- }
334
-
335
- // Step 9: Handle case where all body keys are empty binaries
336
- function handleAllEmptyBinaryBodyKeys(obj, bodyKeys, headers, headerTypes) {
337
- if (bodyKeys.length === 0) {
338
- if (headerTypes.length > 0) {
339
- headers["ao-types"] = headerTypes.sort().join(", ");
340
- }
341
- return {
342
- headers: headers,
343
- body: undefined
344
- };
345
- }
346
- var allBodyKeysAreEmptyBinaries = bodyKeys.every(function (key) {
347
- var value = (0, _encodeUtils.getValueByPath)(obj, key);
348
- return (0, _encodeUtils.isBytes)(value) && (value.length === 0 || value.byteLength === 0);
349
- });
350
- if (allBodyKeysAreEmptyBinaries) {
351
- if (headerTypes.length > 0) {
352
- headers["ao-types"] = headerTypes.sort().join(", ");
353
- }
354
- return {
355
- headers: headers,
356
- body: undefined
357
- };
358
- }
359
- return null;
360
- }
361
-
362
- // Step 10: Handle single body key optimization
363
- function handleSingleBodyKeyOptimization(_x5, _x6, _x7, _x8) {
364
- return _handleSingleBodyKeyOptimization.apply(this, arguments);
365
- } // Step 11: Sort body keys
366
- function _handleSingleBodyKeyOptimization() {
367
- _handleSingleBodyKeyOptimization = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(obj, bodyKeys, headers, headerTypes) {
368
- var singleKey, value, contentToHash, bodyContent, bodyBuffer, encoder, encoded, contentDigest, base64;
369
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
370
- while (1) switch (_context5.prev = _context5.next) {
371
- case 0:
372
- if (!(bodyKeys.length === 1)) {
373
- _context5.next = 14;
374
- break;
375
- }
376
- singleKey = bodyKeys[0];
377
- value = (0, _encodeUtils.getValueByPath)(obj, singleKey); // Apply optimization for binary data OR strings with newlines
378
- if (!((0, _encodeUtils.isBytes)(value) && value.length > 0 || typeof value === "string" && value.includes("\n"))) {
379
- _context5.next = 14;
380
- break;
381
- }
382
- bodyContent = value;
383
- if ((0, _encodeUtils.isBytes)(value)) {
384
- bodyBuffer = (0, _encodeUtils.toBuffer)(value);
385
- contentToHash = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
386
- } else {
387
- // For strings, encode to UTF-8 for hashing
388
- encoder = new TextEncoder();
389
- encoded = encoder.encode(value);
390
- contentToHash = encoded.buffer;
391
- bodyContent = value;
392
- }
393
- _context5.next = 8;
394
- return (0, _encodeUtils.sha256)(contentToHash);
395
- case 8:
396
- contentDigest = _context5.sent;
397
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
398
- headers["content-digest"] = "sha-256=:".concat(base64, ":");
399
- if (singleKey !== "body") {
400
- headers["inline-body-key"] = singleKey;
401
- }
402
- if (headerTypes.length > 0) {
403
- headers["ao-types"] = headerTypes.sort().join(", ");
404
- }
405
- return _context5.abrupt("return", {
406
- headers: headers,
407
- body: bodyContent
408
- });
409
- case 14:
410
- return _context5.abrupt("return", null);
411
- case 15:
412
- case "end":
413
- return _context5.stop();
414
- }
415
- }, _callee5);
416
- }));
417
- return _handleSingleBodyKeyOptimization.apply(this, arguments);
418
- }
419
- function sortBodyKeys(bodyKeys) {
420
- return bodyKeys.sort(function (a, b) {
421
- var aIsArrayElement = /\/\d+$/.test(a);
422
- var bIsArrayElement = /\/\d+$/.test(b);
423
- var aBase = a.split("/")[0];
424
- var bBase = b.split("/")[0];
425
- if (aBase === bBase) {
426
- if (!aIsArrayElement && bIsArrayElement) {
427
- return -1;
428
- }
429
- if (aIsArrayElement && !bIsArrayElement) {
430
- return 1;
431
- }
432
- if (aIsArrayElement && bIsArrayElement) {
433
- var aIndex = parseInt(a.split("/")[1]);
434
- var bIndex = parseInt(b.split("/")[1]);
435
- return aIndex - bIndex;
436
- }
437
- return a.localeCompare(b);
438
- }
439
- return a.localeCompare(b);
440
- });
441
- }
442
-
443
- // Step 12: Check for special data/body case
444
- function checkSpecialDataBodyCase(obj, sortedBodyKeys) {
445
- return sortedBodyKeys.includes("data") && sortedBodyKeys.includes("body") && obj.data && obj.data.body && (0, _encodeUtils.isBytes)(obj.data.body) && obj.body && obj.body.data && (0, _encodeUtils.isBytes)(obj.body.data);
446
- }
447
-
448
- // Step 13.2.2: Handle empty string in nested path
449
- function handleEmptyStringInNestedPath(bodyKey, value, pathParts) {
450
- if (typeof value === "string" && value === "" && pathParts.length > 1) {
451
- var lines = [];
452
- lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
453
- lines.push("");
454
- lines.push("");
455
- return new Blob([lines.join("\r\n")]);
456
- }
457
- return null;
458
- }
459
-
460
- // Step 13.2.3.2: Handle arrays with only empty elements
461
- function handleArrayWithOnlyEmptyElements(bodyKey, value, headers, sortedBodyKeys) {
462
- var fieldLines = [];
463
- var partTypes = [];
464
- value.forEach(function (item, idx) {
465
- var index = idx + 1;
466
- var itemType = (0, _encodeUtils.getAoType)(item);
467
- if (itemType) {
468
- partTypes.push("".concat(index, "=\"").concat(itemType, "\""));
469
- }
470
- });
471
- var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
472
- if (isInline) {
473
- var orderedLines = [];
474
- if (partTypes.length > 0) {
475
- orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
476
- }
477
- orderedLines.push("content-disposition: inline");
478
- orderedLines.push("");
479
- return new Blob([orderedLines.join("\r\n")]);
480
- } else {
481
- var _orderedLines = [];
482
- if (partTypes.length > 0) {
483
- _orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
484
- }
485
- _orderedLines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
486
- var isLastBodyPart = sortedBodyKeys.indexOf(bodyKey) === sortedBodyKeys.length - 1;
487
- var hasOnlyTypes = partTypes.length > 0 && fieldLines.length === 0;
488
- if (isLastBodyPart && hasOnlyTypes) {
489
- return new Blob([_orderedLines.join("\r\n")]);
490
- } else {
491
- _orderedLines.push("");
492
- return new Blob([_orderedLines.join("\r\n")]);
493
- }
494
- }
495
- }
496
-
497
- // Step 13.2.3.3: Build indices with own parts
498
- function buildIndicesWithOwnParts(bodyKey, sortedBodyKeys) {
499
- var indicesWithOwnParts = new Set();
500
- sortedBodyKeys.forEach(function (key) {
501
- if (key.startsWith(bodyKey + "/")) {
502
- var subPath = key.substring(bodyKey.length + 1);
503
- var match = subPath.match(/^(\d+)/);
504
- if (match) {
505
- indicesWithOwnParts.add(parseInt(match[1]));
506
- }
507
- }
508
- });
509
- return indicesWithOwnParts;
510
- }
511
-
512
- // Step 13.2.3.4: Process array items
513
- function processArrayItems(value, indicesWithOwnParts, hasNestedObjectParts, pathParts) {
514
- var fieldLines = [];
515
- var partTypes = [];
516
- if (hasNestedObjectParts) {
517
- value.forEach(function (item, idx) {
518
- var index = idx + 1;
519
- if (Array.isArray(item)) {
520
- partTypes.push("".concat(index, "=\"list\""));
521
- }
522
- });
523
- }
524
- value.forEach(function (item, idx) {
525
- var index = idx + 1;
526
- if (indicesWithOwnParts.has(index)) {
527
- return;
528
- }
529
- if (hasNestedObjectParts && Array.isArray(item) && item.some(function (subItem) {
530
- return (0, _encodeUtils.isPojo)(subItem);
531
- })) {
532
- return;
533
- }
534
- if (typeof item === "string" && item === "") {
535
- partTypes.push("".concat(index, "=\"empty-binary\""));
536
- } else if ((0, _encodeUtils.isPojo)(item) && Object.keys(item).length === 0) {
537
- partTypes.push("".concat(index, "=\"empty-message\""));
538
- } else if ((0, _encodeUtils.isPojo)(item)) {
539
- // Non-empty objects are handled elsewhere
540
- } else if (Array.isArray(item)) {
541
- if (item.length === 0) {
542
- partTypes.push("".concat(index, "=\"empty-list\""));
543
- } else {
544
- partTypes.push("".concat(index, "=\"list\""));
545
- var encodedItems = item.map(function (subItem) {
546
- if (typeof subItem === "number") {
547
- if (Number.isInteger(subItem)) {
548
- return "\"(ao-type-integer) ".concat(subItem, "\"");
549
- } else {
550
- return "\"(ao-type-float) ".concat((0, _encodeUtils.formatFloat)(subItem), "\"");
551
- }
552
- } else if (typeof subItem === "string") {
553
- return "\"".concat(subItem, "\"");
554
- } else if (subItem === null) {
555
- return "\"(ao-type-atom) \\\"null\\\"\"";
556
- } else if (subItem === undefined) {
557
- return "\"(ao-type-atom) \\\"undefined\\\"\"";
558
- } else if (_typeof(subItem) === "symbol") {
559
- var desc = subItem.description || "Symbol.for()";
560
- return "\"(ao-type-atom) \\\"".concat(desc, "\\\"\"");
561
- } else if (typeof subItem === "boolean") {
562
- return "\"(ao-type-atom) \\\"".concat(subItem, "\\\"\"");
563
- } else if (Array.isArray(subItem)) {
564
- return (0, _encodeArrayItem["default"])(subItem);
565
- } else if ((0, _encodeUtils.isBytes)(subItem)) {
566
- var buffer = (0, _encodeUtils.toBuffer)(subItem);
567
- if (buffer.length === 0 || buffer.byteLength === 0) {
568
- return "\"\"";
569
- }
570
- return "\"(ao-type-binary)\"";
571
- } else if ((0, _encodeUtils.isPojo)(subItem)) {
572
- var json = JSON.stringify(subItem);
573
- var escaped = json.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
574
- return "\"(ao-type-map) ".concat(escaped, "\"");
575
- } else {
576
- return "\"".concat(String(subItem), "\"");
577
- }
578
- }).join(", ");
579
- fieldLines.push("".concat(index, ": ").concat(encodedItems));
580
- }
581
- } else if (typeof item === "number") {
582
- if (Number.isInteger(item)) {
583
- partTypes.push("".concat(index, "=\"integer\""));
584
- fieldLines.push("".concat(index, ": ").concat(item));
585
- } else {
586
- partTypes.push("".concat(index, "=\"float\""));
587
- fieldLines.push("".concat(index, ": ").concat((0, _encodeUtils.formatFloat)(item)));
588
- }
589
- } else if (typeof item === "string") {
590
- fieldLines.push("".concat(index, ": ").concat(item));
591
- } else if (item === null || item === undefined || _typeof(item) === "symbol" || typeof item === "boolean") {
592
- partTypes.push("".concat(index, "=\"atom\""));
593
- if (item === null) {
594
- fieldLines.push("".concat(index, ": null"));
595
- } else if (item === undefined) {
596
- fieldLines.push("".concat(index, ": undefined"));
597
- } else if (_typeof(item) === "symbol") {
598
- var desc = item.description || "Symbol.for()";
599
- fieldLines.push("".concat(index, ": ").concat(desc));
600
- } else {
601
- fieldLines.push("".concat(index, ": ").concat(item));
602
- }
603
- } else if ((0, _encodeUtils.isBytes)(item)) {
604
- var buffer = (0, _encodeUtils.toBuffer)(item);
605
- if (buffer.length === 0) {
606
- partTypes.push("".concat(index, "=\"empty-binary\""));
607
- } else {
608
- partTypes.push("".concat(index, "=\"binary\""));
609
- }
610
- }
611
- });
612
- return {
613
- fieldLines: fieldLines,
614
- partTypes: partTypes
615
- };
616
- }
617
-
618
- // Step 13.2.3.5: Create array body part
619
- function createArrayBodyPart(bodyKey, fieldLines, partTypes, headers) {
620
- var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
621
- if (isInline) {
622
- var orderedLines = [];
623
- if (partTypes.length > 0) {
624
- orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
625
- }
626
- orderedLines.push("content-disposition: inline");
627
- if (fieldLines.length > 0) {
628
- orderedLines.push("");
629
- var _iterator = _createForOfIteratorHelper(fieldLines),
630
- _step;
631
- try {
632
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
633
- var line = _step.value;
634
- orderedLines.push(line);
635
- }
636
- } catch (err) {
637
- _iterator.e(err);
638
- } finally {
639
- _iterator.f();
640
- }
641
- }
642
- return new Blob([orderedLines.join("\r\n") + "\r\n"]);
643
- } else {
644
- var _orderedLines2 = [];
645
- if (partTypes.length > 0) {
646
- _orderedLines2.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
647
- }
648
- _orderedLines2.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
649
- var _iterator2 = _createForOfIteratorHelper(fieldLines),
650
- _step2;
651
- try {
652
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
653
- var _line = _step2.value;
654
- _orderedLines2.push(_line);
655
- }
656
- } catch (err) {
657
- _iterator2.e(err);
658
- } finally {
659
- _iterator2.f();
660
- }
661
- if (fieldLines.length > 0) {
662
- return new Blob([_orderedLines2.join("\r\n") + "\r\n"]);
663
- } else {
664
- return new Blob([_orderedLines2.join("\r\n")]);
665
- }
666
- }
667
- }
668
-
669
- // Step 13.2.3: Handle array values
670
- function handleArrayValue(bodyKey, value, headers, sortedBodyKeys, pathParts) {
671
- var arrayInfo = (0, _encodeUtils.analyzeArray)(value);
672
- if (arrayInfo.hasOnlyNonEmptyObjects) {
673
- return null;
674
- }
675
- if (arrayInfo.hasOnlyEmptyElements) {
676
- return handleArrayWithOnlyEmptyElements(bodyKey, value, headers, sortedBodyKeys);
677
- }
678
- var indicesWithOwnParts = buildIndicesWithOwnParts(bodyKey, sortedBodyKeys);
679
- var hasNestedObjectParts = sortedBodyKeys.some(function (key) {
680
- return key.startsWith(bodyKey + "/") && key.split("/").length > pathParts.length + 1;
681
- });
682
- var _processArrayItems = processArrayItems(value, indicesWithOwnParts, hasNestedObjectParts, pathParts),
683
- fieldLines = _processArrayItems.fieldLines,
684
- partTypes = _processArrayItems.partTypes;
685
- return createArrayBodyPart(bodyKey, fieldLines, partTypes, headers);
686
- }
687
-
688
- // Step 13.2.4.3: Process object fields
689
- function processObjectFields(value, bodyKey, sortedBodyKeys) {
690
- var objectTypes = [];
691
- var fieldLines = [];
692
- var binaryFields = [];
693
- var arrayTypes = [];
694
-
695
- // First collect array types
696
- for (var _i3 = 0, _Object$entries3 = Object.entries(value); _i3 < _Object$entries3.length; _i3++) {
697
- var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
698
- k = _Object$entries3$_i[0],
699
- v = _Object$entries3$_i[1];
700
- if (Array.isArray(v)) {
701
- arrayTypes.push("".concat(k.toLowerCase(), "=\"").concat(v.length === 0 ? "empty-list" : "list", "\""));
702
- }
703
- }
704
-
705
- // Then process other fields
706
- for (var _i4 = 0, _Object$entries4 = Object.entries(value); _i4 < _Object$entries4.length; _i4++) {
707
- var _Object$entries4$_i = _slicedToArray(_Object$entries4[_i4], 2),
708
- _k = _Object$entries4$_i[0],
709
- _v = _Object$entries4$_i[1];
710
- var childPath = "".concat(bodyKey, "/").concat(_k);
711
- if (sortedBodyKeys.includes(childPath)) {
712
- continue;
713
- }
714
- if (Array.isArray(_v) && _v.some(function (item) {
715
- return (0, _encodeUtils.isPojo)(item);
716
- })) {
717
- var hasOnlyEmpty = _v.every(function (item) {
718
- return (0, _encodeUtils.isEmpty)(item);
719
- });
720
- if (hasOnlyEmpty) {
721
- continue;
722
- }
723
- }
724
- if (Array.isArray(_v)) {
725
- // Type already added in arrayTypes
726
- } else if (_v === null || _v === undefined || _typeof(_v) === "symbol" || typeof _v === "boolean") {
727
- objectTypes.push("".concat(_k.toLowerCase(), "=\"atom\""));
728
- } else if (typeof _v === "number") {
729
- objectTypes.push("".concat(_k.toLowerCase(), "=\"").concat(Number.isInteger(_v) ? "integer" : "float", "\""));
730
- } else if (typeof _v === "string" && _v.length === 0) {
731
- objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-binary\""));
732
- } else if ((0, _encodeUtils.isBytes)(_v) && (_v.length === 0 || _v.byteLength === 0)) {
733
- objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-binary\""));
734
- } else if ((0, _encodeUtils.isPojo)(_v) && Object.keys(_v).length === 0) {
735
- objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-message\""));
736
- }
737
- if (typeof _v === "string") {
738
- if (_v.length === 0) {
739
- fieldLines.push("".concat(_k, ": "));
740
- } else {
741
- fieldLines.push("".concat(_k, ": ").concat(_v));
742
- }
743
- } else if (typeof _v === "number") {
744
- fieldLines.push("".concat(_k, ": ").concat(_v));
745
- } else if (typeof _v === "boolean") {
746
- fieldLines.push("".concat(_k, ": \"").concat(_v, "\""));
747
- } else if (_v === null) {
748
- fieldLines.push("".concat(_k, ": \"null\""));
749
- } else if (_v === undefined) {
750
- fieldLines.push("".concat(_k, ": \"undefined\""));
751
- } else if (_typeof(_v) === "symbol") {
752
- var desc = _v.description || "Symbol.for()";
753
- fieldLines.push("".concat(_k, ": \"").concat(desc, "\""));
754
- } else if ((0, _encodeUtils.isBytes)(_v)) {
755
- var buffer = (0, _encodeUtils.toBuffer)(_v);
756
- binaryFields.push({
757
- key: _k,
758
- buffer: buffer
759
- });
760
- } else if (Array.isArray(_v) && _v.length > 0) {
761
- var _childPath = "".concat(bodyKey, "/").concat(_k);
762
- if (!sortedBodyKeys.includes(_childPath)) {
763
- var hasObjects = _v.some(function (item) {
764
- return (0, _encodeUtils.isPojo)(item);
765
- });
766
- if (!hasObjects) {
767
- var encodedItems = _v.map(function (item) {
768
- return (0, _encodeArrayItem["default"])(item);
769
- }).join(", ");
770
- fieldLines.push("".concat(_k, ": ").concat(encodedItems));
771
- }
772
- }
773
- }
774
- }
775
- var allTypes = [].concat(arrayTypes, objectTypes);
776
- return {
777
- allTypes: allTypes,
778
- fieldLines: fieldLines,
779
- binaryFields: binaryFields
780
- };
781
- }
782
-
783
- // Step 13.2.4.5: Create object body part
784
- function createObjectBodyPart(bodyKey, value, allTypes, fieldLines, binaryFields, headers, sortedBodyKeys) {
785
- var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
786
- var lines = [];
787
- if (isInline) {
788
- var orderedLines = [];
789
-
790
- // For inline mode: fields first, then headers
791
- var _iterator3 = _createForOfIteratorHelper(fieldLines),
792
- _step3;
793
- try {
794
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
795
- var line = _step3.value;
796
- orderedLines.push(line);
797
- }
798
- } catch (err) {
799
- _iterator3.e(err);
800
- } finally {
801
- _iterator3.f();
802
- }
803
- if (allTypes.length > 0) {
804
- orderedLines.push("ao-types: ".concat(allTypes.sort().join(", ")));
805
- }
806
- orderedLines.push("content-disposition: inline");
807
- var binaryFieldsForInline = Object.entries(value).filter(function (_ref) {
808
- var _ref2 = _slicedToArray(_ref, 2),
809
- k = _ref2[0],
810
- v = _ref2[1];
811
- return (0, _encodeUtils.isBytes)(v) && !sortedBodyKeys.includes("".concat(bodyKey, "/").concat(k));
812
- }).map(function (_ref3) {
813
- var _ref4 = _slicedToArray(_ref3, 2),
814
- k = _ref4[0],
815
- v = _ref4[1];
816
- return {
817
- key: k,
818
- buffer: (0, _encodeUtils.toBuffer)(v)
819
- };
820
- });
821
- if (binaryFieldsForInline.length > 0) {
822
- var parts = [];
823
- // Join all text lines first
824
- parts.push(Buffer.from(orderedLines.join("\r\n")));
825
- // Then add binary fields
826
- var _iterator4 = _createForOfIteratorHelper(binaryFieldsForInline),
827
- _step4;
828
- try {
829
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
830
- var _step4$value = _step4.value,
831
- key = _step4$value.key,
832
- buffer = _step4$value.buffer;
833
- parts.push(Buffer.from("\r\n".concat(key, ": ")));
834
- parts.push(buffer);
835
- }
836
- } catch (err) {
837
- _iterator4.e(err);
838
- } finally {
839
- _iterator4.f();
840
- }
841
- parts.push(Buffer.from("\r\n"));
842
- var fullBody = Buffer.concat(parts);
843
- return new Blob([fullBody]);
844
- } else {
845
- return new Blob([orderedLines.join("\r\n") + "\r\n"]);
846
- }
847
- } else {
848
- // Non-inline mode remains the same
849
- var _orderedLines3 = [];
850
- if (allTypes.length > 0) {
851
- _orderedLines3.push("ao-types: ".concat(allTypes.sort().join(", ")));
852
- }
853
- _orderedLines3.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
854
- var hasBinaryFields = binaryFields && binaryFields.length > 0;
855
- if (hasBinaryFields || fieldLines.length === 0) {
856
- _orderedLines3.push("");
857
- }
858
- var _iterator5 = _createForOfIteratorHelper(fieldLines),
859
- _step5;
860
- try {
861
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
862
- var _line2 = _step5.value;
863
- _orderedLines3.push(_line2);
864
- }
865
- } catch (err) {
866
- _iterator5.e(err);
867
- } finally {
868
- _iterator5.f();
869
- }
870
- if (binaryFields && binaryFields.length > 0) {
871
- var _parts = [];
872
- var headerText = _orderedLines3.join("\r\n");
873
- _parts.push(Buffer.from(headerText));
874
- for (var i = 0; i < binaryFields.length; i++) {
875
- var _binaryFields$i = binaryFields[i],
876
- _key = _binaryFields$i.key,
877
- _buffer = _binaryFields$i.buffer;
878
- if (i > 0) {
879
- _parts.push(Buffer.from("\r\n"));
880
- }
881
- _parts.push(Buffer.from("".concat(_key, ": ")));
882
- _parts.push(_buffer);
883
- }
884
- _parts.push(Buffer.from("\r\n"));
885
- var _fullBody = Buffer.concat(_parts);
886
- return new Blob([_fullBody]);
887
- } else {
888
- if (fieldLines.length > 0) {
889
- return new Blob([_orderedLines3.join("\r\n") + "\r\n"]);
890
- } else {
891
- return new Blob([_orderedLines3.join("\r\n")]);
892
- }
893
- }
894
- }
895
- }
896
-
897
- // Step 13.2.4: Handle object values
898
- function handleObjectValue(obj, bodyKey, value, headers, sortedBodyKeys, pathParts, hasSpecialDataBody) {
899
- if (Object.keys(value).length === 0) {
900
- // Skip empty objects in certain contexts
901
- var parentPath = pathParts.slice(0, -1).join("/");
902
- var parentValue = parentPath ? (0, _encodeUtils.getValueByPath)(obj, parentPath) : obj;
903
- if (Array.isArray(parentValue)) {
904
- var parentArrayInfo = (0, _encodeUtils.analyzeArray)(parentValue);
905
- if (parentArrayInfo.hasObjects && (parentArrayInfo.hasEmptyStrings || parentArrayInfo.hasEmptyObjects)) {
906
- return null;
907
- }
908
- }
909
- return null;
910
- }
911
-
912
- // Skip special data/body case
913
- if (hasSpecialDataBody && bodyKey === "data" && Object.keys(value).length === 1 && value.body && (0, _encodeUtils.isBytes)(value.body)) {
914
- return null;
915
- }
916
- var _processObjectFields = processObjectFields(value, bodyKey, sortedBodyKeys),
917
- allTypes = _processObjectFields.allTypes,
918
- fieldLines = _processObjectFields.fieldLines,
919
- binaryFields = _processObjectFields.binaryFields;
920
-
921
- // Check if object should be skipped
922
- var hasOnlyEmptyCollections = Object.entries(value).every(function (_ref5) {
923
- var _ref6 = _slicedToArray(_ref5, 2),
924
- k = _ref6[0],
925
- v = _ref6[1];
926
- return (0, _encodeUtils.isEmpty)(v);
927
- });
928
- var hasArraysWithOnlyEmptyElements = Object.entries(value).some(function (_ref7) {
929
- var _ref8 = _slicedToArray(_ref7, 2),
930
- k = _ref8[0],
931
- v = _ref8[1];
932
- return Array.isArray(v) && v.length > 0 && v.every(function (item) {
933
- return (0, _encodeUtils.isEmpty)(item);
934
- });
935
- });
936
- var shouldSkipObject = Object.entries(value).every(function (_ref9) {
937
- var _ref10 = _slicedToArray(_ref9, 2),
938
- k = _ref10[0],
939
- v = _ref10[1];
940
- var childPath = "".concat(bodyKey, "/").concat(k);
941
- if (sortedBodyKeys.includes(childPath)) return true;
942
- if (Array.isArray(v) && v.some(function (item) {
943
- return (0, _encodeUtils.isPojo)(item);
944
- })) {
945
- var hasOnlyEmpty = v.every(function (item) {
946
- return (0, _encodeUtils.isEmpty)(item);
947
- });
948
- return hasOnlyEmpty || sortedBodyKeys.includes(childPath);
949
- }
950
- return false;
951
- });
952
- if (shouldSkipObject && !hasOnlyEmptyCollections && !hasArraysWithOnlyEmptyElements) {
953
- return null;
954
- }
955
- return createObjectBodyPart(bodyKey, value, allTypes, fieldLines, binaryFields, headers, sortedBodyKeys);
956
- }
957
-
958
- // Step 13.2.5: Handle primitive values
959
- function handlePrimitiveValue(bodyKey, value, headers) {
960
- var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
961
- var lines = [];
962
- if (isInline) {
963
- lines.push("content-disposition: inline");
964
- } else {
965
- lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
966
- }
967
- if (typeof value === "string") {
968
- lines.push("");
969
- lines.push(value);
970
- return new Blob([lines.join("\r\n")]);
971
- } else {
972
- var content = (0, _encodeUtils.encodePrimitiveContent)(value);
973
- lines.push("");
974
- lines.push(content);
975
- return new Blob([lines.join("\r\n")]);
976
- }
977
- }
978
-
979
- // Step 13.2.6: Handle binary values
980
- function handleBinaryValue(bodyKey, value, headers) {
981
- var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
982
- var lines = [];
983
- if (isInline) {
984
- lines.push("content-disposition: inline");
985
- } else {
986
- lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
987
- }
988
- var buffer = (0, _encodeUtils.toBuffer)(value);
989
- var headerText = lines.join("\r\n") + "\r\n\r\n";
990
- return new Blob([headerText, buffer]);
991
- }
992
-
993
- // Step 13.3: Handle special data/body case
994
- function handleSpecialDataBodyCase(obj, hasSpecialDataBody) {
995
- if (hasSpecialDataBody && obj.data && obj.data.body && (0, _encodeUtils.isBytes)(obj.data.body)) {
996
- var buffer = (0, _encodeUtils.toBuffer)(obj.data.body);
997
- var specialPart = ["content-disposition: form-data;name=\"data/body\"", "", ""].join("\r\n");
998
- return new Blob([specialPart, buffer]);
999
- }
1000
- return null;
1001
- }
1002
-
1003
- // Step 13: Build body parts for each body key
1004
- function buildBodyParts(obj, sortedBodyKeys, headers, hasSpecialDataBody) {
1005
- // Step 13.1: Initialize body parts collection
1006
- var bodyParts = [];
1007
-
1008
- // Step 13.2: Process each body key
1009
- var _iterator6 = _createForOfIteratorHelper(sortedBodyKeys),
1010
- _step6;
1011
- try {
1012
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1013
- var bodyKey = _step6.value;
1014
- // Step 13.2.1: Get value for current body key
1015
- var value = (0, _encodeUtils.getValueByPath)(obj, bodyKey);
1016
- var pathParts = bodyKey.split("/");
1017
-
1018
- // Step 13.2.2: Handle empty string in nested path
1019
- var emptyStringPart = handleEmptyStringInNestedPath(bodyKey, value, pathParts);
1020
- if (emptyStringPart) {
1021
- bodyParts.push(emptyStringPart);
1022
- continue;
1023
- }
1024
-
1025
- // Step 13.2.3: Handle array values
1026
- if (Array.isArray(value)) {
1027
- var arrayPart = handleArrayValue(bodyKey, value, headers, sortedBodyKeys, pathParts);
1028
- if (arrayPart) {
1029
- bodyParts.push(arrayPart);
1030
- }
1031
- continue;
1032
- }
1033
-
1034
- // Step 13.2.4: Handle object values
1035
- if ((0, _encodeUtils.isPojo)(value)) {
1036
- var objectPart = handleObjectValue(obj, bodyKey, value, headers, sortedBodyKeys, pathParts, hasSpecialDataBody);
1037
- if (objectPart) {
1038
- bodyParts.push(objectPart);
1039
- }
1040
- continue;
1041
- }
1042
-
1043
- // Step 13.2.5: Handle primitive values
1044
- if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" || value === null || value === undefined || _typeof(value) === "symbol") {
1045
- var primitivePart = handlePrimitiveValue(bodyKey, value, headers);
1046
- bodyParts.push(primitivePart);
1047
- continue;
1048
- }
1049
-
1050
- // Step 13.2.6: Handle binary values
1051
- if ((0, _encodeUtils.isBytes)(value)) {
1052
- var binaryPart = handleBinaryValue(bodyKey, value, headers);
1053
- bodyParts.push(binaryPart);
1054
- continue;
1055
- }
1056
- }
1057
-
1058
- // Step 13.3: Handle special data/body case
1059
- } catch (err) {
1060
- _iterator6.e(err);
1061
- } finally {
1062
- _iterator6.f();
1063
- }
1064
- var specialPart = handleSpecialDataBodyCase(obj, hasSpecialDataBody);
1065
- if (specialPart) {
1066
- bodyParts.push(specialPart);
1067
- }
1068
-
1069
- // Step 13.4: Return body parts
1070
- return bodyParts;
1071
- }
1072
-
1073
- // Step 14: Generate multipart boundary
1074
- function generateBoundary(_x9) {
1075
- return _generateBoundary.apply(this, arguments);
1076
- } // Step 15: Assemble final multipart body
1077
- function _generateBoundary() {
1078
- _generateBoundary = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(bodyParts) {
1079
- var partsContent, allContent, boundaryHash, boundary;
1080
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1081
- while (1) switch (_context6.prev = _context6.next) {
1082
- case 0:
1083
- _context6.next = 2;
1084
- return Promise.all(bodyParts.map(function (part) {
1085
- return part.text();
1086
- }));
1087
- case 2:
1088
- partsContent = _context6.sent;
1089
- allContent = partsContent.join("");
1090
- _context6.next = 6;
1091
- return (0, _encodeUtils.sha256)(new TextEncoder().encode(allContent));
1092
- case 6:
1093
- boundaryHash = _context6.sent;
1094
- boundary = _base64url["default"].encode(Buffer.from(boundaryHash));
1095
- return _context6.abrupt("return", boundary);
1096
- case 9:
1097
- case "end":
1098
- return _context6.stop();
1099
- }
1100
- }, _callee6);
1101
- }));
1102
- return _generateBoundary.apply(this, arguments);
1103
- }
1104
- function assembleMultipartBody(bodyParts, boundary) {
1105
- var finalParts = [];
1106
- for (var i = 0; i < bodyParts.length; i++) {
1107
- if (i === 0) {
1108
- finalParts.push(new Blob(["--".concat(boundary, "\r\n")]));
1109
- } else {
1110
- finalParts.push(new Blob(["\r\n--".concat(boundary, "\r\n")]));
1111
- }
1112
- finalParts.push(bodyParts[i]);
1113
- }
1114
- finalParts.push(new Blob(["\r\n--".concat(boundary, "--")]));
1115
- return new Blob(finalParts);
1116
- }
1117
-
1118
- // Step 16: Calculate content digest
1119
- function calculateContentDigest(_x10) {
1120
- return _calculateContentDigest.apply(this, arguments);
1121
- } // Step 17: Set final headers (content-type, content-length)
1122
- function _calculateContentDigest() {
1123
- _calculateContentDigest = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(body) {
1124
- var finalContent, contentDigest, base64;
1125
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1126
- while (1) switch (_context7.prev = _context7.next) {
1127
- case 0:
1128
- _context7.next = 2;
1129
- return body.arrayBuffer();
1130
- case 2:
1131
- finalContent = _context7.sent;
1132
- if (!(finalContent.byteLength > 0)) {
1133
- _context7.next = 9;
1134
- break;
1135
- }
1136
- _context7.next = 6;
1137
- return (0, _encodeUtils.sha256)(finalContent);
1138
- case 6:
1139
- contentDigest = _context7.sent;
1140
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
1141
- return _context7.abrupt("return", {
1142
- digest: base64,
1143
- byteLength: finalContent.byteLength
1144
- });
1145
- case 9:
1146
- return _context7.abrupt("return", {
1147
- digest: null,
1148
- byteLength: finalContent.byteLength
1149
- });
1150
- case 10:
1151
- case "end":
1152
- return _context7.stop();
1153
- }
1154
- }, _callee7);
1155
- }));
1156
- return _calculateContentDigest.apply(this, arguments);
1157
- }
1158
- function setFinalHeaders(headers, boundary, contentDigest, byteLength) {
1159
- headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
1160
- if (contentDigest) {
1161
- headers["content-digest"] = "sha-256=:".concat(contentDigest, ":");
1162
- }
1163
- headers["content-length"] = String(byteLength);
1164
- }
1165
- function enc() {
1166
- return _enc.apply(this, arguments);
1167
- }
1168
- function _enc() {
1169
- _enc = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
1170
- var obj,
1171
- processedObj,
1172
- emptyResult,
1173
- emptyBinaryResult,
1174
- singleBinaryResult,
1175
- primitiveResult,
1176
- nonEmptyBinaryResult,
1177
- nonAsciiResult,
1178
- bodyKeys,
1179
- objKeys,
1180
- headers,
1181
- headerTypes,
1182
- emptyBinaryBodyResult,
1183
- singleBodyKeyResult,
1184
- sortedBodyKeys,
1185
- hasSpecialDataBody,
1186
- bodyValue,
1187
- bodyParts,
1188
- boundary,
1189
- body,
1190
- _yield$calculateConte,
1191
- contentDigest,
1192
- byteLength,
1193
- _args8 = arguments;
1194
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1195
- while (1) switch (_context8.prev = _context8.next) {
1196
- case 0:
1197
- obj = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : {};
1198
- // Step 1: Process and normalize input values
1199
- processedObj = processInputValues(obj); // Step 2: Handle empty object case
1200
- emptyResult = handleEmptyObject(processedObj);
1201
- if (!emptyResult) {
1202
- _context8.next = 5;
1203
- break;
1204
- }
1205
- return _context8.abrupt("return", emptyResult);
1206
- case 5:
1207
- // Step 3: Handle single field with empty binary
1208
- emptyBinaryResult = handleSingleEmptyBinaryField(processedObj);
1209
- if (!emptyBinaryResult) {
1210
- _context8.next = 8;
1211
- break;
1212
- }
1213
- return _context8.abrupt("return", emptyBinaryResult);
1214
- case 8:
1215
- _context8.next = 10;
1216
- return handleSingleBinaryField(processedObj);
1217
- case 10:
1218
- singleBinaryResult = _context8.sent;
1219
- if (!singleBinaryResult) {
1220
- _context8.next = 13;
1221
- break;
1222
- }
1223
- return _context8.abrupt("return", singleBinaryResult);
1224
- case 13:
1225
- _context8.next = 15;
1226
- return handleSinglePrimitiveField(processedObj);
1227
- case 15:
1228
- primitiveResult = _context8.sent;
1229
- if (!primitiveResult) {
1230
- _context8.next = 18;
1231
- break;
1232
- }
1233
- return _context8.abrupt("return", primitiveResult);
1234
- case 18:
1235
- _context8.next = 20;
1236
- return handleSingleNonEmptyBinaryField(processedObj);
1237
- case 20:
1238
- nonEmptyBinaryResult = _context8.sent;
1239
- if (!nonEmptyBinaryResult) {
1240
- _context8.next = 23;
1241
- break;
1242
- }
1243
- return _context8.abrupt("return", nonEmptyBinaryResult);
1244
- case 23:
1245
- _context8.next = 25;
1246
- return handleSingleNonAsciiStringField(processedObj);
1247
- case 25:
1248
- nonAsciiResult = _context8.sent;
1249
- if (!nonAsciiResult) {
1250
- _context8.next = 28;
1251
- break;
1252
- }
1253
- return _context8.abrupt("return", nonAsciiResult);
1254
- case 28:
1255
- // Step 7: Collect all keys that need to go in body
1256
- bodyKeys = collectBodyKeysStep(processedObj);
1257
- objKeys = Object.keys(obj);
1258
- headers = {};
1259
- headerTypes = []; // Step 8: Process fields that can go in headers
1260
- processHeaderFields(obj, bodyKeys, headers, headerTypes);
1261
-
1262
- // Step 9: Handle case where all body keys are empty binaries
1263
- emptyBinaryBodyResult = handleAllEmptyBinaryBodyKeys(obj, bodyKeys, headers, headerTypes);
1264
- if (!emptyBinaryBodyResult) {
1265
- _context8.next = 36;
1266
- break;
1267
- }
1268
- return _context8.abrupt("return", emptyBinaryBodyResult);
1269
- case 36:
1270
- _context8.next = 38;
1271
- return handleSingleBodyKeyOptimization(obj, bodyKeys, headers, headerTypes);
1272
- case 38:
1273
- singleBodyKeyResult = _context8.sent;
1274
- if (!singleBodyKeyResult) {
1275
- _context8.next = 41;
1276
- break;
1277
- }
1278
- return _context8.abrupt("return", singleBodyKeyResult);
1279
- case 41:
1280
- // Step 11: Sort body keys
1281
- sortedBodyKeys = sortBodyKeys(bodyKeys); // Step 12: Check for special data/body case
1282
- hasSpecialDataBody = checkSpecialDataBodyCase(obj, sortedBodyKeys); // Only add body-keys header if there are actual body keys
1283
- if (sortedBodyKeys.length > 0) {
1284
- headers["body-keys"] = sortedBodyKeys.map(function (k) {
1285
- return "\"".concat(k, "\"");
1286
- }).join(", ");
1287
- }
1288
-
1289
- // Special case: single body key named "body" containing an object
1290
- if (!hasSpecialDataBody && sortedBodyKeys.length === 1 && sortedBodyKeys[0] === "body") {
1291
- bodyValue = obj.body;
1292
- if ((0, _encodeUtils.isPojo)(bodyValue)) {
1293
- headers["inline-body-key"] = "body";
1294
- }
1295
- }
1296
- if (headerTypes.length > 0) {
1297
- headers["ao-types"] = headerTypes.sort().join(", ");
1298
- }
1299
-
1300
- // Step 13: Build body parts for each body key
1301
- bodyParts = buildBodyParts(obj, sortedBodyKeys, headers, hasSpecialDataBody); // If no body parts were created, return headers only
1302
- if (!(bodyParts.length === 0)) {
1303
- _context8.next = 49;
1304
- break;
1305
- }
1306
- return _context8.abrupt("return", {
1307
- headers: headers,
1308
- body: undefined
1309
- });
1310
- case 49:
1311
- _context8.next = 51;
1312
- return generateBoundary(bodyParts);
1313
- case 51:
1314
- boundary = _context8.sent;
1315
- // Step 15: Assemble final multipart body
1316
- body = assembleMultipartBody(bodyParts, boundary); // Step 16: Calculate content digest
1317
- _context8.next = 55;
1318
- return calculateContentDigest(body);
1319
- case 55:
1320
- _yield$calculateConte = _context8.sent;
1321
- contentDigest = _yield$calculateConte.digest;
1322
- byteLength = _yield$calculateConte.byteLength;
1323
- // Step 17: Set final headers (content-type, content-length)
1324
- setFinalHeaders(headers, boundary, contentDigest, byteLength);
1325
-
1326
- // Step 18: Return result
1327
- return _context8.abrupt("return", {
1328
- headers: headers,
1329
- body: body
1330
- });
1331
- case 60:
1332
- case "end":
1333
- return _context8.stop();
1334
- }
1335
- }, _callee8);
1336
- }));
1337
- return _enc.apply(this, arguments);
1338
- }