From cb1403d1d60b41d93fab98c8695d03f8b0e4a4d1 Mon Sep 17 00:00:00 2001 From: Dillon Skaggs Date: Thu, 19 Dec 2024 03:47:35 -0600 Subject: [PATCH] feat(v8/scripting): swap from msgpack-lite to msgpackr Co-authored-by: Linden <65407488+thelindat@users.noreply.github.com> --- data/shared/citizen/scripting/v8/main.js | 39 +- data/shared/citizen/scripting/v8/msgpack.d.ts | 89 + data/shared/citizen/scripting/v8/msgpack.js | 2361 ++++++++++++++++- 3 files changed, 2445 insertions(+), 44 deletions(-) create mode 100644 data/shared/citizen/scripting/v8/msgpack.d.ts diff --git a/data/shared/citizen/scripting/v8/main.js b/data/shared/citizen/scripting/v8/main.js index cfba3db175..d30c9681ea 100644 --- a/data/shared/citizen/scripting/v8/main.js +++ b/data/shared/citizen/scripting/v8/main.js @@ -1,5 +1,6 @@ // CFX JS runtime /// +/// const EXT_FUNCREF = 10; const EXT_LOCALFUNCREF = 11; @@ -41,18 +42,34 @@ const EXT_LOCALFUNCREF = 11; const nextRefIdx = () => refIndex++; const refFunctionsMap = new Map(); - const codec = msgpack.createCodec({ - uint8array: true, - preset: false, - binarraybuffer: true - }); + /** @type {import("./msgpack").Options} */ + const packrOptions = { + // use "std::map" for the underlying msgpack type for compatibility + useRecords: false, + // allow Map, Set, and Error to be serialized + moreTypes: true, + // keep compatibility Lua/C# + encodeUndefinedAsNil: true, + } + + /** @type {import("./msgpack").Packr} */ + const packr = new Packr(packrOptions); - const pack = data => msgpack.encode(data, { codec }); - const unpack = data => msgpack.decode(data, { codec }); + addExtension({ + Class: Function, + type: EXT_FUNCREF, + pack: refFunctionPacker, + unpack: refFunctionUnpacker + }) + + + const pack = (value) => packr.pack(value); + const unpack = (packed_value) => packr.unpack(packed_value); // store for use by natives.js global.msgpack_pack = pack; global.msgpack_unpack = unpack; + global.msgpack_packr = packr; /** * @param {Function} refFunction @@ -72,7 +89,7 @@ const EXT_LOCALFUNCREF = 11; function refFunctionPacker(refFunction) { const ref = Citizen.makeRefFunction(refFunction); - return ref; + return Buffer.from(ref); } function refFunctionUnpacker(refSerialized) { @@ -134,12 +151,6 @@ const EXT_LOCALFUNCREF = 11; }; } - const AsyncFunction = (async () => {}).constructor; - codec.addExtPacker(EXT_FUNCREF, AsyncFunction, refFunctionPacker); - codec.addExtPacker(EXT_FUNCREF, Function, refFunctionPacker); - codec.addExtUnpacker(EXT_FUNCREF, refFunctionUnpacker); - codec.addExtUnpacker(EXT_LOCALFUNCREF, refFunctionUnpacker); - /** * Deletes ref function * diff --git a/data/shared/citizen/scripting/v8/msgpack.d.ts b/data/shared/citizen/scripting/v8/msgpack.d.ts new file mode 100644 index 0000000000..739175d2af --- /dev/null +++ b/data/shared/citizen/scripting/v8/msgpack.d.ts @@ -0,0 +1,89 @@ +export enum FLOAT32_OPTIONS { + NEVER = 0, + ALWAYS = 1, + DECIMAL_ROUND = 3, + DECIMAL_FIT = 4 +} + +export interface Options { + useFloat32?: FLOAT32_OPTIONS + useRecords?: boolean | ((value:any)=> boolean) + structures?: {}[] + moreTypes?: boolean + sequential?: boolean + structuredClone?: boolean + mapsAsObjects?: boolean + variableMapSize?: boolean + coercibleKeyAsNumber?: boolean + copyBuffers?: boolean + bundleStrings?: boolean + useTimestamp32?: boolean + largeBigIntToFloat?: boolean + largeBigIntToString?: boolean + useBigIntExtension?: boolean + encodeUndefinedAsNil?: boolean + maxSharedStructures?: number + maxOwnStructures?: number + mapAsEmptyObject?: boolean + setAsEmptyObject?: boolean + writeFunction?: () => any + /** @deprecated use int64AsType: 'number' */ + int64AsNumber?: boolean + int64AsType?: 'bigint' | 'number' | 'string' + shouldShareStructure?: (keys: string[]) => boolean + getStructures?(): {}[] + saveStructures?(structures: {}[]): boolean | void + onInvalidDate?: () => any +} +interface Extension { + Class?: Function + type?: number + pack?(value: any): Buffer | Uint8Array + unpack?(messagePack: Buffer | Uint8Array): any + read?(datum: any): any + write?(instance: any): any +} +export type UnpackOptions = { start?: number; end?: number; lazy?: boolean; } | number; +export class Unpackr { + constructor(options?: Options) + unpack(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any + decode(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any + unpackMultiple(messagePack: Buffer | Uint8Array): any[] + unpackMultiple(messagePack: Buffer | Uint8Array, forEach: (value: any, start?: number, end?: number) => any): void +} +export class Decoder extends Unpackr {} +export function unpack(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any +export function unpackMultiple(messagePack: Buffer | Uint8Array): any[] +export function unpackMultiple(messagePack: Buffer | Uint8Array, forEach: (value: any, start?: number, end?: number) => any): void +export function decode(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any +export function addExtension(extension: Extension): void +export function clearSource(): void +export function roundFloat32(float32Number: number): number +export const C1: {} +export let isNativeAccelerationEnabled: boolean + +export class Packr extends Unpackr { + offset: number; + position: number; + pack(value: any, encodeOptions?: number): Buffer + encode(value: any, encodeOptions?: number): Buffer + useBuffer(buffer: Buffer | Uint8Array): void; + clearSharedData(): void; +} +export class Encoder extends Packr {} +export function pack(value: any, encodeOptions?: number): Buffer +export function encode(value: any, encodeOptions?: number): Buffer + +export const REUSE_BUFFER_MODE: number; +export const RESET_BUFFER_MODE: number; +export const RESERVE_START_SPACE: number; + +import { Transform, Readable } from 'stream' + +export as namespace msgpackr; +export class UnpackrStream extends Transform { + constructor(options?: Options | { highWaterMark: number, emitClose: boolean, allowHalfOpen: boolean }) +} +export class PackrStream extends Transform { + constructor(options?: Options | { highWaterMark: number, emitClose: boolean, allowHalfOpen: boolean }) +} diff --git a/data/shared/citizen/scripting/v8/msgpack.js b/data/shared/citizen/scripting/v8/msgpack.js index 670aee7789..46cf68cf59 100644 --- a/data/shared/citizen/scripting/v8/msgpack.js +++ b/data/shared/citizen/scripting/v8/msgpack.js @@ -1,30 +1,2331 @@ -/* - https://github.com/kawanet/msgpack-lite - - The MIT License (MIT) - - Copyright (c) 2015 Yusuke Kawasaki - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - */ - - // Modified to support functions packing, fork: https://github.com/thers/msgpack-lite - -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.msgpack=t()}}(function(){return function t(r,e,n){function i(f,u){if(!e[f]){if(!r[f]){var a="function"==typeof require&&require;if(!u&&a)return a(f,!0);if(o)return o(f,!0);var s=new Error("Cannot find module '"+f+"'");throw s.code="MODULE_NOT_FOUND",s}var c=e[f]={exports:{}};r[f][0].call(c.exports,function(t){var e=r[f][1][t];return i(e||t)},c,c.exports,t,r,e,n)}return e[f].exports}for(var o="function"==typeof require&&require,f=0;f>>6,e[n++]=128|63&o):o<55296||o>57343?(e[n++]=224|o>>>12,e[n++]=128|o>>>6&63,e[n++]=128|63&o):(o=65536+(o-55296<<10|t.charCodeAt(f++)-56320),e[n++]=240|o>>>18,e[n++]=128|o>>>12&63,e[n++]=128|o>>>6&63,e[n++]=128|63&o);return n-r}function i(t,r,e){var n=this,i=0|r;e||(e=n.length);for(var o="",f=0;i=65536?(f-=65536,o+=String.fromCharCode(55296+(f>>>10),56320+(1023&f))):o+=String.fromCharCode(f));return o}function o(t,r,e,n){var i;e||(e=0),n||0===n||(n=this.length),r||(r=0);var o=n-e;if(t===this&&e=0;i--)t[i+r]=this[i+e];else for(i=0;ithis.buffer.length)throw new Error(d);return this.offset=e,r}return{bufferish:h,write:t,fetch:f,flush:r,push:a,pull:s,read:u,reserve:e,offset:0}}()),n.mixin(n.prototype),i.mixin=c(function(){function t(){var t=this.start;if(t1?this.bufferish.concat(t):t[0];return t.length=0,r}function n(t){var r=0|t;if(this.buffer){var e=this.buffer.length,n=0|this.offset,i=n+r;if(ithis.minBufferSize)this.flush(),this.push(t);else{var e=this.reserve(r);h.prototype.copy.call(t,this.buffer,e)}}return{bufferish:h,write:o,fetch:t,flush:r,push:a,pull:e,read:u,reserve:n,send:i,maxBufferSize:p,minBufferSize:l,offset:0,start:0}}()),i.mixin(i.prototype)},{"./bufferish":8}],22:[function(t,r,e){function n(t){function r(t){var r=s(t),n=e[r];if(!n)throw new Error("Invalid type: "+(r?"0x"+r.toString(16):r));return n(t)}var e=c.getReadToken(t);return r}function i(){var t=this.options;return this.decode=n(t),t&&t.preset&&a.setExtUnpackers(this),this}function o(t,r){(this.extUnpackers||(this.extUnpackers=[]))[t]=h.filter(r)}function f(t){function r(r){return new u(r,t)}return(this.extUnpackers||(this.extUnpackers=[]))[t]||r}var u=t("./ext-buffer").ExtBuffer,a=t("./ext-unpacker"),s=t("./read-format").readUint8,c=t("./read-token"),h=t("./codec-base");h.install({addExtUnpacker:o,getExtUnpacker:f,init:i}),e.preset=i.call(h.preset)},{"./codec-base":9,"./ext-buffer":17,"./ext-unpacker":19,"./read-format":23,"./read-token":24}],23:[function(t,r,e){function n(t){var r=k.hasArrayBuffer&&t&&t.binarraybuffer,e=t&&t.int64;return{map:T&&t&&t.usemap?o:i,array:f,str:u,bin:r?s:a,ext:c,uint8:h,uint16:p,uint32:y,uint64:v(8,e?E:b),int8:l,int16:d,int32:g,int64:v(8,e?A:w),float32:v(4,m),float64:v(8,x)}}function i(t,r){var e,n={},i=new Array(r),o=new Array(r),f=t.codec.decode;for(e=0;e>>8,i[n]=e}}function s(t){return function(r,e){var n=r.reserve(5),i=r.buffer;i[n++]=t,i[n++]=e>>>24,i[n++]=e>>>16,i[n++]=e>>>8,i[n]=e}}function c(t,r,e,n){return function(i,o){var f=i.reserve(r+1);i.buffer[f++]=t,e.call(i.buffer,o,f,n)}}function h(t,r){new v(this,r,t)}function l(t,r){new b(this,r,t)}function p(t,r){y.write(this,t,r,!1,23,4)}function d(t,r){y.write(this,t,r,!1,52,8)}var y=t("ieee754"),g=t("int64-buffer"),v=g.Uint64BE,b=g.Int64BE,w=t("./write-uint8").uint8,E=t("./bufferish"),Buffer=E.global,A=E.hasBuffer&&"TYPED_ARRAY_SUPPORT"in Buffer,m=A&&!Buffer.TYPED_ARRAY_SUPPORT,x=E.hasBuffer&&Buffer.prototype||{};e.getWriteToken=n},{"./bufferish":8,"./write-uint8":28,ieee754:32,"int64-buffer":33}],27:[function(t,r,e){function n(t){function r(t,r){_[r?195:194](t,r)}function e(t,r){var e,n=0|r;if(r!==n)return e=203,void _[e](t,r);e=-32<=n&&n<=127?255&n:0<=n?n<=255?204:n<=65535?205:206:-128<=n?208:-32768<=n?209:210,_[e](t,n)}function n(t,r){_[207](t,r.toArray())}function o(t,r){_[211](t,r.toArray())}function g(t){return t<32?1:t<=255?2:t<=65535?3:5}function v(t){return t<32?1:t<=65535?3:5}function b(t,r){var e=t.codec.getExtPacker(r);return e&&(r=e(r)),r instanceof l?U(t,r):A(t,r)}function w(t,r){if(null===r)return A(t,r);if(I(r))return Y(t,r);if(i(r))return m(t,r);if(f.isUint64BE(r))return n(t,r);if(u.isInt64BE(r))return o(t,r);var e=t.codec.getExtPacker(r);if(e&&(r=e(r)),r instanceof l)return U(t,r);D(t,r)}function E(t,r){if(I(r))return k(t,r);w(t,r)}function A(t,r){_[192](t,r)}function m(t,r){var e=r.length;_[e<16?144+e:e<=65535?220:221](t,e);for(var n=t.codec.encode,i=0;i0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[r-2]?2:"="===t[r-1]?1:0}function i(t){return 3*t.length/4-n(t)}function o(t){var r,e,i,o,f,u=t.length;o=n(t),f=new h(3*u/4-o),e=o>0?u-4:u;var a=0;for(r=0;r>16&255,f[a++]=i>>8&255,f[a++]=255&i;return 2===o?(i=c[t.charCodeAt(r)]<<2|c[t.charCodeAt(r+1)]>>4,f[a++]=255&i):1===o&&(i=c[t.charCodeAt(r)]<<10|c[t.charCodeAt(r+1)]<<4|c[t.charCodeAt(r+2)]>>2,f[a++]=i>>8&255,f[a++]=255&i),f}function f(t){return s[t>>18&63]+s[t>>12&63]+s[t>>6&63]+s[63&t]}function u(t,r,e){for(var n,i=[],o=r;oa?a:f+16383));return 1===n?(r=t[e-1],i+=s[r>>2],i+=s[r<<4&63],i+="=="):2===n&&(r=(t[e-2]<<8)+t[e-1],i+=s[r>>10],i+=s[r>>4&63],i+=s[r<<2&63],i+="="),o.push(i),o.join("")}e.byteLength=i,e.toByteArray=o,e.fromByteArray=a;for(var s=[],c=[],h="undefined"!=typeof Uint8Array?Uint8Array:Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,d=l.length;p=n())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n().toString(16)+" bytes");return 0|t}function d(t){return+t!=t&&(t=0),Buffer.alloc(+t)}function y(t,r){if(Buffer.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return J(t).length;default:if(n)return V(t).length;r=(""+r).toLowerCase(),n=!0}}function g(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if(e>>>=0,r>>>=0,e<=r)return"";for(t||(t="utf8");;)switch(t){case"hex":return S(this,r,e);case"utf8":case"utf-8":return R(this,r,e);case"ascii":return _(this,r,e);case"latin1":case"binary":return T(this,r,e);case"base64":return P(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function v(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function b(t,r,e,n,i){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof r&&(r=Buffer.from(r,n)),Buffer.isBuffer(r))return 0===r.length?-1:w(t,r,e,n,i);if("number"==typeof r)return r&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):w(t,[r],e,n,i);throw new TypeError("val must be string, number or Buffer")}function w(t,r,e,n,i){function o(t,r){return 1===f?t[r]:t.readUInt16BE(r*f)}var f=1,u=t.length,a=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;f=2,u/=2,a/=2,e/=2}var s;if(i){var c=-1;for(s=e;su&&(e=u-a),s=e;s>=0;s--){for(var h=!0,l=0;li&&(n=i):n=i;var o=r.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var f=0;f239?4:o>223?3:o>191?2:1;if(i+u<=e){var a,s,c,h;switch(u){case 1:o<128&&(f=o);break;case 2:a=t[i+1],128==(192&a)&&(h=(31&o)<<6|63&a)>127&&(f=h);break;case 3:a=t[i+1],s=t[i+2],128==(192&a)&&128==(192&s)&&(h=(15&o)<<12|(63&a)<<6|63&s)>2047&&(h<55296||h>57343)&&(f=h);break;case 4:a=t[i+1],s=t[i+2],c=t[i+3],128==(192&a)&&128==(192&s)&&128==(192&c)&&(h=(15&o)<<18|(63&a)<<12|(63&s)<<6|63&c)>65535&&h<1114112&&(f=h)}}null===f?(f=65533,u=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=u}return k(n)}function k(t){var r=t.length;if(r<=Q)return String.fromCharCode.apply(String,t);for(var e="",n=0;nn)&&(e=n);for(var i="",o=r;oe)throw new RangeError("Trying to access beyond buffer length")}function C(t,r,e,n,i,o){if(!Buffer.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>i||rt.length)throw new RangeError("Index out of range")}function D(t,r,e,n){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-e,2);i>>8*(n?i:1-i)}function O(t,r,e,n){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-e,4);i>>8*(n?i:3-i)&255}function L(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function M(t,r,e,n,i){return i||L(t,r,e,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(t,r,e,n,23,4),e+4}function N(t,r,e,n,i){return i||L(t,r,e,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(t,r,e,n,52,8),e+8}function F(t){if(t=j(t).replace($,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function j(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function z(t){return t<16?"0"+t.toString(16):t.toString(16)}function V(t,r){r=r||1/0;for(var e,n=t.length,i=null,o=[],f=0;f55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(f+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function q(t){for(var r=[],e=0;e>8,i=e%256,o.push(i),o.push(n);return o}function J(t){return H.toByteArray(F(t))}function X(t,r,e,n){for(var i=0;i=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function G(t){return t!==t}var H=t("base64-js"),Z=t("ieee754"),K=t("isarray");e.Buffer=Buffer,e.SlowBuffer=d,e.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==r.TYPED_ARRAY_SUPPORT?r.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=n(),Buffer.poolSize=8192,Buffer._augment=function(t){return t.__proto__=Buffer.prototype,t},Buffer.from=function(t,r,e){return o(null,t,r,e)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(t,r,e){return u(null,t,r,e)},Buffer.allocUnsafe=function(t){return a(null,t)},Buffer.allocUnsafeSlow=function(t){return a(null,t)},Buffer.isBuffer=function(t){return!(null==t||!t._isBuffer)},Buffer.compare=function(t,r){if(!Buffer.isBuffer(t)||!Buffer.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(t===r)return 0;for(var e=t.length,n=r.length,i=0,o=Math.min(e,n);i0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),""},Buffer.prototype.compare=function(t,r,e,n,i){if(!Buffer.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||e>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&r>=e)return 0;if(n>=i)return-1;if(r>=e)return 1;if(r>>>=0,e>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,f=e-r,u=Math.min(o,f),a=this.slice(n,i),s=t.slice(r,e),c=0;ci)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return E(this,t,r,e);case"utf8":case"utf-8":return A(this,t,r,e);case"ascii":return m(this,t,r,e);case"latin1":case"binary":return x(this,t,r,e);case"base64":return B(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;Buffer.prototype.slice=function(t,r){var e=this.length;t=~~t,r=void 0===r?e:~~r,t<0?(t+=e)<0&&(t=0):t>e&&(t=e),r<0?(r+=e)<0&&(r=0):r>e&&(r=e),r0&&(i*=256);)n+=this[t+--r]*i;return n},Buffer.prototype.readUInt8=function(t,r){return r||Y(t,1,this.length),this[t]},Buffer.prototype.readUInt16LE=function(t,r){return r||Y(t,2,this.length),this[t]|this[t+1]<<8},Buffer.prototype.readUInt16BE=function(t,r){return r||Y(t,2,this.length),this[t]<<8|this[t+1]},Buffer.prototype.readUInt32LE=function(t,r){return r||Y(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Buffer.prototype.readUInt32BE=function(t,r){return r||Y(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Buffer.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||Y(t,r,this.length);for(var n=this[t],i=1,o=0;++o=i&&(n-=Math.pow(2,8*r)),n},Buffer.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||Y(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*r)),o},Buffer.prototype.readInt8=function(t,r){return r||Y(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Buffer.prototype.readInt16LE=function(t,r){r||Y(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},Buffer.prototype.readInt16BE=function(t,r){r||Y(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},Buffer.prototype.readInt32LE=function(t,r){return r||Y(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Buffer.prototype.readInt32BE=function(t,r){return r||Y(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Buffer.prototype.readFloatLE=function(t,r){return r||Y(t,4,this.length),Z.read(this,t,!0,23,4)},Buffer.prototype.readFloatBE=function(t,r){return r||Y(t,4,this.length),Z.read(this,t,!1,23,4)},Buffer.prototype.readDoubleLE=function(t,r){return r||Y(t,8,this.length),Z.read(this,t,!0,52,8)},Buffer.prototype.readDoubleBE=function(t,r){return r||Y(t,8,this.length),Z.read(this,t,!1,52,8)},Buffer.prototype.writeUIntLE=function(t,r,e,n){if(t=+t,r|=0,e|=0,!n){C(this,t,r,e,Math.pow(2,8*e)-1,0)}var i=1,o=0;for(this[r]=255&t;++o=0&&(o*=256);)this[r+i]=t/o&255;return r+e},Buffer.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},Buffer.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):D(this,t,r,!0),r+2},Buffer.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):D(this,t,r,!1),r+2},Buffer.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):O(this,t,r,!0),r+4},Buffer.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):O(this,t,r,!1),r+4},Buffer.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);C(this,t,r,e,i-1,-i)}var o=0,f=1,u=0;for(this[r]=255&t;++o>0)-u&255;return r+e},Buffer.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);C(this,t,r,e,i-1,-i)}var o=e-1,f=1,u=0;for(this[r+o]=255&t;--o>=0&&(f*=256);)t<0&&0===u&&0!==this[r+o+1]&&(u=1),this[r+o]=(t/f>>0)-u&255;return r+e},Buffer.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},Buffer.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):D(this,t,r,!0),r+2},Buffer.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):D(this,t,r,!1),r+2},Buffer.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):O(this,t,r,!0),r+4},Buffer.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||C(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):O(this,t,r,!1),r+4},Buffer.prototype.writeFloatLE=function(t,r,e){return M(this,t,r,!0,e)},Buffer.prototype.writeFloatBE=function(t,r,e){return M(this,t,r,!1,e)},Buffer.prototype.writeDoubleLE=function(t,r,e){return N(this,t,r,!0,e)},Buffer.prototype.writeDoubleBE=function(t,r,e){return N(this,t,r,!1,e)},Buffer.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r=0;--i)t[i+r]=this[i+e];else if(o<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,e=void 0===e?this.length:e>>>0,t||(t=0);var o;if("number"==typeof t)for(o=r;o>1,c=-7,h=e?i-1:0,l=e?-1:1,p=t[r+h];for(h+=l,o=p&(1<<-c)-1,p>>=-c,c+=u;c>0;o=256*o+t[r+h],h+=l,c-=8);for(f=o&(1<<-c)-1,o>>=-c,c+=n;c>0;f=256*f+t[r+h],h+=l,c-=8);if(0===o)o=1-s;else{if(o===a)return f?NaN:1/0*(p?-1:1);f+=Math.pow(2,n),o-=s}return(p?-1:1)*f*Math.pow(2,o-n)},e.write=function(t,r,e,n,i,o){var f,u,a,s=8*o-i-1,c=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,y=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,f=c):(f=Math.floor(Math.log(r)/Math.LN2),r*(a=Math.pow(2,-f))<1&&(f--,a*=2),r+=f+h>=1?l/a:l*Math.pow(2,1-h),r*a>=2&&(f++,a/=2),f+h>=c?(u=0,f=c):f+h>=1?(u=(r*a-1)*Math.pow(2,i),f+=h):(u=r*Math.pow(2,h-1)*Math.pow(2,i),f=0));i>=8;t[e+p]=255&u,p+=d,u/=256,i-=8);for(f=f<0;t[e+p]=255&f,p+=d,f/=256,s-=8);t[e+p-d]|=128*y}},{}],33:[function(t,r,e){(function(Buffer){var t,r,n,i;!function(e){function o(t,r,n){function i(t,r,e,n){return this instanceof i?g(this,t,r,e,n):new i(t,r,e,n)}function o(t){return!(!t||!t[F])}function g(t,r,e,n,i){if(E&&A&&(r instanceof A&&(r=new E(r)),n instanceof A&&(n=new E(n))),!(r||e||n||v))return void(t.buffer=h(m,0));if(!s(r,e)){var o=v||Array;i=e,n=r,e=0,r=new o(8)}t.buffer=r,t.offset=e|=0,b!==typeof n&&("string"==typeof n?x(r,e,n,i||10):s(n,i)?c(r,e,n,i):"number"==typeof i?(k(r,e+T,n),k(r,e+S,i)):n>0?O(r,e,n):n<0?L(r,e,n):c(r,e,m,0))}function x(t,r,e,n){var i=0,o=e.length,f=0,u=0;"-"===e[0]&&i++;for(var a=i;i=0))break;u=u*n+s,f=f*n+Math.floor(u/B),u%=B}a&&(f=~f,u?u=B-u:f++),k(t,r+T,f),k(t,r+S,u)}function P(){var t=this.buffer,r=this.offset,e=_(t,r+T),i=_(t,r+S);return n||(e|=0),e?e*B+i:i}function R(t){var r=this.buffer,e=this.offset,i=_(r,e+T),o=_(r,e+S),f="",u=!n&&2147483648&i;for(u&&(i=~i,o=B-o),t=t||10;;){var a=i%t*B+o;if(i=Math.floor(i/t),o=Math.floor(a/t),f=(a%t).toString(t)+f,!i&&!o)break}return u&&(f="-"+f),f}function k(t,r,e){t[r+D]=255&e,e>>=8,t[r+C]=255&e,e>>=8,t[r+Y]=255&e,e>>=8,t[r+I]=255&e}function _(t,r){return t[r+I]*U+(t[r+Y]<<16)+(t[r+C]<<8)+t[r+D]}var T=r?0:4,S=r?4:0,I=r?0:3,Y=r?1:2,C=r?2:1,D=r?3:0,O=r?l:d,L=r?p:y,M=i.prototype,N="is"+t,F="_"+N;return M.buffer=void 0,M.offset=0,M[F]=!0,M.toNumber=P,M.toString=R,M.toJSON=P,M.toArray=f,w&&(M.toBuffer=u),E&&(M.toArrayBuffer=a),i[N]=o,e[t]=i,i}function f(t){var r=this.buffer,e=this.offset;return v=null,!1!==t&&0===e&&8===r.length&&x(r)?r:h(r,e)}function u(t){var r=this.buffer,e=this.offset;if(v=w,!1!==t&&0===e&&8===r.length&&Buffer.isBuffer(r))return r;var n=new w(8);return c(n,0,r,e),n}function a(t){var r=this.buffer,e=this.offset,n=r.buffer;if(v=E,!1!==t&&0===e&&n instanceof A&&8===n.byteLength)return n;var i=new E(8);return c(i,0,r,e),i.buffer}function s(t,r){var e=t&&t.length;return r|=0,e&&r+8<=e&&"string"!=typeof t[r]}function c(t,r,e,n){r|=0,n|=0;for(var i=0;i<8;i++)t[r++]=255&e[n++]}function h(t,r){return Array.prototype.slice.call(t,r,r+8)}function l(t,r,e){for(var n=r+8;n>r;)t[--n]=255&e,e/=256}function p(t,r,e){var n=r+8;for(e++;n>r;)t[--n]=255&-e^255,e/=256}function d(t,r,e){for(var n=r+8;r { + clearSource(); + return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options) + }) + } + if (!source.buffer && source.constructor === ArrayBuffer) + source = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source); + if (typeof options === 'object') { + srcEnd = options.end || source.length; + position$1 = options.start || 0; + } else { + position$1 = 0; + srcEnd = options > -1 ? options : source.length; + } + srcStringEnd = 0; + srcString = null; + bundledStrings$1 = null; + src = source; + // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend + // technique for getting data from a database where it can be copied into an existing buffer instead of creating + // new ones + try { + dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength)); + } catch(error) { + // if it doesn't have a buffer, maybe it is the wrong type of object + src = null; + if (source instanceof Uint8Array) + throw error + throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source)) + } + if (this instanceof Unpackr) { + currentUnpackr = this; + if (this.structures) { + currentStructures = this.structures; + return checkedRead(options) + } else if (!currentStructures || currentStructures.length > 0) { + currentStructures = []; + } + } else { + currentUnpackr = defaultOptions; + if (!currentStructures || currentStructures.length > 0) + currentStructures = []; + } + return checkedRead(options) + } + unpackMultiple(source, forEach) { + let values, lastPosition = 0; + try { + sequentialMode = true; + let size = source.length; + let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size); + if (forEach) { + if (forEach(value, lastPosition, position$1) === false) return; + while(position$1 < size) { + lastPosition = position$1; + if (forEach(checkedRead(), lastPosition, position$1) === false) { + return + } + } + } + else { + values = [ value ]; + while(position$1 < size) { + lastPosition = position$1; + values.push(checkedRead()); + } + return values + } + } catch(error) { + error.lastPosition = lastPosition; + error.values = values; + throw error + } finally { + sequentialMode = false; + clearSource(); + } + } + _mergeStructures(loadedStructures, existingStructures) { + loadedStructures = loadedStructures || []; + if (Object.isFrozen(loadedStructures)) + loadedStructures = loadedStructures.map(structure => structure.slice(0)); + for (let i = 0, l = loadedStructures.length; i < l; i++) { + let structure = loadedStructures[i]; + if (structure) { + structure.isShared = true; + if (i >= 32) + structure.highByte = (i - 32) >> 5; + } + } + loadedStructures.sharedLength = loadedStructures.length; + for (let id in existingStructures || []) { + if (id >= 0) { + let structure = loadedStructures[id]; + let existing = existingStructures[id]; + if (existing) { + if (structure) + (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure; + loadedStructures[id] = existing; + } + } + } + return this.structures = loadedStructures + } + decode(source, options) { + return this.unpack(source, options) + } + } + function checkedRead(options) { + try { + if (!currentUnpackr.trusted && !sequentialMode) { + let sharedLength = currentStructures.sharedLength || 0; + if (sharedLength < currentStructures.length) + currentStructures.length = sharedLength; + } + let result; + if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct) { + result = readStruct(src, position$1, srcEnd, currentUnpackr); + src = null; // dispose of this so that recursive unpack calls don't save state + if (!(options && options.lazy) && result) + result = result.toJSON(); + position$1 = srcEnd; + } else + result = read(); + if (bundledStrings$1) { // bundled strings to skip past + position$1 = bundledStrings$1.postBundlePosition; + bundledStrings$1 = null; + } + if (sequentialMode) + // we only need to restore the structures if there was an error, but if we completed a read, + // we can clear this out and keep the structures we read + currentStructures.restoreStructures = null; + + if (position$1 == srcEnd) { + // finished reading this source, cleanup references + if (currentStructures && currentStructures.restoreStructures) + restoreStructures(); + currentStructures = null; + src = null; + if (referenceMap) + referenceMap = null; + } else if (position$1 > srcEnd) { + // over read + throw new Error('Unexpected end of MessagePack data') + } else if (!sequentialMode) { + let jsonView; + try { + jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100); + } catch(error) { + jsonView = '(JSON view not available ' + error + ')'; + } + throw new Error('Data read, but end of buffer not reached ' + jsonView) + } + // else more to read, but we are reading sequentially, so don't clear source yet + return result + } catch(error) { + if (currentStructures && currentStructures.restoreStructures) + restoreStructures(); + clearSource(); + if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) { + error.incomplete = true; + } + throw error + } + } + + function restoreStructures() { + for (let id in currentStructures.restoreStructures) { + currentStructures[id] = currentStructures.restoreStructures[id]; + } + currentStructures.restoreStructures = null; + } + + function read() { + let token = src[position$1++]; + if (token < 0xa0) { + if (token < 0x80) { + if (token < 0x40) + return token + else { + let structure = currentStructures[token & 0x3f] || + currentUnpackr.getStructures && loadStructures()[token & 0x3f]; + if (structure) { + if (!structure.read) { + structure.read = createStructureReader(structure, token & 0x3f); + } + return structure.read() + } else + return token + } + } else if (token < 0x90) { + // map + token -= 0x80; + if (currentUnpackr.mapsAsObjects) { + let object = {}; + for (let i = 0; i < token; i++) { + let key = readKey(); + if (key === '__proto__') + key = '__proto_'; + object[key] = read(); + } + return object + } else { + let map = new Map(); + for (let i = 0; i < token; i++) { + map.set(read(), read()); + } + return map + } + } else { + token -= 0x90; + let array = new Array(token); + for (let i = 0; i < token; i++) { + array[i] = read(); + } + if (currentUnpackr.freezeData) + return Object.freeze(array) + return array + } + } else if (token < 0xc0) { + // fixstr + let length = token - 0xa0; + if (srcStringEnd >= position$1) { + return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart) + } + if (srcStringEnd == 0 && srcEnd < 140) { + // for small blocks, avoiding the overhead of the extract call is helpful + let string = length < 16 ? shortStringInJS(length) : longStringInJS(length); + if (string != null) + return string + } + return readFixedString(length) + } else { + let value; + switch (token) { + case 0xc0: return null + case 0xc1: + if (bundledStrings$1) { + value = read(); // followed by the length of the string in characters (not bytes!) + if (value > 0) + return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value) + else + return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value) + } + return C1; // "never-used", return special object to denote that + case 0xc2: return false + case 0xc3: return true + case 0xc4: + // bin 8 + value = src[position$1++]; + if (value === undefined) + throw new Error('Unexpected end of buffer') + return readBin(value) + case 0xc5: + // bin 16 + value = dataView.getUint16(position$1); + position$1 += 2; + return readBin(value) + case 0xc6: + // bin 32 + value = dataView.getUint32(position$1); + position$1 += 4; + return readBin(value) + case 0xc7: + // ext 8 + return readExt(src[position$1++]) + case 0xc8: + // ext 16 + value = dataView.getUint16(position$1); + position$1 += 2; + return readExt(value) + case 0xc9: + // ext 32 + value = dataView.getUint32(position$1); + position$1 += 4; + return readExt(value) + case 0xca: + value = dataView.getFloat32(position$1); + if (currentUnpackr.useFloat32 > 2) { + // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved + let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)]; + position$1 += 4; + return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier + } + position$1 += 4; + return value + case 0xcb: + value = dataView.getFloat64(position$1); + position$1 += 8; + return value + // uint handlers + case 0xcc: + return src[position$1++] + case 0xcd: + value = dataView.getUint16(position$1); + position$1 += 2; + return value + case 0xce: + value = dataView.getUint32(position$1); + position$1 += 4; + return value + case 0xcf: + if (currentUnpackr.int64AsType === 'number') { + value = dataView.getUint32(position$1) * 0x100000000; + value += dataView.getUint32(position$1 + 4); + } else if (currentUnpackr.int64AsType === 'string') { + value = dataView.getBigUint64(position$1).toString(); + } else if (currentUnpackr.int64AsType === 'auto') { + value = dataView.getBigUint64(position$1); + if (value<=BigInt(2)<=BigInt(-2)<= position$1) { + return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart) + } + return readString8(value) + case 0xda: + // str 16 + value = dataView.getUint16(position$1); + position$1 += 2; + if (srcStringEnd >= position$1) { + return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart) + } + return readString16(value) + case 0xdb: + // str 32 + value = dataView.getUint32(position$1); + position$1 += 4; + if (srcStringEnd >= position$1) { + return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart) + } + return readString32(value) + case 0xdc: + // array 16 + value = dataView.getUint16(position$1); + position$1 += 2; + return readArray(value) + case 0xdd: + // array 32 + value = dataView.getUint32(position$1); + position$1 += 4; + return readArray(value) + case 0xde: + // map 16 + value = dataView.getUint16(position$1); + position$1 += 2; + return readMap(value) + case 0xdf: + // map 32 + value = dataView.getUint32(position$1); + position$1 += 4; + return readMap(value) + default: // negative int + if (token >= 0xe0) + return token - 0x100 + if (token === undefined) { + let error = new Error('Unexpected end of MessagePack data'); + error.incomplete = true; + throw error + } + throw new Error('Unknown MessagePack token ' + token) + + } + } + } + const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/; + function createStructureReader(structure, firstId) { + function readObject() { + // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function + if (readObject.count++ > inlineObjectReadThreshold) { + let readObject = structure.read = (new BlockedFunction ('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') + + '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read); + if (structure.highByte === 0) + structure.read = createSecondByteReader(firstId, structure.read); + return readObject() // second byte is already read, if there is one so immediately read object + } + let object = {}; + for (let i = 0, l = structure.length; i < l; i++) { + let key = structure[i]; + if (key === '__proto__') + key = '__proto_'; + object[key] = read(); + } + if (currentUnpackr.freezeData) + return Object.freeze(object); + return object + } + readObject.count = 0; + if (structure.highByte === 0) { + return createSecondByteReader(firstId, readObject) + } + return readObject + } + + const createSecondByteReader = (firstId, read0) => { + return function() { + let highByte = src[position$1++]; + if (highByte === 0) + return read0() + let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5); + let structure = currentStructures[id] || loadStructures()[id]; + if (!structure) { + throw new Error('Record id is not defined for ' + id) + } + if (!structure.read) + structure.read = createStructureReader(structure, firstId); + return structure.read() + } + }; + + function loadStructures() { + let loadedStructures = saveState(() => { + // save the state in case getStructures modifies our buffer + src = null; + return currentUnpackr.getStructures() + }); + return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures) + } + + var readFixedString = readStringJS; + var readString8 = readStringJS; + var readString16 = readStringJS; + var readString32 = readStringJS; + let isNativeAccelerationEnabled = false; + function readStringJS(length) { + let result; + if (length < 16) { + if (result = shortStringInJS(length)) + return result + } + if (length > 64 && decoder) + return decoder.decode(src.subarray(position$1, position$1 += length)) + const end = position$1 + length; + const units = []; + result = ''; + while (position$1 < end) { + const byte1 = src[position$1++]; + if ((byte1 & 0x80) === 0) { + // 1 byte + units.push(byte1); + } else if ((byte1 & 0xe0) === 0xc0) { + // 2 bytes + const byte2 = src[position$1++] & 0x3f; + units.push(((byte1 & 0x1f) << 6) | byte2); + } else if ((byte1 & 0xf0) === 0xe0) { + // 3 bytes + const byte2 = src[position$1++] & 0x3f; + const byte3 = src[position$1++] & 0x3f; + units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3); + } else if ((byte1 & 0xf8) === 0xf0) { + // 4 bytes + const byte2 = src[position$1++] & 0x3f; + const byte3 = src[position$1++] & 0x3f; + const byte4 = src[position$1++] & 0x3f; + let 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 >= 0x1000) { + result += fromCharCode.apply(String, units); + units.length = 0; + } + } + + if (units.length > 0) { + result += fromCharCode.apply(String, units); + } + + return result + } + + function readArray(length) { + let array = new Array(length); + for (let i = 0; i < length; i++) { + array[i] = read(); + } + if (currentUnpackr.freezeData) + return Object.freeze(array) + return array + } + + function readMap(length) { + if (currentUnpackr.mapsAsObjects) { + let object = {}; + for (let i = 0; i < length; i++) { + let key = readKey(); + if (key === '__proto__') + key = '__proto_'; + object[key] = read(); + } + return object + } else { + let map = new Map(); + for (let i = 0; i < length; i++) { + map.set(read(), read()); + } + return map + } + } + + var fromCharCode = String.fromCharCode; + function longStringInJS(length) { + let start = position$1; + let bytes = new Array(length); + for (let i = 0; i < length; i++) { + const byte = src[position$1++]; + if ((byte & 0x80) > 0) { + position$1 = start; + return + } + bytes[i] = byte; + } + return fromCharCode.apply(String, bytes) + } + function shortStringInJS(length) { + if (length < 4) { + if (length < 2) { + if (length === 0) + return '' + else { + let a = src[position$1++]; + if ((a & 0x80) > 1) { + position$1 -= 1; + return + } + return fromCharCode(a) + } + } else { + let a = src[position$1++]; + let b = src[position$1++]; + if ((a & 0x80) > 0 || (b & 0x80) > 0) { + position$1 -= 2; + return + } + if (length < 3) + return fromCharCode(a, b) + let c = src[position$1++]; + if ((c & 0x80) > 0) { + position$1 -= 3; + return + } + return fromCharCode(a, b, c) + } + } else { + let a = src[position$1++]; + let b = src[position$1++]; + let c = src[position$1++]; + let d = src[position$1++]; + if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) { + position$1 -= 4; + return + } + if (length < 6) { + if (length === 4) + return fromCharCode(a, b, c, d) + else { + let e = src[position$1++]; + if ((e & 0x80) > 0) { + position$1 -= 5; + return + } + return fromCharCode(a, b, c, d, e) + } + } else if (length < 8) { + let e = src[position$1++]; + let f = src[position$1++]; + if ((e & 0x80) > 0 || (f & 0x80) > 0) { + position$1 -= 6; + return + } + if (length < 7) + return fromCharCode(a, b, c, d, e, f) + let g = src[position$1++]; + if ((g & 0x80) > 0) { + position$1 -= 7; + return + } + return fromCharCode(a, b, c, d, e, f, g) + } else { + let e = src[position$1++]; + let f = src[position$1++]; + let g = src[position$1++]; + let h = src[position$1++]; + if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) { + position$1 -= 8; + return + } + if (length < 10) { + if (length === 8) + return fromCharCode(a, b, c, d, e, f, g, h) + else { + let i = src[position$1++]; + if ((i & 0x80) > 0) { + position$1 -= 9; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i) + } + } else if (length < 12) { + let i = src[position$1++]; + let j = src[position$1++]; + if ((i & 0x80) > 0 || (j & 0x80) > 0) { + position$1 -= 10; + return + } + if (length < 11) + return fromCharCode(a, b, c, d, e, f, g, h, i, j) + let k = src[position$1++]; + if ((k & 0x80) > 0) { + position$1 -= 11; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k) + } else { + let i = src[position$1++]; + let j = src[position$1++]; + let k = src[position$1++]; + let l = src[position$1++]; + if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) { + position$1 -= 12; + return + } + if (length < 14) { + if (length === 12) + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l) + else { + let m = src[position$1++]; + if ((m & 0x80) > 0) { + position$1 -= 13; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m) + } + } else { + let m = src[position$1++]; + let n = src[position$1++]; + if ((m & 0x80) > 0 || (n & 0x80) > 0) { + position$1 -= 14; + return + } + if (length < 15) + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n) + let o = src[position$1++]; + if ((o & 0x80) > 0) { + position$1 -= 15; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) + } + } + } + } + } + + function readOnlyJSString() { + let token = src[position$1++]; + let length; + if (token < 0xc0) { + // fixstr + length = token - 0xa0; + } else { + switch(token) { + case 0xd9: + // str 8 + length = src[position$1++]; + break + case 0xda: + // str 16 + length = dataView.getUint16(position$1); + position$1 += 2; + break + case 0xdb: + // str 32 + length = dataView.getUint32(position$1); + position$1 += 4; + break + default: + throw new Error('Expected string') + } + } + return readStringJS(length) + } + + + function readBin(length) { + return currentUnpackr.copyBuffers ? + // specifically use the copying slice (not the node one) + Uint8Array.prototype.slice.call(src, position$1, position$1 += length) : + src.subarray(position$1, position$1 += length) + } + function readExt(length) { + let type = src[position$1++]; + if (currentExtensions[type]) { + let end; + return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => { + position$1 = readPosition; + try { + return read(); + } finally { + position$1 = end; + } + }) + } + else + throw new Error('Unknown extension type ' + type) + } + + var keyCache = new Array(4096); + function readKey() { + let length = src[position$1++]; + if (length >= 0xa0 && length < 0xc0) { + // fixstr, potentially use key cache + length = length - 0xa0; + if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway) + return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart) + else if (!(srcStringEnd == 0 && srcEnd < 180)) + return readFixedString(length) + } else { // not cacheable, go back and do a standard read + position$1--; + return asSafeString(read()) + } + let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff; + let entry = keyCache[key]; + let checkPosition = position$1; + let end = position$1 + length - 3; + let chunk; + let i = 0; + if (entry && entry.bytes == length) { + while (checkPosition < end) { + chunk = dataView.getUint32(checkPosition); + if (chunk != entry[i++]) { + checkPosition = 0x70000000; + break + } + checkPosition += 4; + } + end += 3; + while (checkPosition < end) { + chunk = src[checkPosition++]; + if (chunk != entry[i++]) { + checkPosition = 0x70000000; + break + } + } + if (checkPosition === end) { + position$1 = checkPosition; + return entry.string + } + end -= 3; + checkPosition = position$1; + } + entry = []; + keyCache[key] = entry; + entry.bytes = length; + while (checkPosition < end) { + chunk = dataView.getUint32(checkPosition); + entry.push(chunk); + checkPosition += 4; + } + end += 3; + while (checkPosition < end) { + chunk = src[checkPosition++]; + entry.push(chunk); + } + // for small blocks, avoiding the overhead of the extract call is helpful + let string = length < 16 ? shortStringInJS(length) : longStringInJS(length); + if (string != null) + return entry.string = string + return entry.string = readFixedString(length) + } + + function asSafeString(property) { + // protect against expensive (DoS) string conversions + if (typeof property === 'string') return property; + if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString(); + if (property == null) return property + ''; + throw new Error('Invalid property type for record', typeof property); + } + // the registration of the record definition extension (as "r") + const recordDefinition = (id, highByte) => { + let structure = read().map(asSafeString); // ensure that all keys are strings and + // that the array is mutable + let firstByte = id; + if (highByte !== undefined) { + id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id); + structure.highByte = highByte; + } + let existingStructure = currentStructures[id]; + // If it is a shared structure, we need to restore any changes after reading. + // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore + // to the state prior to an incomplete read in order to properly resume. + if (existingStructure && (existingStructure.isShared || sequentialMode)) { + (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure; + } + currentStructures[id] = structure; + structure.read = createStructureReader(structure, firstByte); + return structure.read() + }; + currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here + currentExtensions[0].noBuffer = true; + + currentExtensions[0x42] = (data) => { + // decode bigint + let length = data.length; + let value = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]); + for (let i = 1; i < length; i++) { + value <<= BigInt(8); + value += BigInt(data[i]); + } + return value; + }; + + let errors = { Error, TypeError, ReferenceError }; + currentExtensions[0x65] = () => { + let data = read(); + return (errors[data[0]] || Error)(data[1], { cause: data[2] }) + }; + + currentExtensions[0x69] = (data) => { + // id extension (for structured clones) + if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled') + let id = dataView.getUint32(position$1 - 4); + if (!referenceMap) + referenceMap = new Map(); + let token = src[position$1]; + let target; + // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read + // ahead past references to record structure definitions + if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd) + target = []; + else + target = {}; + + let refEntry = { target }; // a placeholder object + referenceMap.set(id, refEntry); + let targetProperties = read(); // read the next value as the target object to id + if (refEntry.used) // there is a cycle, so we have to assign properties to original target + return Object.assign(target, targetProperties) + refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one + return targetProperties // no cycle, can just use the returned read object + }; + + currentExtensions[0x70] = (data) => { + // pointer extension (for structured clones) + if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled') + let id = dataView.getUint32(position$1 - 4); + let refEntry = referenceMap.get(id); + refEntry.used = true; + return refEntry.target + }; + + currentExtensions[0x73] = () => new Set(read()); + + const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array'); + + let glbl = typeof globalThis === 'object' ? globalThis : window; + currentExtensions[0x74] = (data) => { + let typeCode = data[0]; + let typedArrayName = typedArrays[typeCode]; + if (!typedArrayName) { + if (typeCode === 16) { + let ab = new ArrayBuffer(data.length - 1); + let u8 = new Uint8Array(ab); + u8.set(data.subarray(1)); + return ab; + } + throw new Error('Could not find typed array for code ' + typeCode) + } + // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned + return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer) + }; + currentExtensions[0x78] = () => { + let data = read(); + return new RegExp(data[0], data[1]) + }; + const TEMP_BUNDLE = []; + currentExtensions[0x62] = (data) => { + let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; + let dataPosition = position$1; + position$1 += dataSize - data.length; + bundledStrings$1 = TEMP_BUNDLE; + bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()]; + bundledStrings$1.position0 = 0; + bundledStrings$1.position1 = 0; + bundledStrings$1.postBundlePosition = position$1; + position$1 = dataPosition; + return read() + }; + + currentExtensions[0xff] = (data) => { + // 32-bit date extension + if (data.length == 4) + return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000) + else if (data.length == 8) + return new Date( + ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 + + ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000) + else if (data.length == 12)// TODO: Implement support for negative + return new Date( + ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 + + (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000) + else + return new Date('invalid') + }; // notepack defines extension 0 to mean undefined, so use that as the default here + // registration of bulk record definition? + // currentExtensions[0x52] = () => + + function saveState(callback) { + let savedSrcEnd = srcEnd; + let savedPosition = position$1; + let savedSrcStringStart = srcStringStart; + let savedSrcStringEnd = srcStringEnd; + let savedSrcString = srcString; + let savedReferenceMap = referenceMap; + let savedBundledStrings = bundledStrings$1; + + // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow) + let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed + let savedStructures = currentStructures; + let savedStructuresContents = currentStructures.slice(0, currentStructures.length); + let savedPackr = currentUnpackr; + let savedSequentialMode = sequentialMode; + let value = callback(); + srcEnd = savedSrcEnd; + position$1 = savedPosition; + srcStringStart = savedSrcStringStart; + srcStringEnd = savedSrcStringEnd; + srcString = savedSrcString; + referenceMap = savedReferenceMap; + bundledStrings$1 = savedBundledStrings; + src = savedSrc; + sequentialMode = savedSequentialMode; + currentStructures = savedStructures; + currentStructures.splice(0, currentStructures.length, ...savedStructuresContents); + currentUnpackr = savedPackr; + dataView = new DataView(src.buffer, src.byteOffset, src.byteLength); + return value + } + function clearSource() { + src = null; + referenceMap = null; + currentStructures = null; + } + + function addExtension$1(extension) { + if (extension.unpack) + currentExtensions[extension.type] = extension.unpack; + else + currentExtensions[extension.type] = extension; + } + + const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding + for (let i = 0; i < 256; i++) { + mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103)); + } + const Decoder = Unpackr; + var defaultUnpackr = new Unpackr({ useRecords: false }); + const unpack = defaultUnpackr.unpack; + const unpackMultiple = defaultUnpackr.unpackMultiple; + const decode = defaultUnpackr.unpack; + const FLOAT32_OPTIONS = { + NEVER: 0, + ALWAYS: 1, + DECIMAL_ROUND: 3, + DECIMAL_FIT: 4 + }; + let f32Array = new Float32Array(1); + let u8Array = new Uint8Array(f32Array.buffer, 0, 4); + function roundFloat32(float32Number) { + f32Array[0] = float32Number; + let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)]; + return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier + } + + let textEncoder; + try { + textEncoder = new TextEncoder(); + } catch (error) {} + let extensions, extensionClasses; + const hasNodeBuffer = typeof Buffer !== 'undefined'; + const ByteArrayAllocate = hasNodeBuffer ? + function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array; + const ByteArray = hasNodeBuffer ? Buffer : Uint8Array; + const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000; + let target, keysTarget; + let targetView; + let position = 0; + let safeEnd; + let bundledStrings = null; + let writeStructSlots; + const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits. + const hasNonLatin = /[\u0080-\uFFFF]/; + const RECORD_SYMBOL = Symbol('record-id'); + class Packr extends Unpackr { + constructor(options) { + super(options); + this.offset = 0; + let start; + let hasSharedUpdate; + let structures; + let referenceMap; + let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) { + return target.utf8Write(string, position, target.byteLength - position) + } : (textEncoder && textEncoder.encodeInto) ? + function(string, position) { + return textEncoder.encodeInto(string, target.subarray(position)).written + } : false; + + let packr = this; + if (!options) + options = {}; + let isSequential = options && options.sequential; + let hasSharedStructures = options.structures || options.saveStructures; + let maxSharedStructures = options.maxSharedStructures; + if (maxSharedStructures == null) + maxSharedStructures = hasSharedStructures ? 32 : 0; + if (maxSharedStructures > 8160) + throw new Error('Maximum maxSharedStructure is 8160') + if (options.structuredClone && options.moreTypes == undefined) { + this.moreTypes = true; + } + let maxOwnStructures = options.maxOwnStructures; + if (maxOwnStructures == null) + maxOwnStructures = hasSharedStructures ? 32 : 64; + if (!this.structures && options.useRecords != false) + this.structures = []; + // two byte record ids for shared structures + let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64); + let sharedLimitId = maxSharedStructures + 0x40; + let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40; + if (maxStructureId > 8256) { + throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192') + } + let recordIdsToRemove = []; + let transitionsCount = 0; + let serializationsSinceTransitionRebuild = 0; + + this.pack = this.encode = function(value, encodeOptions) { + if (!target) { + target = new ByteArrayAllocate(8192); + targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192)); + position = 0; + } + safeEnd = target.length - 10; + if (safeEnd - position < 0x800) { + // don't start too close to the end, + target = new ByteArrayAllocate(target.length); + targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length)); + safeEnd = target.length - 10; + position = 0; + } else + position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster + start = position; + if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff); + referenceMap = packr.structuredClone ? new Map() : null; + if (packr.bundleStrings && typeof value !== 'string') { + bundledStrings = []; + bundledStrings.size = Infinity; // force a new bundle start on first string + } else + bundledStrings = null; + structures = packr.structures; + if (structures) { + if (structures.uninitialized) + structures = packr._mergeStructures(packr.getStructures()); + let sharedLength = structures.sharedLength || 0; + if (sharedLength > maxSharedStructures) { + //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids + throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength) + } + if (!structures.transitions) { + // rebuild our structure transitions + structures.transitions = Object.create(null); + for (let i = 0; i < sharedLength; i++) { + let keys = structures[i]; + if (!keys) + continue + let nextTransition, transition = structures.transitions; + for (let j = 0, l = keys.length; j < l; j++) { + let key = keys[j]; + nextTransition = transition[key]; + if (!nextTransition) { + nextTransition = transition[key] = Object.create(null); + } + transition = nextTransition; + } + transition[RECORD_SYMBOL] = i + 0x40; + } + this.lastNamedStructuresLength = sharedLength; + } + if (!isSequential) { + structures.nextId = sharedLength + 0x40; + } + } + if (hasSharedUpdate) + hasSharedUpdate = false; + let encodingError; + try { + if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object) + writeStruct(value); + else + pack(value); + let lastBundle = bundledStrings; + if (bundledStrings) + writeBundles(start, pack, 0); + if (referenceMap && referenceMap.idsToInsert) { + let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1); + let i = idsToInsert.length; + let incrementPosition = -1; + while (lastBundle && i > 0) { + let insertionPoint = idsToInsert[--i].offset + start; + if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1) + incrementPosition = 0; + if (insertionPoint > (lastBundle.position + start)) { + if (incrementPosition >= 0) + incrementPosition += 6; + } else { + if (incrementPosition >= 0) { + // update the bundle reference now + targetView.setUint32(lastBundle.position + start, + targetView.getUint32(lastBundle.position + start) + incrementPosition); + incrementPosition = -1; // reset + } + lastBundle = lastBundle.previous; + i++; + } + } + if (incrementPosition >= 0 && lastBundle) { + // update the bundle reference now + targetView.setUint32(lastBundle.position + start, + targetView.getUint32(lastBundle.position + start) + incrementPosition); + } + position += idsToInsert.length * 6; + if (position > safeEnd) + makeRoom(position); + packr.offset = position; + let serialized = insertIds(target.subarray(start, position), idsToInsert); + referenceMap = null; + return serialized + } + packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially + if (encodeOptions & REUSE_BUFFER_MODE) { + target.start = start; + target.end = position; + return target + } + return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now + } catch(error) { + encodingError = error; + throw error; + } finally { + if (structures) { + resetStructures(); + if (hasSharedUpdate && packr.saveStructures) { + let sharedLength = structures.sharedLength || 0; + // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save + let returnBuffer = target.subarray(start, position); + let newSharedData = prepareStructures(structures, packr); + if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time + if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) { + // get updated structures and try again if the update failed + return packr.pack(value, encodeOptions) + } + packr.lastNamedStructuresLength = sharedLength; + // don't keep large buffers around + if (target.length > 0x40000000) target = null; + return returnBuffer + } + } + } + // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB) + if (target.length > 0x40000000) target = null; + if (encodeOptions & RESET_BUFFER_MODE) + position = start; + } + }; + const resetStructures = () => { + if (serializationsSinceTransitionRebuild < 10) + serializationsSinceTransitionRebuild++; + let sharedLength = structures.sharedLength || 0; + if (structures.length > sharedLength && !isSequential) + structures.length = sharedLength; + if (transitionsCount > 10000) { + // force a rebuild occasionally after a lot of transitions so it can get cleaned up + structures.transitions = null; + serializationsSinceTransitionRebuild = 0; + transitionsCount = 0; + if (recordIdsToRemove.length > 0) + recordIdsToRemove = []; + } else if (recordIdsToRemove.length > 0 && !isSequential) { + for (let i = 0, l = recordIdsToRemove.length; i < l; i++) { + recordIdsToRemove[i][RECORD_SYMBOL] = 0; + } + recordIdsToRemove = []; + } + }; + const packArray = (value) => { + var length = value.length; + if (length < 0x10) { + target[position++] = 0x90 | length; + } else if (length < 0x10000) { + target[position++] = 0xdc; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0xdd; + targetView.setUint32(position, length); + position += 4; + } + for (let i = 0; i < length; i++) { + pack(value[i]); + } + }; + const pack = (value) => { + if (position > safeEnd) + target = makeRoom(position); + + var type = typeof value; + var length; + if (type === 'string') { + let strLength = value.length; + if (bundledStrings && strLength >= 4 && strLength < 0x1000) { + if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) { + let extStart; + let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10; + if (position + maxBytes > safeEnd) + target = makeRoom(position + maxBytes); + let lastBundle; + if (bundledStrings.position) { // here we use the 0x62 extension to write the last bundle and reserve space for the reference pointer to the next/current bundle + lastBundle = bundledStrings; + target[position] = 0xc8; // ext 16 + position += 3; // reserve for the writing bundle size + target[position++] = 0x62; // 'b' + extStart = position - start; + position += 4; // reserve for writing bundle reference + writeBundles(start, pack, 0); // write the last bundles + targetView.setUint16(extStart + start - 3, position - start - extStart); + } else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written) + target[position++] = 0xd6; // fixext 4 + target[position++] = 0x62; // 'b' + extStart = position - start; + position += 4; // reserve for writing bundle reference + } + bundledStrings = ['', '']; // create new ones + bundledStrings.previous = lastBundle; + bundledStrings.size = 0; + bundledStrings.position = extStart; + } + let twoByte = hasNonLatin.test(value); + bundledStrings[twoByte ? 0 : 1] += value; + target[position++] = 0xc1; + pack(twoByte ? -strLength : strLength); + return + } + let headerSize; + // first we estimate the header size, so we can write to the correct location + if (strLength < 0x20) { + headerSize = 1; + } else if (strLength < 0x100) { + headerSize = 2; + } else if (strLength < 0x10000) { + headerSize = 3; + } else { + headerSize = 5; + } + let maxBytes = strLength * 3; + if (position + maxBytes > safeEnd) + target = makeRoom(position + maxBytes); + + if (strLength < 0x40 || !encodeUtf8) { + let i, c1, c2, strPosition = position + headerSize; + for (i = 0; i < strLength; i++) { + c1 = value.charCodeAt(i); + if (c1 < 0x80) { + target[strPosition++] = c1; + } else if (c1 < 0x800) { + target[strPosition++] = c1 >> 6 | 0xc0; + target[strPosition++] = c1 & 0x3f | 0x80; + } else if ( + (c1 & 0xfc00) === 0xd800 && + ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00 + ) { + c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff); + i++; + target[strPosition++] = c1 >> 18 | 0xf0; + target[strPosition++] = c1 >> 12 & 0x3f | 0x80; + target[strPosition++] = c1 >> 6 & 0x3f | 0x80; + target[strPosition++] = c1 & 0x3f | 0x80; + } else { + target[strPosition++] = c1 >> 12 | 0xe0; + target[strPosition++] = c1 >> 6 & 0x3f | 0x80; + target[strPosition++] = c1 & 0x3f | 0x80; + } + } + length = strPosition - position - headerSize; + } else { + length = encodeUtf8(value, position + headerSize); + } + + if (length < 0x20) { + target[position++] = 0xa0 | length; + } else if (length < 0x100) { + if (headerSize < 2) { + target.copyWithin(position + 2, position + 1, position + 1 + length); + } + target[position++] = 0xd9; + target[position++] = length; + } else if (length < 0x10000) { + if (headerSize < 3) { + target.copyWithin(position + 3, position + 2, position + 2 + length); + } + target[position++] = 0xda; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + if (headerSize < 5) { + target.copyWithin(position + 5, position + 3, position + 3 + length); + } + target[position++] = 0xdb; + targetView.setUint32(position, length); + position += 4; + } + position += length; + } else if (type === 'number') { + if (value >>> 0 === value) {// positive integer, 32-bit or less + // positive uint + if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) { + target[position++] = value; + } else if (value < 0x100) { + target[position++] = 0xcc; + target[position++] = value; + } else if (value < 0x10000) { + target[position++] = 0xcd; + target[position++] = value >> 8; + target[position++] = value & 0xff; + } else { + target[position++] = 0xce; + targetView.setUint32(position, value); + position += 4; + } + } else if (value >> 0 === value) { // negative integer + if (value >= -0x20) { + target[position++] = 0x100 + value; + } else if (value >= -0x80) { + target[position++] = 0xd0; + target[position++] = value + 0x100; + } else if (value >= -0x8000) { + target[position++] = 0xd1; + targetView.setInt16(position, value); + position += 2; + } else { + target[position++] = 0xd2; + targetView.setInt32(position, value); + position += 4; + } + } else { + let useFloat32; + if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) { + target[position++] = 0xca; + targetView.setFloat32(position, value); + let xShifted; + if (useFloat32 < 4 || + // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved + ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) { + position += 4; + return + } else + position--; // move back into position for writing a double + } + target[position++] = 0xcb; + targetView.setFloat64(position, value); + position += 8; + } + } else if (type === 'object' || type === 'function') { + if (!value) + target[position++] = 0xc0; + else { + if (referenceMap) { + let referee = referenceMap.get(value); + if (referee) { + if (!referee.id) { + let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []); + referee.id = idsToInsert.push(referee); + } + target[position++] = 0xd6; // fixext 4 + target[position++] = 0x70; // "p" for pointer + targetView.setUint32(position, referee.id); + position += 4; + return + } else + referenceMap.set(value, { offset: position - start }); + } + let constructor = value.constructor; + if (constructor === Object) { + writeObject(value); + } else if (constructor === Array) { + packArray(value); + } else if (constructor === Map) { + if (this.mapAsEmptyObject) target[position++] = 0x80; + else { + length = value.size; + if (length < 0x10) { + target[position++] = 0x80 | length; + } else if (length < 0x10000) { + target[position++] = 0xde; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0xdf; + targetView.setUint32(position, length); + position += 4; + } + for (let [key, entryValue] of value) { + pack(key); + pack(entryValue); + } + } + } else { + for (let i = 0, l = extensions.length; i < l; i++) { + let extensionClass = extensionClasses[i]; + if (value instanceof extensionClass) { + let extension = extensions[i]; + if (extension.write) { + if (extension.type) { + target[position++] = 0xd4; // one byte "tag" extension + target[position++] = extension.type; + target[position++] = 0; + } + let writeResult = extension.write.call(this, value); + if (writeResult === value) { // avoid infinite recursion + if (Array.isArray(value)) { + packArray(value); + } else { + writeObject(value); + } + } else { + pack(writeResult); + } + return + } + let currentTarget = target; + let currentTargetView = targetView; + let currentPosition = position; + target = null; + let result; + try { + result = extension.pack.call(this, value, (size) => { + // restore target and use it + target = currentTarget; + currentTarget = null; + position += size; + if (position > safeEnd) + makeRoom(position); + return { + target, targetView, position: position - size + } + }, pack); + } finally { + // restore current target information (unless already restored) + if (currentTarget) { + target = currentTarget; + targetView = currentTargetView; + position = currentPosition; + safeEnd = target.length - 10; + } + } + if (result) { + if (result.length + position > safeEnd) + makeRoom(result.length + position); + position = writeExtensionData(result, target, position, extension.type); + } + return + } + } + // check isArray after extensions, because extensions can extend Array + if (Array.isArray(value)) { + packArray(value); + } else { + // use this as an alternate mechanism for expressing how to serialize + if (value.toJSON) { + const json = value.toJSON(); + // if for some reason value.toJSON returns itself it'll loop forever + if (json !== value) + return pack(json) + } + + // if there is a writeFunction, use it, otherwise just encode as undefined + if (type === 'function') + return pack(this.writeFunction && this.writeFunction(value)); + + // no extension found, write as plain object + writeObject(value); + } + } + } + } else if (type === 'boolean') { + target[position++] = value ? 0xc3 : 0xc2; + } else if (type === 'bigint') { + if (value < (BigInt(1)<= -(BigInt(1)< 0) { + // if we can fit an unsigned int, use that + target[position++] = 0xcf; + targetView.setBigUint64(position, value); + } else { + // overflow + if (this.largeBigIntToFloat) { + target[position++] = 0xcb; + targetView.setFloat64(position, Number(value)); + } else if (this.largeBigIntToString) { + return pack(value.toString()); + } else if (this.useBigIntExtension && value < BigInt(2)**BigInt(1023) && value > -(BigInt(2)**BigInt(1023))) { + target[position++] = 0xc7; + position++; + target[position++] = 0x42; // "B" for BigInt + let bytes = []; + let alignedSign; + do { + let byte = value & BigInt(0xff); + alignedSign = (byte & BigInt(0x80)) === (value < BigInt(0) ? BigInt(0x80) : BigInt(0)); + bytes.push(byte); + value >>= BigInt(8); + } while (!((value === BigInt(0) || value === BigInt(-1)) && alignedSign)); + target[position-2] = bytes.length; + for (let i = bytes.length; i > 0;) { + target[position++] = Number(bytes[--i]); + } + return + } else { + throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' + + ' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' + + ' largeBigIntToString to convert to string') + } + } + position += 8; + } else if (type === 'undefined') { + if (this.encodeUndefinedAsNil) + target[position++] = 0xc0; + else { + target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite + target[position++] = 0; + target[position++] = 0; + } + } else { + throw new Error('Unknown type: ' + type) + } + }; + + const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => { + // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects) + let keys; + if (this.skipValues) { + keys = []; + for (let key in object) { + if ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) && + !this.skipValues.includes(object[key])) + keys.push(key); + } + } else { + keys = Object.keys(object); + } + let length = keys.length; + if (length < 0x10) { + target[position++] = 0x80 | length; + } else if (length < 0x10000) { + target[position++] = 0xde; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0xdf; + targetView.setUint32(position, length); + position += 4; + } + let key; + if (this.coercibleKeyAsNumber) { + for (let i = 0; i < length; i++) { + key = keys[i]; + let num = Number(key); + pack(isNaN(num) ? key : num); + pack(object[key]); + } + + } else { + for (let i = 0; i < length; i++) { + pack(key = keys[i]); + pack(object[key]); + } + } + } : + (object) => { + target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards + let objectOffset = position - start; + position += 2; + let size = 0; + for (let key in object) { + if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) { + pack(key); + pack(object[key]); + size++; + } + } + if (size > 0xffff) { + throw new Error('Object is too large to serialize with fast 16-bit map size,' + + ' use the "variableMapSize" option to serialize this object'); + } + target[objectOffset++ + start] = size >> 8; + target[objectOffset + start] = size & 0xff; + }; + + const writeRecord = this.useRecords === false ? writePlainObject : + (options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written) + (object) => { + let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); + let objectOffset = position++ - start; + let wroteKeys; + for (let key in object) { + if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) { + nextTransition = transition[key]; + if (nextTransition) + transition = nextTransition; + else { + // record doesn't exist, create full new record and insert it + let keys = Object.keys(object); + let lastTransition = transition; + transition = structures.transitions; + let newTransitions = 0; + for (let i = 0, l = keys.length; i < l; i++) { + let key = keys[i]; + nextTransition = transition[key]; + if (!nextTransition) { + nextTransition = transition[key] = Object.create(null); + newTransitions++; + } + transition = nextTransition; + } + if (objectOffset + start + 1 == position) { + // first key, so we don't need to insert, we can just write record directly + position--; + newRecord(transition, keys, newTransitions); + } else // otherwise we need to insert the record, moving existing data after the record + insertNewRecord(transition, keys, objectOffset, newTransitions); + wroteKeys = true; + transition = lastTransition[key]; + } + pack(object[key]); + } + } + if (!wroteKeys) { + let recordId = transition[RECORD_SYMBOL]; + if (recordId) + target[objectOffset + start] = recordId; + else + insertNewRecord(transition, Object.keys(object), objectOffset, 0); + } + } : + (object) => { + let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); + let newTransitions = 0; + for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) { + nextTransition = transition[key]; + if (!nextTransition) { + nextTransition = transition[key] = Object.create(null); + newTransitions++; + } + transition = nextTransition; + } + let recordId = transition[RECORD_SYMBOL]; + if (recordId) { + if (recordId >= 0x60 && useTwoByteRecords) { + target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60; + target[position++] = recordId >> 5; + } else + target[position++] = recordId; + } else { + newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions); + } + // now write the values + for (let key in object) + if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) { + pack(object[key]); + } + }; + + // create reference to useRecords if useRecords is a function + const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords; + + const writeObject = checkUseRecords ? (object) => { + checkUseRecords(object) ? writeRecord(object) : writePlainObject(object); + } : writeRecord; + + const makeRoom = (end) => { + let newSize; + if (end > 0x1000000) { + // special handling for really large buffers + if ((end - start) > MAX_BUFFER_SIZE) + throw new Error('Packed buffer would be larger than maximum buffer size') + newSize = Math.min(MAX_BUFFER_SIZE, + Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000); + } else // faster handling for smaller buffers + newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12; + let newBuffer = new ByteArrayAllocate(newSize); + targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize)); + end = Math.min(end, target.length); + if (target.copy) + target.copy(newBuffer, 0, start, end); + else + newBuffer.set(target.slice(start, end)); + position -= start; + start = 0; + safeEnd = newBuffer.length - 10; + return target = newBuffer + }; + const newRecord = (transition, keys, newTransitions) => { + let recordId = structures.nextId; + if (!recordId) + recordId = 0x40; + if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) { + recordId = structures.nextOwnId; + if (!(recordId < maxStructureId)) + recordId = sharedLimitId; + structures.nextOwnId = recordId + 1; + } else { + if (recordId >= maxStructureId)// cycle back around + recordId = sharedLimitId; + structures.nextId = recordId + 1; + } + let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1; + transition[RECORD_SYMBOL] = recordId; + transition.__keys__ = keys; + structures[recordId - 0x40] = keys; + + if (recordId < sharedLimitId) { + keys.isShared = true; + structures.sharedLength = recordId - 0x3f; + hasSharedUpdate = true; + if (highByte >= 0) { + target[position++] = (recordId & 0x1f) + 0x60; + target[position++] = highByte; + } else { + target[position++] = recordId; + } + } else { + if (highByte >= 0) { + target[position++] = 0xd5; // fixext 2 + target[position++] = 0x72; // "r" record defintion extension type + target[position++] = (recordId & 0x1f) + 0x60; + target[position++] = highByte; + } else { + target[position++] = 0xd4; // fixext 1 + target[position++] = 0x72; // "r" record defintion extension type + target[position++] = recordId; + } + + if (newTransitions) + transitionsCount += serializationsSinceTransitionRebuild * newTransitions; + // record the removal of the id, we can maintain our shared structure + if (recordIdsToRemove.length >= maxOwnStructures) + recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones + recordIdsToRemove.push(transition); + pack(keys); + } + }; + const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => { + let mainTarget = target; + let mainPosition = position; + let mainSafeEnd = safeEnd; + let mainStart = start; + target = keysTarget; + position = 0; + start = 0; + if (!target) + keysTarget = target = new ByteArrayAllocate(8192); + safeEnd = target.length - 10; + newRecord(transition, keys, newTransitions); + keysTarget = target; + let keysPosition = position; + target = mainTarget; + position = mainPosition; + safeEnd = mainSafeEnd; + start = mainStart; + if (keysPosition > 1) { + let newEnd = position + keysPosition - 1; + if (newEnd > safeEnd) + makeRoom(newEnd); + let insertionPosition = insertionOffset + start; + target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position); + target.set(keysTarget.slice(0, keysPosition), insertionPosition); + position = newEnd; + } else { + target[insertionOffset + start] = keysTarget[0]; + } + }; + const writeStruct = (object) => { + let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => { + if (notifySharedUpdate) + return hasSharedUpdate = true; + position = newPosition; + let startTarget = target; + pack(value); + resetStructures(); + if (startTarget !== target) { + return { position, targetView, target }; // indicate the buffer was re-allocated + } + return position; + }, this); + if (newPosition === 0) // bail and go to a msgpack object + return writeObject(object); + position = newPosition; + }; + } + useBuffer(buffer) { + // this means we are finished using our own buffer and we can write over it safely + target = buffer; + target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength)); + position = 0; + } + set position (value) { + position = value; + } + get position() { + return position; + } + clearSharedData() { + if (this.structures) + this.structures = []; + if (this.typedStructs) + this.typedStructs = []; + } + } + + extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ]; + extensions = [{ + pack(date, allocateForWrite, pack) { + let seconds = date.getTime() / 1000; + if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) { + // Timestamp 32 + let { target, targetView, position} = allocateForWrite(6); + target[position++] = 0xd6; + target[position++] = 0xff; + targetView.setUint32(position, seconds); + } else if (seconds > 0 && seconds < 0x100000000) { + // Timestamp 64 + let { target, targetView, position} = allocateForWrite(10); + target[position++] = 0xd7; + target[position++] = 0xff; + targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0)); + targetView.setUint32(position + 4, seconds); + } else if (isNaN(seconds)) { + if (this.onInvalidDate) { + allocateForWrite(0); + return pack(this.onInvalidDate()) + } + // Intentionally invalid timestamp + let { target, targetView, position} = allocateForWrite(3); + target[position++] = 0xd4; + target[position++] = 0xff; + target[position++] = 0xff; + } else { + // Timestamp 96 + let { target, targetView, position} = allocateForWrite(15); + target[position++] = 0xc7; + target[position++] = 12; + target[position++] = 0xff; + targetView.setUint32(position, date.getMilliseconds() * 1000000); + targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds))); + } + } + }, { + pack(set, allocateForWrite, pack) { + if (this.setAsEmptyObject) { + allocateForWrite(0); + return pack({}) + } + let array = Array.from(set); + let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0); + if (this.moreTypes) { + target[position++] = 0xd4; + target[position++] = 0x73; // 's' for Set + target[position++] = 0; + } + pack(array); + } + }, { + pack(error, allocateForWrite, pack) { + let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0); + if (this.moreTypes) { + target[position++] = 0xd4; + target[position++] = 0x65; // 'e' for error + target[position++] = 0; + } + pack([ error.name, error.message, error.cause ]); + } + }, { + pack(regex, allocateForWrite, pack) { + let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0); + if (this.moreTypes) { + target[position++] = 0xd4; + target[position++] = 0x78; // 'x' for regeXp + target[position++] = 0; + } + pack([ regex.source, regex.flags ]); + } + }, { + pack(arrayBuffer, allocateForWrite) { + if (this.moreTypes) + writeExtBuffer(arrayBuffer, 0x10, allocateForWrite); + else + writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite); + } + }, { + pack(typedArray, allocateForWrite) { + let constructor = typedArray.constructor; + if (constructor !== ByteArray && this.moreTypes) + writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite); + else + writeBuffer(typedArray, allocateForWrite); + } + }, { + pack(c1, allocateForWrite) { // specific 0xC1 object + let { target, position} = allocateForWrite(1); + target[position] = 0xc1; + } + }]; + + function writeExtBuffer(typedArray, type, allocateForWrite, encode) { + let length = typedArray.byteLength; + if (length + 1 < 0x100) { + var { target, position } = allocateForWrite(4 + length); + target[position++] = 0xc7; + target[position++] = length + 1; + } else if (length + 1 < 0x10000) { + var { target, position } = allocateForWrite(5 + length); + target[position++] = 0xc8; + target[position++] = (length + 1) >> 8; + target[position++] = (length + 1) & 0xff; + } else { + var { target, position, targetView } = allocateForWrite(7 + length); + target[position++] = 0xc9; + targetView.setUint32(position, length + 1); // plus one for the type byte + position += 4; + } + target[position++] = 0x74; // "t" for typed array + target[position++] = type; + if (!typedArray.buffer) typedArray = new Uint8Array(typedArray); + target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position); + } + function writeBuffer(buffer, allocateForWrite) { + let length = buffer.byteLength; + var target, position; + if (length < 0x100) { + var { target, position } = allocateForWrite(length + 2); + target[position++] = 0xc4; + target[position++] = length; + } else if (length < 0x10000) { + var { target, position } = allocateForWrite(length + 3); + target[position++] = 0xc5; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + var { target, position, targetView } = allocateForWrite(length + 5); + target[position++] = 0xc6; + targetView.setUint32(position, length); + position += 4; + } + target.set(buffer, position); + } + + function writeExtensionData(result, target, position, type) { + let length = result.length; + switch (length) { + case 1: + target[position++] = 0xd4; + break + case 2: + target[position++] = 0xd5; + break + case 4: + target[position++] = 0xd6; + break + case 8: + target[position++] = 0xd7; + break + case 16: + target[position++] = 0xd8; + break + default: + if (length < 0x100) { + target[position++] = 0xc7; + target[position++] = length; + } else if (length < 0x10000) { + target[position++] = 0xc8; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0xc9; + target[position++] = length >> 24; + target[position++] = (length >> 16) & 0xff; + target[position++] = (length >> 8) & 0xff; + target[position++] = length & 0xff; + } + } + target[position++] = type; + target.set(result, position); + position += length; + return position + } + + function insertIds(serialized, idsToInsert) { + // insert the ids that need to be referenced for structured clones + let nextId; + let distanceToMove = idsToInsert.length * 6; + let lastEnd = serialized.length - distanceToMove; + while (nextId = idsToInsert.pop()) { + let offset = nextId.offset; + let id = nextId.id; + serialized.copyWithin(offset + distanceToMove, offset, lastEnd); + distanceToMove -= 6; + let position = offset + distanceToMove; + serialized[position++] = 0xd6; + serialized[position++] = 0x69; // 'i' + serialized[position++] = id >> 24; + serialized[position++] = (id >> 16) & 0xff; + serialized[position++] = (id >> 8) & 0xff; + serialized[position++] = id & 0xff; + lastEnd = offset; + } + return serialized + } + + function writeBundles(start, pack, incrementPosition) { + if (bundledStrings.length > 0) { + targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start); + bundledStrings.stringsPosition = position - start; + let writeStrings = bundledStrings; + bundledStrings = null; + pack(writeStrings[0]); + pack(writeStrings[1]); + } + } + + function addExtension(extension) { + if (extension.Class) { + if (!extension.pack && !extension.write) + throw new Error('Extension has no pack or write function') + if (extension.pack && !extension.type) + throw new Error('Extension has no type (numeric code to identify the extension)') + extensionClasses.unshift(extension.Class); + extensions.unshift(extension); + } + addExtension$1(extension); + } + function prepareStructures(structures, packr) { + structures.isCompatible = (existingStructures) => { + let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length); + if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction + packr._mergeStructures(existingStructures); + return compatible; + }; + return structures + } + + let defaultPackr = new Packr({ useRecords: false }); + const pack = defaultPackr.pack; + const encode = defaultPackr.pack; + const Encoder = Packr; + const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS; + const REUSE_BUFFER_MODE = 512; + const RESET_BUFFER_MODE = 1024; + const RESERVE_START_SPACE = 2048; + + /** + * Given an Iterable first argument, returns an Iterable where each value is packed as a Buffer + * If the argument is only Async Iterable, the return value will be an Async Iterable. + * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object + * @param {options} [options] - msgpackr pack options + * @returns {IterableIterator|Promise.} + */ + function packIter (objectIterator, options = {}) { + if (!objectIterator || typeof objectIterator !== 'object') { + throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable') + } else if (typeof objectIterator[Symbol.iterator] === 'function') { + return packIterSync(objectIterator, options) + } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') { + return packIterAsync(objectIterator, options) + } else { + throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise') + } + } + + function * packIterSync (objectIterator, options) { + const packr = new Packr(options); + for (const value of objectIterator) { + yield packr.pack(value); + } + } + + async function * packIterAsync (objectIterator, options) { + const packr = new Packr(options); + for await (const value of objectIterator) { + yield packr.pack(value); + } + } + + /** + * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects + * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator. + * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator + * @param {object} [options] - unpackr options + * @returns {IterableIterator|Promise. { + let yields; + // if there's incomplete data from previous chunk, concatinate and try again + if (incomplete) { + chunk = Buffer.concat([incomplete, chunk]); + incomplete = undefined; + } + + try { + yields = unpackr.unpackMultiple(chunk); + } catch (err) { + if (err.incomplete) { + incomplete = chunk.slice(err.lastPosition); + yields = err.values; + } else { + throw err + } + } + return yields + }; + + if (typeof bufferIterator[Symbol.iterator] === 'function') { + return (function * iter () { + for (const value of bufferIterator) { + yield * parser(value); + } + })() + } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') { + return (async function * iter () { + for await (const value of bufferIterator) { + yield * parser(value); + } + })() + } + } + const decodeIter = unpackIter; + const encodeIter = packIter; + + const useRecords = false; + const mapsAsObjects = true; + + global.ALWAYS = ALWAYS; + global.C1 = C1; + global.DECIMAL_FIT = DECIMAL_FIT; + global.DECIMAL_ROUND = DECIMAL_ROUND; + global.Decoder = Decoder; + global.Encoder = Encoder; + global.FLOAT32_OPTIONS = FLOAT32_OPTIONS; + global.NEVER = NEVER; + global.Packr = Packr; + global.RESERVE_START_SPACE = RESERVE_START_SPACE; + global.RESET_BUFFER_MODE = RESET_BUFFER_MODE; + global.REUSE_BUFFER_MODE = REUSE_BUFFER_MODE; + global.Unpackr = Unpackr; + global.addExtension = addExtension; + global.clearSource = clearSource; + global.decode = decode; + global.decodeIter = decodeIter; + global.encode = encode; + global.encodeIter = encodeIter; + global.isNativeAccelerationEnabled = isNativeAccelerationEnabled; + global.mapsAsObjects = mapsAsObjects; + global.pack = pack; + global.roundFloat32 = roundFloat32; + global.unpack = unpack; + global.unpackMultiple = unpackMultiple; + global.useRecords = useRecords; + +})); +//# sourceMappingURL=index-no-eval.cjs.map +