Remotely/Server/wwwroot/lib/msgpack/msgpack.js

2069 lines
75 KiB
JavaScript

(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["MessagePack"] = factory();
else
root["MessagePack"] = factory();
})(this, function() {
return /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"DecodeError": function() { return /* reexport */ DecodeError; },
"Decoder": function() { return /* reexport */ Decoder; },
"EXT_TIMESTAMP": function() { return /* reexport */ EXT_TIMESTAMP; },
"Encoder": function() { return /* reexport */ Encoder; },
"ExtData": function() { return /* reexport */ ExtData; },
"ExtensionCodec": function() { return /* reexport */ ExtensionCodec; },
"decode": function() { return /* reexport */ decode; },
"decodeArrayStream": function() { return /* reexport */ decodeArrayStream; },
"decodeAsync": function() { return /* reexport */ decodeAsync; },
"decodeMulti": function() { return /* reexport */ decodeMulti; },
"decodeMultiStream": function() { return /* reexport */ decodeMultiStream; },
"decodeStream": function() { return /* reexport */ decodeStream; },
"decodeTimestampExtension": function() { return /* reexport */ decodeTimestampExtension; },
"decodeTimestampToTimeSpec": function() { return /* reexport */ decodeTimestampToTimeSpec; },
"encode": function() { return /* reexport */ encode; },
"encodeDateToTimeSpec": function() { return /* reexport */ encodeDateToTimeSpec; },
"encodeTimeSpecToTimestamp": function() { return /* reexport */ encodeTimeSpecToTimestamp; },
"encodeTimestampExtension": function() { return /* reexport */ encodeTimestampExtension; }
});
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
;// CONCATENATED MODULE: ./src/utils/utf8.ts
var TEXT_ENCODING_AVAILABLE = (typeof process === "undefined" || undefined !== "never") &&
typeof TextEncoder !== "undefined" &&
typeof TextDecoder !== "undefined";
var STR_SIZE_MAX = 4294967295; // uint32_max
function utf8Count(str) {
var strLength = str.length;
var byteLength = 0;
var pos = 0;
while (pos < strLength) {
var value = str.charCodeAt(pos++);
if ((value & 0xffffff80) === 0) {
// 1-byte
byteLength++;
continue;
}
else if ((value & 0xfffff800) === 0) {
// 2-bytes
byteLength += 2;
}
else {
// handle surrogate pair
if (value >= 0xd800 && value <= 0xdbff) {
// high surrogate
if (pos < strLength) {
var extra = str.charCodeAt(pos);
if ((extra & 0xfc00) === 0xdc00) {
++pos;
value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
}
}
}
if ((value & 0xffff0000) === 0) {
// 3-byte
byteLength += 3;
}
else {
// 4-byte
byteLength += 4;
}
}
}
return byteLength;
}
function utf8EncodeJs(str, output, outputOffset) {
var strLength = str.length;
var offset = outputOffset;
var pos = 0;
while (pos < strLength) {
var value = str.charCodeAt(pos++);
if ((value & 0xffffff80) === 0) {
// 1-byte
output[offset++] = value;
continue;
}
else if ((value & 0xfffff800) === 0) {
// 2-bytes
output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
}
else {
// handle surrogate pair
if (value >= 0xd800 && value <= 0xdbff) {
// high surrogate
if (pos < strLength) {
var extra = str.charCodeAt(pos);
if ((extra & 0xfc00) === 0xdc00) {
++pos;
value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
}
}
}
if ((value & 0xffff0000) === 0) {
// 3-byte
output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
output[offset++] = ((value >> 6) & 0x3f) | 0x80;
}
else {
// 4-byte
output[offset++] = ((value >> 18) & 0x07) | 0xf0;
output[offset++] = ((value >> 12) & 0x3f) | 0x80;
output[offset++] = ((value >> 6) & 0x3f) | 0x80;
}
}
output[offset++] = (value & 0x3f) | 0x80;
}
}
var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
? STR_SIZE_MAX
: typeof process !== "undefined" && undefined !== "force"
? 200
: 0;
function utf8EncodeTEencode(str, output, outputOffset) {
output.set(sharedTextEncoder.encode(str), outputOffset);
}
function utf8EncodeTEencodeInto(str, output, outputOffset) {
sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
}
var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
var CHUNK_SIZE = 4096;
function utf8DecodeJs(bytes, inputOffset, byteLength) {
var offset = inputOffset;
var end = offset + byteLength;
var units = [];
var result = "";
while (offset < end) {
var byte1 = bytes[offset++];
if ((byte1 & 0x80) === 0) {
// 1 byte
units.push(byte1);
}
else if ((byte1 & 0xe0) === 0xc0) {
// 2 bytes
var byte2 = bytes[offset++] & 0x3f;
units.push(((byte1 & 0x1f) << 6) | byte2);
}
else if ((byte1 & 0xf0) === 0xe0) {
// 3 bytes
var byte2 = bytes[offset++] & 0x3f;
var byte3 = bytes[offset++] & 0x3f;
units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
}
else if ((byte1 & 0xf8) === 0xf0) {
// 4 bytes
var byte2 = bytes[offset++] & 0x3f;
var byte3 = bytes[offset++] & 0x3f;
var byte4 = bytes[offset++] & 0x3f;
var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
if (unit > 0xffff) {
unit -= 0x10000;
units.push(((unit >>> 10) & 0x3ff) | 0xd800);
unit = 0xdc00 | (unit & 0x3ff);
}
units.push(unit);
}
else {
units.push(byte1);
}
if (units.length >= CHUNK_SIZE) {
result += String.fromCharCode.apply(String, __spreadArray([], __read(units)));
units.length = 0;
}
}
if (units.length > 0) {
result += String.fromCharCode.apply(String, __spreadArray([], __read(units)));
}
return result;
}
var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
? STR_SIZE_MAX
: typeof process !== "undefined" && undefined !== "force"
? 200
: 0;
function utf8DecodeTD(bytes, inputOffset, byteLength) {
var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
return sharedTextDecoder.decode(stringBytes);
}
;// CONCATENATED MODULE: ./src/ExtData.ts
/**
* ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
*/
var ExtData = /** @class */ (function () {
function ExtData(type, data) {
this.type = type;
this.data = data;
}
return ExtData;
}());
;// CONCATENATED MODULE: ./src/utils/int.ts
// DataView extension to handle int64 / uint64,
// where the actual range is 53-bits integer (a.k.a. safe integer)
function setUint64(view, offset, value) {
var high = value / 4294967296;
var low = value; // high bits are truncated by DataView
view.setUint32(offset, high);
view.setUint32(offset + 4, low);
}
function setInt64(view, offset, value) {
var high = Math.floor(value / 4294967296);
var low = value; // high bits are truncated by DataView
view.setUint32(offset, high);
view.setUint32(offset + 4, low);
}
function getInt64(view, offset) {
var high = view.getInt32(offset);
var low = view.getUint32(offset + 4);
return high * 4294967296 + low;
}
function getUint64(view, offset) {
var high = view.getUint32(offset);
var low = view.getUint32(offset + 4);
return high * 4294967296 + low;
}
;// CONCATENATED MODULE: ./src/timestamp.ts
// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
var EXT_TIMESTAMP = -1;
var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
function encodeTimeSpecToTimestamp(_a) {
var sec = _a.sec, nsec = _a.nsec;
if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
// Here sec >= 0 && nsec >= 0
if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
// timestamp 32 = { sec32 (unsigned) }
var rv = new Uint8Array(4);
var view = new DataView(rv.buffer);
view.setUint32(0, sec);
return rv;
}
else {
// timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
var secHigh = sec / 0x100000000;
var secLow = sec & 0xffffffff;
var rv = new Uint8Array(8);
var view = new DataView(rv.buffer);
// nsec30 | secHigh2
view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
// secLow32
view.setUint32(4, secLow);
return rv;
}
}
else {
// timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
var rv = new Uint8Array(12);
var view = new DataView(rv.buffer);
view.setUint32(0, nsec);
setInt64(view, 4, sec);
return rv;
}
}
function encodeDateToTimeSpec(date) {
var msec = date.getTime();
var sec = Math.floor(msec / 1e3);
var nsec = (msec - sec * 1e3) * 1e6;
// Normalizes { sec, nsec } to ensure nsec is unsigned.
var nsecInSec = Math.floor(nsec / 1e9);
return {
sec: sec + nsecInSec,
nsec: nsec - nsecInSec * 1e9,
};
}
function encodeTimestampExtension(object) {
if (object instanceof Date) {
var timeSpec = encodeDateToTimeSpec(object);
return encodeTimeSpecToTimestamp(timeSpec);
}
else {
return null;
}
}
function decodeTimestampToTimeSpec(data) {
var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
// data may be 32, 64, or 96 bits
switch (data.byteLength) {
case 4: {
// timestamp 32 = { sec32 }
var sec = view.getUint32(0);
var nsec = 0;
return { sec: sec, nsec: nsec };
}
case 8: {
// timestamp 64 = { nsec30, sec34 }
var nsec30AndSecHigh2 = view.getUint32(0);
var secLow32 = view.getUint32(4);
var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
var nsec = nsec30AndSecHigh2 >>> 2;
return { sec: sec, nsec: nsec };
}
case 12: {
// timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
var sec = getInt64(view, 4);
var nsec = view.getUint32(0);
return { sec: sec, nsec: nsec };
}
default:
throw new Error("Unrecognized data size for timestamp: " + data.length);
}
}
function decodeTimestampExtension(data) {
var timeSpec = decodeTimestampToTimeSpec(data);
return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
}
var timestampExtension = {
type: EXT_TIMESTAMP,
encode: encodeTimestampExtension,
decode: decodeTimestampExtension,
};
;// CONCATENATED MODULE: ./src/ExtensionCodec.ts
// ExtensionCodec to handle MessagePack extensions
var ExtensionCodec = /** @class */ (function () {
function ExtensionCodec() {
// built-in extensions
this.builtInEncoders = [];
this.builtInDecoders = [];
// custom extensions
this.encoders = [];
this.decoders = [];
this.register(timestampExtension);
}
ExtensionCodec.prototype.register = function (_a) {
var type = _a.type, encode = _a.encode, decode = _a.decode;
if (type >= 0) {
// custom extensions
this.encoders[type] = encode;
this.decoders[type] = decode;
}
else {
// built-in extensions
var index = 1 + type;
this.builtInEncoders[index] = encode;
this.builtInDecoders[index] = decode;
}
};
ExtensionCodec.prototype.tryToEncode = function (object, context) {
// built-in extensions
for (var i = 0; i < this.builtInEncoders.length; i++) {
var encodeExt = this.builtInEncoders[i];
if (encodeExt != null) {
var data = encodeExt(object, context);
if (data != null) {
var type = -1 - i;
return new ExtData(type, data);
}
}
}
// custom extensions
for (var i = 0; i < this.encoders.length; i++) {
var encodeExt = this.encoders[i];
if (encodeExt != null) {
var data = encodeExt(object, context);
if (data != null) {
var type = i;
return new ExtData(type, data);
}
}
}
if (object instanceof ExtData) {
// to keep ExtData as is
return object;
}
return null;
};
ExtensionCodec.prototype.decode = function (data, type, context) {
var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
if (decodeExt) {
return decodeExt(data, type, context);
}
else {
// decode() does not fail, returns ExtData instead.
return new ExtData(type, data);
}
};
ExtensionCodec.defaultCodec = new ExtensionCodec();
return ExtensionCodec;
}());
;// CONCATENATED MODULE: ./src/utils/typedArrays.ts
function ensureUint8Array(buffer) {
if (buffer instanceof Uint8Array) {
return buffer;
}
else if (ArrayBuffer.isView(buffer)) {
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
else if (buffer instanceof ArrayBuffer) {
return new Uint8Array(buffer);
}
else {
// ArrayLike<number>
return Uint8Array.from(buffer);
}
}
function createDataView(buffer) {
if (buffer instanceof ArrayBuffer) {
return new DataView(buffer);
}
var bufferView = ensureUint8Array(buffer);
return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
}
;// CONCATENATED MODULE: ./src/Encoder.ts
var DEFAULT_MAX_DEPTH = 100;
var DEFAULT_INITIAL_BUFFER_SIZE = 2048;
var Encoder = /** @class */ (function () {
function Encoder(extensionCodec, context, maxDepth, initialBufferSize, sortKeys, forceFloat32, ignoreUndefined, forceIntegerToFloat) {
if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }
if (context === void 0) { context = undefined; }
if (maxDepth === void 0) { maxDepth = DEFAULT_MAX_DEPTH; }
if (initialBufferSize === void 0) { initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE; }
if (sortKeys === void 0) { sortKeys = false; }
if (forceFloat32 === void 0) { forceFloat32 = false; }
if (ignoreUndefined === void 0) { ignoreUndefined = false; }
if (forceIntegerToFloat === void 0) { forceIntegerToFloat = false; }
this.extensionCodec = extensionCodec;
this.context = context;
this.maxDepth = maxDepth;
this.initialBufferSize = initialBufferSize;
this.sortKeys = sortKeys;
this.forceFloat32 = forceFloat32;
this.ignoreUndefined = ignoreUndefined;
this.forceIntegerToFloat = forceIntegerToFloat;
this.pos = 0;
this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
this.bytes = new Uint8Array(this.view.buffer);
}
Encoder.prototype.getUint8Array = function () {
return this.bytes.subarray(0, this.pos);
};
Encoder.prototype.reinitializeState = function () {
this.pos = 0;
};
Encoder.prototype.encode = function (object) {
this.reinitializeState();
this.doEncode(object, 1);
return this.getUint8Array();
};
Encoder.prototype.doEncode = function (object, depth) {
if (depth > this.maxDepth) {
throw new Error("Too deep objects in depth " + depth);
}
if (object == null) {
this.encodeNil();
}
else if (typeof object === "boolean") {
this.encodeBoolean(object);
}
else if (typeof object === "number") {
this.encodeNumber(object);
}
else if (typeof object === "string") {
this.encodeString(object);
}
else {
this.encodeObject(object, depth);
}
};
Encoder.prototype.ensureBufferSizeToWrite = function (sizeToWrite) {
var requiredSize = this.pos + sizeToWrite;
if (this.view.byteLength < requiredSize) {
this.resizeBuffer(requiredSize * 2);
}
};
Encoder.prototype.resizeBuffer = function (newSize) {
var newBuffer = new ArrayBuffer(newSize);
var newBytes = new Uint8Array(newBuffer);
var newView = new DataView(newBuffer);
newBytes.set(this.bytes);
this.view = newView;
this.bytes = newBytes;
};
Encoder.prototype.encodeNil = function () {
this.writeU8(0xc0);
};
Encoder.prototype.encodeBoolean = function (object) {
if (object === false) {
this.writeU8(0xc2);
}
else {
this.writeU8(0xc3);
}
};
Encoder.prototype.encodeNumber = function (object) {
if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {
if (object >= 0) {
if (object < 0x80) {
// positive fixint
this.writeU8(object);
}
else if (object < 0x100) {
// uint 8
this.writeU8(0xcc);
this.writeU8(object);
}
else if (object < 0x10000) {
// uint 16
this.writeU8(0xcd);
this.writeU16(object);
}
else if (object < 0x100000000) {
// uint 32
this.writeU8(0xce);
this.writeU32(object);
}
else {
// uint 64
this.writeU8(0xcf);
this.writeU64(object);
}
}
else {
if (object >= -0x20) {
// nagative fixint
this.writeU8(0xe0 | (object + 0x20));
}
else if (object >= -0x80) {
// int 8
this.writeU8(0xd0);
this.writeI8(object);
}
else if (object >= -0x8000) {
// int 16
this.writeU8(0xd1);
this.writeI16(object);
}
else if (object >= -0x80000000) {
// int 32
this.writeU8(0xd2);
this.writeI32(object);
}
else {
// int 64
this.writeU8(0xd3);
this.writeI64(object);
}
}
}
else {
// non-integer numbers
if (this.forceFloat32) {
// float 32
this.writeU8(0xca);
this.writeF32(object);
}
else {
// float 64
this.writeU8(0xcb);
this.writeF64(object);
}
}
};
Encoder.prototype.writeStringHeader = function (byteLength) {
if (byteLength < 32) {
// fixstr
this.writeU8(0xa0 + byteLength);
}
else if (byteLength < 0x100) {
// str 8
this.writeU8(0xd9);
this.writeU8(byteLength);
}
else if (byteLength < 0x10000) {
// str 16
this.writeU8(0xda);
this.writeU16(byteLength);
}
else if (byteLength < 0x100000000) {
// str 32
this.writeU8(0xdb);
this.writeU32(byteLength);
}
else {
throw new Error("Too long string: " + byteLength + " bytes in UTF-8");
}
};
Encoder.prototype.encodeString = function (object) {
var maxHeaderSize = 1 + 4;
var strLength = object.length;
if (strLength > TEXT_ENCODER_THRESHOLD) {
var byteLength = utf8Count(object);
this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
this.writeStringHeader(byteLength);
utf8EncodeTE(object, this.bytes, this.pos);
this.pos += byteLength;
}
else {
var byteLength = utf8Count(object);
this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
this.writeStringHeader(byteLength);
utf8EncodeJs(object, this.bytes, this.pos);
this.pos += byteLength;
}
};
Encoder.prototype.encodeObject = function (object, depth) {
// try to encode objects with custom codec first of non-primitives
var ext = this.extensionCodec.tryToEncode(object, this.context);
if (ext != null) {
this.encodeExtension(ext);
}
else if (Array.isArray(object)) {
this.encodeArray(object, depth);
}
else if (ArrayBuffer.isView(object)) {
this.encodeBinary(object);
}
else if (typeof object === "object") {
this.encodeMap(object, depth);
}
else {
// symbol, function and other special object come here unless extensionCodec handles them.
throw new Error("Unrecognized object: " + Object.prototype.toString.apply(object));
}
};
Encoder.prototype.encodeBinary = function (object) {
var size = object.byteLength;
if (size < 0x100) {
// bin 8
this.writeU8(0xc4);
this.writeU8(size);
}
else if (size < 0x10000) {
// bin 16
this.writeU8(0xc5);
this.writeU16(size);
}
else if (size < 0x100000000) {
// bin 32
this.writeU8(0xc6);
this.writeU32(size);
}
else {
throw new Error("Too large binary: " + size);
}
var bytes = ensureUint8Array(object);
this.writeU8a(bytes);
};
Encoder.prototype.encodeArray = function (object, depth) {
var e_1, _a;
var size = object.length;
if (size < 16) {
// fixarray
this.writeU8(0x90 + size);
}
else if (size < 0x10000) {
// array 16
this.writeU8(0xdc);
this.writeU16(size);
}
else if (size < 0x100000000) {
// array 32
this.writeU8(0xdd);
this.writeU32(size);
}
else {
throw new Error("Too large array: " + size);
}
try {
for (var object_1 = __values(object), object_1_1 = object_1.next(); !object_1_1.done; object_1_1 = object_1.next()) {
var item = object_1_1.value;
this.doEncode(item, depth + 1);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (object_1_1 && !object_1_1.done && (_a = object_1.return)) _a.call(object_1);
}
finally { if (e_1) throw e_1.error; }
}
};
Encoder.prototype.countWithoutUndefined = function (object, keys) {
var e_2, _a;
var count = 0;
try {
for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
var key = keys_1_1.value;
if (object[key] !== undefined) {
count++;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
}
finally { if (e_2) throw e_2.error; }
}
return count;
};
Encoder.prototype.encodeMap = function (object, depth) {
var e_3, _a;
var keys = Object.keys(object);
if (this.sortKeys) {
keys.sort();
}
var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
if (size < 16) {
// fixmap
this.writeU8(0x80 + size);
}
else if (size < 0x10000) {
// map 16
this.writeU8(0xde);
this.writeU16(size);
}
else if (size < 0x100000000) {
// map 32
this.writeU8(0xdf);
this.writeU32(size);
}
else {
throw new Error("Too large map object: " + size);
}
try {
for (var keys_2 = __values(keys), keys_2_1 = keys_2.next(); !keys_2_1.done; keys_2_1 = keys_2.next()) {
var key = keys_2_1.value;
var value = object[key];
if (!(this.ignoreUndefined && value === undefined)) {
this.encodeString(key);
this.doEncode(value, depth + 1);
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (keys_2_1 && !keys_2_1.done && (_a = keys_2.return)) _a.call(keys_2);
}
finally { if (e_3) throw e_3.error; }
}
};
Encoder.prototype.encodeExtension = function (ext) {
var size = ext.data.length;
if (size === 1) {
// fixext 1
this.writeU8(0xd4);
}
else if (size === 2) {
// fixext 2
this.writeU8(0xd5);
}
else if (size === 4) {
// fixext 4
this.writeU8(0xd6);
}
else if (size === 8) {
// fixext 8
this.writeU8(0xd7);
}
else if (size === 16) {
// fixext 16
this.writeU8(0xd8);
}
else if (size < 0x100) {
// ext 8
this.writeU8(0xc7);
this.writeU8(size);
}
else if (size < 0x10000) {
// ext 16
this.writeU8(0xc8);
this.writeU16(size);
}
else if (size < 0x100000000) {
// ext 32
this.writeU8(0xc9);
this.writeU32(size);
}
else {
throw new Error("Too large extension object: " + size);
}
this.writeI8(ext.type);
this.writeU8a(ext.data);
};
Encoder.prototype.writeU8 = function (value) {
this.ensureBufferSizeToWrite(1);
this.view.setUint8(this.pos, value);
this.pos++;
};
Encoder.prototype.writeU8a = function (values) {
var size = values.length;
this.ensureBufferSizeToWrite(size);
this.bytes.set(values, this.pos);
this.pos += size;
};
Encoder.prototype.writeI8 = function (value) {
this.ensureBufferSizeToWrite(1);
this.view.setInt8(this.pos, value);
this.pos++;
};
Encoder.prototype.writeU16 = function (value) {
this.ensureBufferSizeToWrite(2);
this.view.setUint16(this.pos, value);
this.pos += 2;
};
Encoder.prototype.writeI16 = function (value) {
this.ensureBufferSizeToWrite(2);
this.view.setInt16(this.pos, value);
this.pos += 2;
};
Encoder.prototype.writeU32 = function (value) {
this.ensureBufferSizeToWrite(4);
this.view.setUint32(this.pos, value);
this.pos += 4;
};
Encoder.prototype.writeI32 = function (value) {
this.ensureBufferSizeToWrite(4);
this.view.setInt32(this.pos, value);
this.pos += 4;
};
Encoder.prototype.writeF32 = function (value) {
this.ensureBufferSizeToWrite(4);
this.view.setFloat32(this.pos, value);
this.pos += 4;
};
Encoder.prototype.writeF64 = function (value) {
this.ensureBufferSizeToWrite(8);
this.view.setFloat64(this.pos, value);
this.pos += 8;
};
Encoder.prototype.writeU64 = function (value) {
this.ensureBufferSizeToWrite(8);
setUint64(this.view, this.pos, value);
this.pos += 8;
};
Encoder.prototype.writeI64 = function (value) {
this.ensureBufferSizeToWrite(8);
setInt64(this.view, this.pos, value);
this.pos += 8;
};
return Encoder;
}());
;// CONCATENATED MODULE: ./src/encode.ts
var defaultEncodeOptions = {};
/**
* It encodes `value` in the MessagePack format and
* returns a byte buffer.
*
* The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.
*/
function encode(value, options) {
if (options === void 0) { options = defaultEncodeOptions; }
var encoder = new Encoder(options.extensionCodec, options.context, options.maxDepth, options.initialBufferSize, options.sortKeys, options.forceFloat32, options.ignoreUndefined, options.forceIntegerToFloat);
return encoder.encode(value);
}
;// CONCATENATED MODULE: ./src/utils/prettyByte.ts
function prettyByte(byte) {
return (byte < 0 ? "-" : "") + "0x" + Math.abs(byte).toString(16).padStart(2, "0");
}
;// CONCATENATED MODULE: ./src/CachedKeyDecoder.ts
var DEFAULT_MAX_KEY_LENGTH = 16;
var DEFAULT_MAX_LENGTH_PER_KEY = 16;
var CachedKeyDecoder = /** @class */ (function () {
function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
this.maxKeyLength = maxKeyLength;
this.maxLengthPerKey = maxLengthPerKey;
this.hit = 0;
this.miss = 0;
// avoid `new Array(N)` to create a non-sparse array for performance.
this.caches = [];
for (var i = 0; i < this.maxKeyLength; i++) {
this.caches.push([]);
}
}
CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
return byteLength > 0 && byteLength <= this.maxKeyLength;
};
CachedKeyDecoder.prototype.get = function (bytes, inputOffset, byteLength) {
var e_1, _a;
var records = this.caches[byteLength - 1];
try {
FIND_CHUNK: for (var records_1 = __values(records), records_1_1 = records_1.next(); !records_1_1.done; records_1_1 = records_1.next()) {
var record = records_1_1.value;
var recordBytes = record.bytes;
for (var j = 0; j < byteLength; j++) {
if (recordBytes[j] !== bytes[inputOffset + j]) {
continue FIND_CHUNK;
}
}
return record.value;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (records_1_1 && !records_1_1.done && (_a = records_1.return)) _a.call(records_1);
}
finally { if (e_1) throw e_1.error; }
}
return null;
};
CachedKeyDecoder.prototype.store = function (bytes, value) {
var records = this.caches[bytes.length - 1];
var record = { bytes: bytes, value: value };
if (records.length >= this.maxLengthPerKey) {
// `records` are full!
// Set `record` to a randomized position.
records[(Math.random() * records.length) | 0] = record;
}
else {
records.push(record);
}
};
CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
var cachedValue = this.get(bytes, inputOffset, byteLength);
if (cachedValue != null) {
this.hit++;
return cachedValue;
}
this.miss++;
var value = utf8DecodeJs(bytes, inputOffset, byteLength);
// Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
this.store(slicedCopyOfBytes, value);
return value;
};
return CachedKeyDecoder;
}());
;// CONCATENATED MODULE: ./src/Decoder.ts
var isValidMapKeyType = function (key) {
var keyType = typeof key;
return keyType === "string" || keyType === "number";
};
var HEAD_BYTE_REQUIRED = -1;
var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
// IE11: Hack to support IE11.
// IE11: Drop this hack and just use RangeError when IE11 is obsolete.
var DataViewIndexOutOfBoundsError = (function () {
try {
// IE11: The spec says it should throw RangeError,
// IE11: but in IE11 it throws TypeError.
EMPTY_VIEW.getInt8(0);
}
catch (e) {
return e.constructor;
}
throw new Error("never reached");
})();
var MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data");
var DEFAULT_MAX_LENGTH = 4294967295; // uint32_max
var sharedCachedKeyDecoder = new CachedKeyDecoder();
var DecodeError = /** @class */ (function (_super) {
__extends(DecodeError, _super);
function DecodeError(message) {
var _this = _super.call(this, message) || this;
// fix the prototype chain in a cross-platform way
var proto = Object.create(DecodeError.prototype);
Object.setPrototypeOf(_this, proto);
Object.defineProperty(_this, "name", {
configurable: true,
enumerable: false,
value: DecodeError.name,
});
return _this;
}
return DecodeError;
}(Error));
var Decoder = /** @class */ (function () {
function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {
if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }
if (context === void 0) { context = undefined; }
if (maxStrLength === void 0) { maxStrLength = DEFAULT_MAX_LENGTH; }
if (maxBinLength === void 0) { maxBinLength = DEFAULT_MAX_LENGTH; }
if (maxArrayLength === void 0) { maxArrayLength = DEFAULT_MAX_LENGTH; }
if (maxMapLength === void 0) { maxMapLength = DEFAULT_MAX_LENGTH; }
if (maxExtLength === void 0) { maxExtLength = DEFAULT_MAX_LENGTH; }
if (keyDecoder === void 0) { keyDecoder = sharedCachedKeyDecoder; }
this.extensionCodec = extensionCodec;
this.context = context;
this.maxStrLength = maxStrLength;
this.maxBinLength = maxBinLength;
this.maxArrayLength = maxArrayLength;
this.maxMapLength = maxMapLength;
this.maxExtLength = maxExtLength;
this.keyDecoder = keyDecoder;
this.totalPos = 0;
this.pos = 0;
this.view = EMPTY_VIEW;
this.bytes = EMPTY_BYTES;
this.headByte = HEAD_BYTE_REQUIRED;
this.stack = [];
}
Decoder.prototype.reinitializeState = function () {
this.totalPos = 0;
this.headByte = HEAD_BYTE_REQUIRED;
};
Decoder.prototype.setBuffer = function (buffer) {
this.bytes = ensureUint8Array(buffer);
this.view = createDataView(this.bytes);
this.pos = 0;
};
Decoder.prototype.appendBuffer = function (buffer) {
if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining()) {
this.setBuffer(buffer);
}
else {
// retried because data is insufficient
var remainingData = this.bytes.subarray(this.pos);
var newData = ensureUint8Array(buffer);
var concated = new Uint8Array(remainingData.length + newData.length);
concated.set(remainingData);
concated.set(newData, remainingData.length);
this.setBuffer(concated);
}
};
Decoder.prototype.hasRemaining = function (size) {
if (size === void 0) { size = 1; }
return this.view.byteLength - this.pos >= size;
};
Decoder.prototype.createExtraByteError = function (posToShow) {
var _a = this, view = _a.view, pos = _a.pos;
return new RangeError("Extra " + (view.byteLength - pos) + " of " + view.byteLength + " byte(s) found at buffer[" + posToShow + "]");
};
Decoder.prototype.decode = function (buffer) {
this.reinitializeState();
this.setBuffer(buffer);
var object = this.doDecodeSync();
if (this.hasRemaining()) {
throw this.createExtraByteError(this.pos);
}
return object;
};
Decoder.prototype.decodeMulti = function (buffer) {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.reinitializeState();
this.setBuffer(buffer);
_a.label = 1;
case 1:
if (!this.hasRemaining()) return [3 /*break*/, 3];
return [4 /*yield*/, this.doDecodeSync()];
case 2:
_a.sent();
return [3 /*break*/, 1];
case 3: return [2 /*return*/];
}
});
};
Decoder.prototype.decodeAsync = function (stream) {
var stream_1, stream_1_1;
var e_1, _a;
return __awaiter(this, void 0, void 0, function () {
var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
decoded = false;
_c.label = 1;
case 1:
_c.trys.push([1, 6, 7, 12]);
stream_1 = __asyncValues(stream);
_c.label = 2;
case 2: return [4 /*yield*/, stream_1.next()];
case 3:
if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3 /*break*/, 5];
buffer = stream_1_1.value;
if (decoded) {
throw this.createExtraByteError(this.totalPos);
}
this.appendBuffer(buffer);
try {
object = this.doDecodeSync();
decoded = true;
}
catch (e) {
if (!(e instanceof DataViewIndexOutOfBoundsError)) {
throw e; // rethrow
}
// fallthrough
}
this.totalPos += this.pos;
_c.label = 4;
case 4: return [3 /*break*/, 2];
case 5: return [3 /*break*/, 12];
case 6:
e_1_1 = _c.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 12];
case 7:
_c.trys.push([7, , 10, 11]);
if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3 /*break*/, 9];
return [4 /*yield*/, _a.call(stream_1)];
case 8:
_c.sent();
_c.label = 9;
case 9: return [3 /*break*/, 11];
case 10:
if (e_1) throw e_1.error;
return [7 /*endfinally*/];
case 11: return [7 /*endfinally*/];
case 12:
if (decoded) {
if (this.hasRemaining()) {
throw this.createExtraByteError(this.totalPos);
}
return [2 /*return*/, object];
}
_b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;
throw new RangeError("Insufficient data in parsing " + prettyByte(headByte) + " at " + totalPos + " (" + pos + " in the current buffer)");
}
});
});
};
Decoder.prototype.decodeArrayStream = function (stream) {
return this.decodeMultiAsync(stream, true);
};
Decoder.prototype.decodeStream = function (stream) {
return this.decodeMultiAsync(stream, false);
};
Decoder.prototype.decodeMultiAsync = function (stream, isArray) {
return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {
var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;
var e_3, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
isArrayHeaderRequired = isArray;
arrayItemsLeft = -1;
_b.label = 1;
case 1:
_b.trys.push([1, 13, 14, 19]);
stream_2 = __asyncValues(stream);
_b.label = 2;
case 2: return [4 /*yield*/, __await(stream_2.next())];
case 3:
if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3 /*break*/, 12];
buffer = stream_2_1.value;
if (isArray && arrayItemsLeft === 0) {
throw this.createExtraByteError(this.totalPos);
}
this.appendBuffer(buffer);
if (isArrayHeaderRequired) {
arrayItemsLeft = this.readArraySize();
isArrayHeaderRequired = false;
this.complete();
}
_b.label = 4;
case 4:
_b.trys.push([4, 9, , 10]);
_b.label = 5;
case 5:
if (false) {}
return [4 /*yield*/, __await(this.doDecodeSync())];
case 6: return [4 /*yield*/, _b.sent()];
case 7:
_b.sent();
if (--arrayItemsLeft === 0) {
return [3 /*break*/, 8];
}
return [3 /*break*/, 5];
case 8: return [3 /*break*/, 10];
case 9:
e_2 = _b.sent();
if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) {
throw e_2; // rethrow
}
return [3 /*break*/, 10];
case 10:
this.totalPos += this.pos;
_b.label = 11;
case 11: return [3 /*break*/, 2];
case 12: return [3 /*break*/, 19];
case 13:
e_3_1 = _b.sent();
e_3 = { error: e_3_1 };
return [3 /*break*/, 19];
case 14:
_b.trys.push([14, , 17, 18]);
if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3 /*break*/, 16];
return [4 /*yield*/, __await(_a.call(stream_2))];
case 15:
_b.sent();
_b.label = 16;
case 16: return [3 /*break*/, 18];
case 17:
if (e_3) throw e_3.error;
return [7 /*endfinally*/];
case 18: return [7 /*endfinally*/];
case 19: return [2 /*return*/];
}
});
});
};
Decoder.prototype.doDecodeSync = function () {
DECODE: while (true) {
var headByte = this.readHeadByte();
var object = void 0;
if (headByte >= 0xe0) {
// negative fixint (111x xxxx) 0xe0 - 0xff
object = headByte - 0x100;
}
else if (headByte < 0xc0) {
if (headByte < 0x80) {
// positive fixint (0xxx xxxx) 0x00 - 0x7f
object = headByte;
}
else if (headByte < 0x90) {
// fixmap (1000 xxxx) 0x80 - 0x8f
var size = headByte - 0x80;
if (size !== 0) {
this.pushMapState(size);
this.complete();
continue DECODE;
}
else {
object = {};
}
}
else if (headByte < 0xa0) {
// fixarray (1001 xxxx) 0x90 - 0x9f
var size = headByte - 0x90;
if (size !== 0) {
this.pushArrayState(size);
this.complete();
continue DECODE;
}
else {
object = [];
}
}
else {
// fixstr (101x xxxx) 0xa0 - 0xbf
var byteLength = headByte - 0xa0;
object = this.decodeUtf8String(byteLength, 0);
}
}
else if (headByte === 0xc0) {
// nil
object = null;
}
else if (headByte === 0xc2) {
// false
object = false;
}
else if (headByte === 0xc3) {
// true
object = true;
}
else if (headByte === 0xca) {
// float 32
object = this.readF32();
}
else if (headByte === 0xcb) {
// float 64
object = this.readF64();
}
else if (headByte === 0xcc) {
// uint 8
object = this.readU8();
}
else if (headByte === 0xcd) {
// uint 16
object = this.readU16();
}
else if (headByte === 0xce) {
// uint 32
object = this.readU32();
}
else if (headByte === 0xcf) {
// uint 64
object = this.readU64();
}
else if (headByte === 0xd0) {
// int 8
object = this.readI8();
}
else if (headByte === 0xd1) {
// int 16
object = this.readI16();
}
else if (headByte === 0xd2) {
// int 32
object = this.readI32();
}
else if (headByte === 0xd3) {
// int 64
object = this.readI64();
}
else if (headByte === 0xd9) {
// str 8
var byteLength = this.lookU8();
object = this.decodeUtf8String(byteLength, 1);
}
else if (headByte === 0xda) {
// str 16
var byteLength = this.lookU16();
object = this.decodeUtf8String(byteLength, 2);
}
else if (headByte === 0xdb) {
// str 32
var byteLength = this.lookU32();
object = this.decodeUtf8String(byteLength, 4);
}
else if (headByte === 0xdc) {
// array 16
var size = this.readU16();
if (size !== 0) {
this.pushArrayState(size);
this.complete();
continue DECODE;
}
else {
object = [];
}
}
else if (headByte === 0xdd) {
// array 32
var size = this.readU32();
if (size !== 0) {
this.pushArrayState(size);
this.complete();
continue DECODE;
}
else {
object = [];
}
}
else if (headByte === 0xde) {
// map 16
var size = this.readU16();
if (size !== 0) {
this.pushMapState(size);
this.complete();
continue DECODE;
}
else {
object = {};
}
}
else if (headByte === 0xdf) {
// map 32
var size = this.readU32();
if (size !== 0) {
this.pushMapState(size);
this.complete();
continue DECODE;
}
else {
object = {};
}
}
else if (headByte === 0xc4) {
// bin 8
var size = this.lookU8();
object = this.decodeBinary(size, 1);
}
else if (headByte === 0xc5) {
// bin 16
var size = this.lookU16();
object = this.decodeBinary(size, 2);
}
else if (headByte === 0xc6) {
// bin 32
var size = this.lookU32();
object = this.decodeBinary(size, 4);
}
else if (headByte === 0xd4) {
// fixext 1
object = this.decodeExtension(1, 0);
}
else if (headByte === 0xd5) {
// fixext 2
object = this.decodeExtension(2, 0);
}
else if (headByte === 0xd6) {
// fixext 4
object = this.decodeExtension(4, 0);
}
else if (headByte === 0xd7) {
// fixext 8
object = this.decodeExtension(8, 0);
}
else if (headByte === 0xd8) {
// fixext 16
object = this.decodeExtension(16, 0);
}
else if (headByte === 0xc7) {
// ext 8
var size = this.lookU8();
object = this.decodeExtension(size, 1);
}
else if (headByte === 0xc8) {
// ext 16
var size = this.lookU16();
object = this.decodeExtension(size, 2);
}
else if (headByte === 0xc9) {
// ext 32
var size = this.lookU32();
object = this.decodeExtension(size, 4);
}
else {
throw new DecodeError("Unrecognized type byte: " + prettyByte(headByte));
}
this.complete();
var stack = this.stack;
while (stack.length > 0) {
// arrays and maps
var state = stack[stack.length - 1];
if (state.type === 0 /* ARRAY */) {
state.array[state.position] = object;
state.position++;
if (state.position === state.size) {
stack.pop();
object = state.array;
}
else {
continue DECODE;
}
}
else if (state.type === 1 /* MAP_KEY */) {
if (!isValidMapKeyType(object)) {
throw new DecodeError("The type of key must be string or number but " + typeof object);
}
if (object === "__proto__") {
throw new DecodeError("The key __proto__ is not allowed");
}
state.key = object;
state.type = 2 /* MAP_VALUE */;
continue DECODE;
}
else {
// it must be `state.type === State.MAP_VALUE` here
state.map[state.key] = object;
state.readCount++;
if (state.readCount === state.size) {
stack.pop();
object = state.map;
}
else {
state.key = null;
state.type = 1 /* MAP_KEY */;
continue DECODE;
}
}
}
return object;
}
};
Decoder.prototype.readHeadByte = function () {
if (this.headByte === HEAD_BYTE_REQUIRED) {
this.headByte = this.readU8();
// console.log("headByte", prettyByte(this.headByte));
}
return this.headByte;
};
Decoder.prototype.complete = function () {
this.headByte = HEAD_BYTE_REQUIRED;
};
Decoder.prototype.readArraySize = function () {
var headByte = this.readHeadByte();
switch (headByte) {
case 0xdc:
return this.readU16();
case 0xdd:
return this.readU32();
default: {
if (headByte < 0xa0) {
return headByte - 0x90;
}
else {
throw new DecodeError("Unrecognized array type byte: " + prettyByte(headByte));
}
}
}
};
Decoder.prototype.pushMapState = function (size) {
if (size > this.maxMapLength) {
throw new DecodeError("Max length exceeded: map length (" + size + ") > maxMapLengthLength (" + this.maxMapLength + ")");
}
this.stack.push({
type: 1 /* MAP_KEY */,
size: size,
key: null,
readCount: 0,
map: {},
});
};
Decoder.prototype.pushArrayState = function (size) {
if (size > this.maxArrayLength) {
throw new DecodeError("Max length exceeded: array length (" + size + ") > maxArrayLength (" + this.maxArrayLength + ")");
}
this.stack.push({
type: 0 /* ARRAY */,
size: size,
array: new Array(size),
position: 0,
});
};
Decoder.prototype.decodeUtf8String = function (byteLength, headerOffset) {
var _a;
if (byteLength > this.maxStrLength) {
throw new DecodeError("Max length exceeded: UTF-8 byte length (" + byteLength + ") > maxStrLength (" + this.maxStrLength + ")");
}
if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
throw MORE_DATA;
}
var offset = this.pos + headerOffset;
var object;
if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) {
object = this.keyDecoder.decode(this.bytes, offset, byteLength);
}
else if (byteLength > TEXT_DECODER_THRESHOLD) {
object = utf8DecodeTD(this.bytes, offset, byteLength);
}
else {
object = utf8DecodeJs(this.bytes, offset, byteLength);
}
this.pos += headerOffset + byteLength;
return object;
};
Decoder.prototype.stateIsMapKey = function () {
if (this.stack.length > 0) {
var state = this.stack[this.stack.length - 1];
return state.type === 1 /* MAP_KEY */;
}
return false;
};
Decoder.prototype.decodeBinary = function (byteLength, headOffset) {
if (byteLength > this.maxBinLength) {
throw new DecodeError("Max length exceeded: bin length (" + byteLength + ") > maxBinLength (" + this.maxBinLength + ")");
}
if (!this.hasRemaining(byteLength + headOffset)) {
throw MORE_DATA;
}
var offset = this.pos + headOffset;
var object = this.bytes.subarray(offset, offset + byteLength);
this.pos += headOffset + byteLength;
return object;
};
Decoder.prototype.decodeExtension = function (size, headOffset) {
if (size > this.maxExtLength) {
throw new DecodeError("Max length exceeded: ext length (" + size + ") > maxExtLength (" + this.maxExtLength + ")");
}
var extType = this.view.getInt8(this.pos + headOffset);
var data = this.decodeBinary(size, headOffset + 1 /* extType */);
return this.extensionCodec.decode(data, extType, this.context);
};
Decoder.prototype.lookU8 = function () {
return this.view.getUint8(this.pos);
};
Decoder.prototype.lookU16 = function () {
return this.view.getUint16(this.pos);
};
Decoder.prototype.lookU32 = function () {
return this.view.getUint32(this.pos);
};
Decoder.prototype.readU8 = function () {
var value = this.view.getUint8(this.pos);
this.pos++;
return value;
};
Decoder.prototype.readI8 = function () {
var value = this.view.getInt8(this.pos);
this.pos++;
return value;
};
Decoder.prototype.readU16 = function () {
var value = this.view.getUint16(this.pos);
this.pos += 2;
return value;
};
Decoder.prototype.readI16 = function () {
var value = this.view.getInt16(this.pos);
this.pos += 2;
return value;
};
Decoder.prototype.readU32 = function () {
var value = this.view.getUint32(this.pos);
this.pos += 4;
return value;
};
Decoder.prototype.readI32 = function () {
var value = this.view.getInt32(this.pos);
this.pos += 4;
return value;
};
Decoder.prototype.readU64 = function () {
var value = getUint64(this.view, this.pos);
this.pos += 8;
return value;
};
Decoder.prototype.readI64 = function () {
var value = getInt64(this.view, this.pos);
this.pos += 8;
return value;
};
Decoder.prototype.readF32 = function () {
var value = this.view.getFloat32(this.pos);
this.pos += 4;
return value;
};
Decoder.prototype.readF64 = function () {
var value = this.view.getFloat64(this.pos);
this.pos += 8;
return value;
};
return Decoder;
}());
;// CONCATENATED MODULE: ./src/decode.ts
var defaultDecodeOptions = {};
/**
* It decodes a single MessagePack object in a buffer.
*
* This is a synchronous decoding function.
* See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
*/
function decode(buffer, options) {
if (options === void 0) { options = defaultDecodeOptions; }
var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
return decoder.decode(buffer);
}
/**
* It decodes multiple MessagePack objects in a buffer.
* This is corresponding to {@link decodeMultiStream()}.
*/
function decodeMulti(buffer, options) {
if (options === void 0) { options = defaultDecodeOptions; }
var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
return decoder.decodeMulti(buffer);
}
;// CONCATENATED MODULE: ./src/utils/stream.ts
// utility for whatwg streams
function isAsyncIterable(object) {
return object[Symbol.asyncIterator] != null;
}
function assertNonNull(value) {
if (value == null) {
throw new Error("Assertion Failure: value must not be null nor undefined");
}
}
function asyncIterableFromStream(stream) {
return __asyncGenerator(this, arguments, function asyncIterableFromStream_1() {
var reader, _a, done, value;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
reader = stream.getReader();
_b.label = 1;
case 1:
_b.trys.push([1, , 9, 10]);
_b.label = 2;
case 2:
if (false) {}
return [4 /*yield*/, __await(reader.read())];
case 3:
_a = _b.sent(), done = _a.done, value = _a.value;
if (!done) return [3 /*break*/, 5];
return [4 /*yield*/, __await(void 0)];
case 4: return [2 /*return*/, _b.sent()];
case 5:
assertNonNull(value);
return [4 /*yield*/, __await(value)];
case 6: return [4 /*yield*/, _b.sent()];
case 7:
_b.sent();
return [3 /*break*/, 2];
case 8: return [3 /*break*/, 10];
case 9:
reader.releaseLock();
return [7 /*endfinally*/];
case 10: return [2 /*return*/];
}
});
});
}
function ensureAsyncIterable(streamLike) {
if (isAsyncIterable(streamLike)) {
return streamLike;
}
else {
return asyncIterableFromStream(streamLike);
}
}
;// CONCATENATED MODULE: ./src/decodeAsync.ts
function decodeAsync(streamLike, options) {
if (options === void 0) { options = defaultDecodeOptions; }
return __awaiter(this, void 0, void 0, function () {
var stream, decoder;
return __generator(this, function (_a) {
stream = ensureAsyncIterable(streamLike);
decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
return [2 /*return*/, decoder.decodeAsync(stream)];
});
});
}
function decodeArrayStream(streamLike, options) {
if (options === void 0) { options = defaultDecodeOptions; }
var stream = ensureAsyncIterable(streamLike);
var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
return decoder.decodeArrayStream(stream);
}
function decodeMultiStream(streamLike, options) {
if (options === void 0) { options = defaultDecodeOptions; }
var stream = ensureAsyncIterable(streamLike);
var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
return decoder.decodeStream(stream);
}
/**
* @deprecated Use {@link decodeMultiStream()} instead.
*/
function decodeStream(streamLike, options) {
if (options === void 0) { options = defaultDecodeOptions; }
return decodeMultiStream(streamLike, options);
}
;// CONCATENATED MODULE: ./src/index.ts
// Main Functions:
// Utilitiies for Extension Types:
/******/ return __webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=msgpack.js.map