index.js 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.msgpackr = {}));
  5. })(this, (function (exports) { 'use strict';
  6. var decoder;
  7. try {
  8. decoder = new TextDecoder();
  9. } catch(error) {}
  10. var src;
  11. var srcEnd;
  12. var position$1 = 0;
  13. var currentUnpackr = {};
  14. var currentStructures;
  15. var srcString;
  16. var srcStringStart = 0;
  17. var srcStringEnd = 0;
  18. var bundledStrings$1;
  19. var referenceMap;
  20. var currentExtensions = [];
  21. var dataView;
  22. var defaultOptions = {
  23. useRecords: false,
  24. mapsAsObjects: true
  25. };
  26. class C1Type {}
  27. const C1 = new C1Type();
  28. C1.name = 'MessagePack 0xC1';
  29. var sequentialMode = false;
  30. var inlineObjectReadThreshold = 2;
  31. var readStruct;
  32. // no-eval build
  33. try {
  34. new Function('');
  35. } catch(error) {
  36. // if eval variants are not supported, do not create inline object readers ever
  37. inlineObjectReadThreshold = Infinity;
  38. }
  39. class Unpackr {
  40. constructor(options) {
  41. if (options) {
  42. if (options.useRecords === false && options.mapsAsObjects === undefined)
  43. options.mapsAsObjects = true;
  44. if (options.sequential && options.trusted !== false) {
  45. options.trusted = true;
  46. if (!options.structures && options.useRecords != false) {
  47. options.structures = [];
  48. if (!options.maxSharedStructures)
  49. options.maxSharedStructures = 0;
  50. }
  51. }
  52. if (options.structures)
  53. options.structures.sharedLength = options.structures.length;
  54. else if (options.getStructures) {
  55. (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
  56. options.structures.sharedLength = 0;
  57. }
  58. if (options.int64AsNumber) {
  59. options.int64AsType = 'number';
  60. }
  61. }
  62. Object.assign(this, options);
  63. }
  64. unpack(source, options) {
  65. if (src) {
  66. // re-entrant execution, save the state and restore it after we do this unpack
  67. return saveState(() => {
  68. clearSource();
  69. return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options)
  70. })
  71. }
  72. if (!source.buffer && source.constructor === ArrayBuffer)
  73. source = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);
  74. if (typeof options === 'object') {
  75. srcEnd = options.end || source.length;
  76. position$1 = options.start || 0;
  77. } else {
  78. position$1 = 0;
  79. srcEnd = options > -1 ? options : source.length;
  80. }
  81. srcStringEnd = 0;
  82. srcString = null;
  83. bundledStrings$1 = null;
  84. src = source;
  85. // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
  86. // technique for getting data from a database where it can be copied into an existing buffer instead of creating
  87. // new ones
  88. try {
  89. dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
  90. } catch(error) {
  91. // if it doesn't have a buffer, maybe it is the wrong type of object
  92. src = null;
  93. if (source instanceof Uint8Array)
  94. throw error
  95. throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
  96. }
  97. if (this instanceof Unpackr) {
  98. currentUnpackr = this;
  99. if (this.structures) {
  100. currentStructures = this.structures;
  101. return checkedRead(options)
  102. } else if (!currentStructures || currentStructures.length > 0) {
  103. currentStructures = [];
  104. }
  105. } else {
  106. currentUnpackr = defaultOptions;
  107. if (!currentStructures || currentStructures.length > 0)
  108. currentStructures = [];
  109. }
  110. return checkedRead(options)
  111. }
  112. unpackMultiple(source, forEach) {
  113. let values, lastPosition = 0;
  114. try {
  115. sequentialMode = true;
  116. let size = source.length;
  117. let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
  118. if (forEach) {
  119. if (forEach(value, lastPosition, position$1) === false) return;
  120. while(position$1 < size) {
  121. lastPosition = position$1;
  122. if (forEach(checkedRead(), lastPosition, position$1) === false) {
  123. return
  124. }
  125. }
  126. }
  127. else {
  128. values = [ value ];
  129. while(position$1 < size) {
  130. lastPosition = position$1;
  131. values.push(checkedRead());
  132. }
  133. return values
  134. }
  135. } catch(error) {
  136. error.lastPosition = lastPosition;
  137. error.values = values;
  138. throw error
  139. } finally {
  140. sequentialMode = false;
  141. clearSource();
  142. }
  143. }
  144. _mergeStructures(loadedStructures, existingStructures) {
  145. loadedStructures = loadedStructures || [];
  146. if (Object.isFrozen(loadedStructures))
  147. loadedStructures = loadedStructures.map(structure => structure.slice(0));
  148. for (let i = 0, l = loadedStructures.length; i < l; i++) {
  149. let structure = loadedStructures[i];
  150. if (structure) {
  151. structure.isShared = true;
  152. if (i >= 32)
  153. structure.highByte = (i - 32) >> 5;
  154. }
  155. }
  156. loadedStructures.sharedLength = loadedStructures.length;
  157. for (let id in existingStructures || []) {
  158. if (id >= 0) {
  159. let structure = loadedStructures[id];
  160. let existing = existingStructures[id];
  161. if (existing) {
  162. if (structure)
  163. (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
  164. loadedStructures[id] = existing;
  165. }
  166. }
  167. }
  168. return this.structures = loadedStructures
  169. }
  170. decode(source, options) {
  171. return this.unpack(source, options)
  172. }
  173. }
  174. function checkedRead(options) {
  175. try {
  176. if (!currentUnpackr.trusted && !sequentialMode) {
  177. let sharedLength = currentStructures.sharedLength || 0;
  178. if (sharedLength < currentStructures.length)
  179. currentStructures.length = sharedLength;
  180. }
  181. let result;
  182. if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct) {
  183. result = readStruct(src, position$1, srcEnd, currentUnpackr);
  184. src = null; // dispose of this so that recursive unpack calls don't save state
  185. if (!(options && options.lazy) && result)
  186. result = result.toJSON();
  187. position$1 = srcEnd;
  188. } else
  189. result = read();
  190. if (bundledStrings$1) { // bundled strings to skip past
  191. position$1 = bundledStrings$1.postBundlePosition;
  192. bundledStrings$1 = null;
  193. }
  194. if (sequentialMode)
  195. // we only need to restore the structures if there was an error, but if we completed a read,
  196. // we can clear this out and keep the structures we read
  197. currentStructures.restoreStructures = null;
  198. if (position$1 == srcEnd) {
  199. // finished reading this source, cleanup references
  200. if (currentStructures && currentStructures.restoreStructures)
  201. restoreStructures();
  202. currentStructures = null;
  203. src = null;
  204. if (referenceMap)
  205. referenceMap = null;
  206. } else if (position$1 > srcEnd) {
  207. // over read
  208. throw new Error('Unexpected end of MessagePack data')
  209. } else if (!sequentialMode) {
  210. let jsonView;
  211. try {
  212. jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100);
  213. } catch(error) {
  214. jsonView = '(JSON view not available ' + error + ')';
  215. }
  216. throw new Error('Data read, but end of buffer not reached ' + jsonView)
  217. }
  218. // else more to read, but we are reading sequentially, so don't clear source yet
  219. return result
  220. } catch(error) {
  221. if (currentStructures && currentStructures.restoreStructures)
  222. restoreStructures();
  223. clearSource();
  224. if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) {
  225. error.incomplete = true;
  226. }
  227. throw error
  228. }
  229. }
  230. function restoreStructures() {
  231. for (let id in currentStructures.restoreStructures) {
  232. currentStructures[id] = currentStructures.restoreStructures[id];
  233. }
  234. currentStructures.restoreStructures = null;
  235. }
  236. function read() {
  237. let token = src[position$1++];
  238. if (token < 0xa0) {
  239. if (token < 0x80) {
  240. if (token < 0x40)
  241. return token
  242. else {
  243. let structure = currentStructures[token & 0x3f] ||
  244. currentUnpackr.getStructures && loadStructures()[token & 0x3f];
  245. if (structure) {
  246. if (!structure.read) {
  247. structure.read = createStructureReader(structure, token & 0x3f);
  248. }
  249. return structure.read()
  250. } else
  251. return token
  252. }
  253. } else if (token < 0x90) {
  254. // map
  255. token -= 0x80;
  256. if (currentUnpackr.mapsAsObjects) {
  257. let object = {};
  258. for (let i = 0; i < token; i++) {
  259. let key = readKey();
  260. if (key === '__proto__')
  261. key = '__proto_';
  262. object[key] = read();
  263. }
  264. return object
  265. } else {
  266. let map = new Map();
  267. for (let i = 0; i < token; i++) {
  268. map.set(read(), read());
  269. }
  270. return map
  271. }
  272. } else {
  273. token -= 0x90;
  274. let array = new Array(token);
  275. for (let i = 0; i < token; i++) {
  276. array[i] = read();
  277. }
  278. if (currentUnpackr.freezeData)
  279. return Object.freeze(array)
  280. return array
  281. }
  282. } else if (token < 0xc0) {
  283. // fixstr
  284. let length = token - 0xa0;
  285. if (srcStringEnd >= position$1) {
  286. return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  287. }
  288. if (srcStringEnd == 0 && srcEnd < 140) {
  289. // for small blocks, avoiding the overhead of the extract call is helpful
  290. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  291. if (string != null)
  292. return string
  293. }
  294. return readFixedString(length)
  295. } else {
  296. let value;
  297. switch (token) {
  298. case 0xc0: return null
  299. case 0xc1:
  300. if (bundledStrings$1) {
  301. value = read(); // followed by the length of the string in characters (not bytes!)
  302. if (value > 0)
  303. return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
  304. else
  305. return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value)
  306. }
  307. return C1; // "never-used", return special object to denote that
  308. case 0xc2: return false
  309. case 0xc3: return true
  310. case 0xc4:
  311. // bin 8
  312. value = src[position$1++];
  313. if (value === undefined)
  314. throw new Error('Unexpected end of buffer')
  315. return readBin(value)
  316. case 0xc5:
  317. // bin 16
  318. value = dataView.getUint16(position$1);
  319. position$1 += 2;
  320. return readBin(value)
  321. case 0xc6:
  322. // bin 32
  323. value = dataView.getUint32(position$1);
  324. position$1 += 4;
  325. return readBin(value)
  326. case 0xc7:
  327. // ext 8
  328. return readExt(src[position$1++])
  329. case 0xc8:
  330. // ext 16
  331. value = dataView.getUint16(position$1);
  332. position$1 += 2;
  333. return readExt(value)
  334. case 0xc9:
  335. // ext 32
  336. value = dataView.getUint32(position$1);
  337. position$1 += 4;
  338. return readExt(value)
  339. case 0xca:
  340. value = dataView.getFloat32(position$1);
  341. if (currentUnpackr.useFloat32 > 2) {
  342. // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  343. let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
  344. position$1 += 4;
  345. return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  346. }
  347. position$1 += 4;
  348. return value
  349. case 0xcb:
  350. value = dataView.getFloat64(position$1);
  351. position$1 += 8;
  352. return value
  353. // uint handlers
  354. case 0xcc:
  355. return src[position$1++]
  356. case 0xcd:
  357. value = dataView.getUint16(position$1);
  358. position$1 += 2;
  359. return value
  360. case 0xce:
  361. value = dataView.getUint32(position$1);
  362. position$1 += 4;
  363. return value
  364. case 0xcf:
  365. if (currentUnpackr.int64AsType === 'number') {
  366. value = dataView.getUint32(position$1) * 0x100000000;
  367. value += dataView.getUint32(position$1 + 4);
  368. } else if (currentUnpackr.int64AsType === 'string') {
  369. value = dataView.getBigUint64(position$1).toString();
  370. } else if (currentUnpackr.int64AsType === 'auto') {
  371. value = dataView.getBigUint64(position$1);
  372. if (value<=BigInt(2)<<BigInt(52)) value=Number(value);
  373. } else
  374. value = dataView.getBigUint64(position$1);
  375. position$1 += 8;
  376. return value
  377. // int handlers
  378. case 0xd0:
  379. return dataView.getInt8(position$1++)
  380. case 0xd1:
  381. value = dataView.getInt16(position$1);
  382. position$1 += 2;
  383. return value
  384. case 0xd2:
  385. value = dataView.getInt32(position$1);
  386. position$1 += 4;
  387. return value
  388. case 0xd3:
  389. if (currentUnpackr.int64AsType === 'number') {
  390. value = dataView.getInt32(position$1) * 0x100000000;
  391. value += dataView.getUint32(position$1 + 4);
  392. } else if (currentUnpackr.int64AsType === 'string') {
  393. value = dataView.getBigInt64(position$1).toString();
  394. } else if (currentUnpackr.int64AsType === 'auto') {
  395. value = dataView.getBigInt64(position$1);
  396. if (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);
  397. } else
  398. value = dataView.getBigInt64(position$1);
  399. position$1 += 8;
  400. return value
  401. case 0xd4:
  402. // fixext 1
  403. value = src[position$1++];
  404. if (value == 0x72) {
  405. return recordDefinition(src[position$1++] & 0x3f)
  406. } else {
  407. let extension = currentExtensions[value];
  408. if (extension) {
  409. if (extension.read) {
  410. position$1++; // skip filler byte
  411. return extension.read(read())
  412. } else if (extension.noBuffer) {
  413. position$1++; // skip filler byte
  414. return extension()
  415. } else
  416. return extension(src.subarray(position$1, ++position$1))
  417. } else
  418. throw new Error('Unknown extension ' + value)
  419. }
  420. case 0xd5:
  421. // fixext 2
  422. value = src[position$1];
  423. if (value == 0x72) {
  424. position$1++;
  425. return recordDefinition(src[position$1++] & 0x3f, src[position$1++])
  426. } else
  427. return readExt(2)
  428. case 0xd6:
  429. // fixext 4
  430. return readExt(4)
  431. case 0xd7:
  432. // fixext 8
  433. return readExt(8)
  434. case 0xd8:
  435. // fixext 16
  436. return readExt(16)
  437. case 0xd9:
  438. // str 8
  439. value = src[position$1++];
  440. if (srcStringEnd >= position$1) {
  441. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  442. }
  443. return readString8(value)
  444. case 0xda:
  445. // str 16
  446. value = dataView.getUint16(position$1);
  447. position$1 += 2;
  448. if (srcStringEnd >= position$1) {
  449. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  450. }
  451. return readString16(value)
  452. case 0xdb:
  453. // str 32
  454. value = dataView.getUint32(position$1);
  455. position$1 += 4;
  456. if (srcStringEnd >= position$1) {
  457. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  458. }
  459. return readString32(value)
  460. case 0xdc:
  461. // array 16
  462. value = dataView.getUint16(position$1);
  463. position$1 += 2;
  464. return readArray(value)
  465. case 0xdd:
  466. // array 32
  467. value = dataView.getUint32(position$1);
  468. position$1 += 4;
  469. return readArray(value)
  470. case 0xde:
  471. // map 16
  472. value = dataView.getUint16(position$1);
  473. position$1 += 2;
  474. return readMap(value)
  475. case 0xdf:
  476. // map 32
  477. value = dataView.getUint32(position$1);
  478. position$1 += 4;
  479. return readMap(value)
  480. default: // negative int
  481. if (token >= 0xe0)
  482. return token - 0x100
  483. if (token === undefined) {
  484. let error = new Error('Unexpected end of MessagePack data');
  485. error.incomplete = true;
  486. throw error
  487. }
  488. throw new Error('Unknown MessagePack token ' + token)
  489. }
  490. }
  491. }
  492. const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
  493. function createStructureReader(structure, firstId) {
  494. function readObject() {
  495. // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
  496. if (readObject.count++ > inlineObjectReadThreshold) {
  497. let readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
  498. '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
  499. if (structure.highByte === 0)
  500. structure.read = createSecondByteReader(firstId, structure.read);
  501. return readObject() // second byte is already read, if there is one so immediately read object
  502. }
  503. let object = {};
  504. for (let i = 0, l = structure.length; i < l; i++) {
  505. let key = structure[i];
  506. if (key === '__proto__')
  507. key = '__proto_';
  508. object[key] = read();
  509. }
  510. if (currentUnpackr.freezeData)
  511. return Object.freeze(object);
  512. return object
  513. }
  514. readObject.count = 0;
  515. if (structure.highByte === 0) {
  516. return createSecondByteReader(firstId, readObject)
  517. }
  518. return readObject
  519. }
  520. const createSecondByteReader = (firstId, read0) => {
  521. return function() {
  522. let highByte = src[position$1++];
  523. if (highByte === 0)
  524. return read0()
  525. let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
  526. let structure = currentStructures[id] || loadStructures()[id];
  527. if (!structure) {
  528. throw new Error('Record id is not defined for ' + id)
  529. }
  530. if (!structure.read)
  531. structure.read = createStructureReader(structure, firstId);
  532. return structure.read()
  533. }
  534. };
  535. function loadStructures() {
  536. let loadedStructures = saveState(() => {
  537. // save the state in case getStructures modifies our buffer
  538. src = null;
  539. return currentUnpackr.getStructures()
  540. });
  541. return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
  542. }
  543. var readFixedString = readStringJS;
  544. var readString8 = readStringJS;
  545. var readString16 = readStringJS;
  546. var readString32 = readStringJS;
  547. let isNativeAccelerationEnabled = false;
  548. function readStringJS(length) {
  549. let result;
  550. if (length < 16) {
  551. if (result = shortStringInJS(length))
  552. return result
  553. }
  554. if (length > 64 && decoder)
  555. return decoder.decode(src.subarray(position$1, position$1 += length))
  556. const end = position$1 + length;
  557. const units = [];
  558. result = '';
  559. while (position$1 < end) {
  560. const byte1 = src[position$1++];
  561. if ((byte1 & 0x80) === 0) {
  562. // 1 byte
  563. units.push(byte1);
  564. } else if ((byte1 & 0xe0) === 0xc0) {
  565. // 2 bytes
  566. const byte2 = src[position$1++] & 0x3f;
  567. units.push(((byte1 & 0x1f) << 6) | byte2);
  568. } else if ((byte1 & 0xf0) === 0xe0) {
  569. // 3 bytes
  570. const byte2 = src[position$1++] & 0x3f;
  571. const byte3 = src[position$1++] & 0x3f;
  572. units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
  573. } else if ((byte1 & 0xf8) === 0xf0) {
  574. // 4 bytes
  575. const byte2 = src[position$1++] & 0x3f;
  576. const byte3 = src[position$1++] & 0x3f;
  577. const byte4 = src[position$1++] & 0x3f;
  578. let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
  579. if (unit > 0xffff) {
  580. unit -= 0x10000;
  581. units.push(((unit >>> 10) & 0x3ff) | 0xd800);
  582. unit = 0xdc00 | (unit & 0x3ff);
  583. }
  584. units.push(unit);
  585. } else {
  586. units.push(byte1);
  587. }
  588. if (units.length >= 0x1000) {
  589. result += fromCharCode.apply(String, units);
  590. units.length = 0;
  591. }
  592. }
  593. if (units.length > 0) {
  594. result += fromCharCode.apply(String, units);
  595. }
  596. return result
  597. }
  598. function readArray(length) {
  599. let array = new Array(length);
  600. for (let i = 0; i < length; i++) {
  601. array[i] = read();
  602. }
  603. if (currentUnpackr.freezeData)
  604. return Object.freeze(array)
  605. return array
  606. }
  607. function readMap(length) {
  608. if (currentUnpackr.mapsAsObjects) {
  609. let object = {};
  610. for (let i = 0; i < length; i++) {
  611. let key = readKey();
  612. if (key === '__proto__')
  613. key = '__proto_';
  614. object[key] = read();
  615. }
  616. return object
  617. } else {
  618. let map = new Map();
  619. for (let i = 0; i < length; i++) {
  620. map.set(read(), read());
  621. }
  622. return map
  623. }
  624. }
  625. var fromCharCode = String.fromCharCode;
  626. function longStringInJS(length) {
  627. let start = position$1;
  628. let bytes = new Array(length);
  629. for (let i = 0; i < length; i++) {
  630. const byte = src[position$1++];
  631. if ((byte & 0x80) > 0) {
  632. position$1 = start;
  633. return
  634. }
  635. bytes[i] = byte;
  636. }
  637. return fromCharCode.apply(String, bytes)
  638. }
  639. function shortStringInJS(length) {
  640. if (length < 4) {
  641. if (length < 2) {
  642. if (length === 0)
  643. return ''
  644. else {
  645. let a = src[position$1++];
  646. if ((a & 0x80) > 1) {
  647. position$1 -= 1;
  648. return
  649. }
  650. return fromCharCode(a)
  651. }
  652. } else {
  653. let a = src[position$1++];
  654. let b = src[position$1++];
  655. if ((a & 0x80) > 0 || (b & 0x80) > 0) {
  656. position$1 -= 2;
  657. return
  658. }
  659. if (length < 3)
  660. return fromCharCode(a, b)
  661. let c = src[position$1++];
  662. if ((c & 0x80) > 0) {
  663. position$1 -= 3;
  664. return
  665. }
  666. return fromCharCode(a, b, c)
  667. }
  668. } else {
  669. let a = src[position$1++];
  670. let b = src[position$1++];
  671. let c = src[position$1++];
  672. let d = src[position$1++];
  673. if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
  674. position$1 -= 4;
  675. return
  676. }
  677. if (length < 6) {
  678. if (length === 4)
  679. return fromCharCode(a, b, c, d)
  680. else {
  681. let e = src[position$1++];
  682. if ((e & 0x80) > 0) {
  683. position$1 -= 5;
  684. return
  685. }
  686. return fromCharCode(a, b, c, d, e)
  687. }
  688. } else if (length < 8) {
  689. let e = src[position$1++];
  690. let f = src[position$1++];
  691. if ((e & 0x80) > 0 || (f & 0x80) > 0) {
  692. position$1 -= 6;
  693. return
  694. }
  695. if (length < 7)
  696. return fromCharCode(a, b, c, d, e, f)
  697. let g = src[position$1++];
  698. if ((g & 0x80) > 0) {
  699. position$1 -= 7;
  700. return
  701. }
  702. return fromCharCode(a, b, c, d, e, f, g)
  703. } else {
  704. let e = src[position$1++];
  705. let f = src[position$1++];
  706. let g = src[position$1++];
  707. let h = src[position$1++];
  708. if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
  709. position$1 -= 8;
  710. return
  711. }
  712. if (length < 10) {
  713. if (length === 8)
  714. return fromCharCode(a, b, c, d, e, f, g, h)
  715. else {
  716. let i = src[position$1++];
  717. if ((i & 0x80) > 0) {
  718. position$1 -= 9;
  719. return
  720. }
  721. return fromCharCode(a, b, c, d, e, f, g, h, i)
  722. }
  723. } else if (length < 12) {
  724. let i = src[position$1++];
  725. let j = src[position$1++];
  726. if ((i & 0x80) > 0 || (j & 0x80) > 0) {
  727. position$1 -= 10;
  728. return
  729. }
  730. if (length < 11)
  731. return fromCharCode(a, b, c, d, e, f, g, h, i, j)
  732. let k = src[position$1++];
  733. if ((k & 0x80) > 0) {
  734. position$1 -= 11;
  735. return
  736. }
  737. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
  738. } else {
  739. let i = src[position$1++];
  740. let j = src[position$1++];
  741. let k = src[position$1++];
  742. let l = src[position$1++];
  743. if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
  744. position$1 -= 12;
  745. return
  746. }
  747. if (length < 14) {
  748. if (length === 12)
  749. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
  750. else {
  751. let m = src[position$1++];
  752. if ((m & 0x80) > 0) {
  753. position$1 -= 13;
  754. return
  755. }
  756. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
  757. }
  758. } else {
  759. let m = src[position$1++];
  760. let n = src[position$1++];
  761. if ((m & 0x80) > 0 || (n & 0x80) > 0) {
  762. position$1 -= 14;
  763. return
  764. }
  765. if (length < 15)
  766. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
  767. let o = src[position$1++];
  768. if ((o & 0x80) > 0) {
  769. position$1 -= 15;
  770. return
  771. }
  772. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
  773. }
  774. }
  775. }
  776. }
  777. }
  778. function readOnlyJSString() {
  779. let token = src[position$1++];
  780. let length;
  781. if (token < 0xc0) {
  782. // fixstr
  783. length = token - 0xa0;
  784. } else {
  785. switch(token) {
  786. case 0xd9:
  787. // str 8
  788. length = src[position$1++];
  789. break
  790. case 0xda:
  791. // str 16
  792. length = dataView.getUint16(position$1);
  793. position$1 += 2;
  794. break
  795. case 0xdb:
  796. // str 32
  797. length = dataView.getUint32(position$1);
  798. position$1 += 4;
  799. break
  800. default:
  801. throw new Error('Expected string')
  802. }
  803. }
  804. return readStringJS(length)
  805. }
  806. function readBin(length) {
  807. return currentUnpackr.copyBuffers ?
  808. // specifically use the copying slice (not the node one)
  809. Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
  810. src.subarray(position$1, position$1 += length)
  811. }
  812. function readExt(length) {
  813. let type = src[position$1++];
  814. if (currentExtensions[type]) {
  815. let end;
  816. return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => {
  817. position$1 = readPosition;
  818. try {
  819. return read();
  820. } finally {
  821. position$1 = end;
  822. }
  823. })
  824. }
  825. else
  826. throw new Error('Unknown extension type ' + type)
  827. }
  828. var keyCache = new Array(4096);
  829. function readKey() {
  830. let length = src[position$1++];
  831. if (length >= 0xa0 && length < 0xc0) {
  832. // fixstr, potentially use key cache
  833. length = length - 0xa0;
  834. if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway)
  835. return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  836. else if (!(srcStringEnd == 0 && srcEnd < 180))
  837. return readFixedString(length)
  838. } else { // not cacheable, go back and do a standard read
  839. position$1--;
  840. return asSafeString(read())
  841. }
  842. let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff;
  843. let entry = keyCache[key];
  844. let checkPosition = position$1;
  845. let end = position$1 + length - 3;
  846. let chunk;
  847. let i = 0;
  848. if (entry && entry.bytes == length) {
  849. while (checkPosition < end) {
  850. chunk = dataView.getUint32(checkPosition);
  851. if (chunk != entry[i++]) {
  852. checkPosition = 0x70000000;
  853. break
  854. }
  855. checkPosition += 4;
  856. }
  857. end += 3;
  858. while (checkPosition < end) {
  859. chunk = src[checkPosition++];
  860. if (chunk != entry[i++]) {
  861. checkPosition = 0x70000000;
  862. break
  863. }
  864. }
  865. if (checkPosition === end) {
  866. position$1 = checkPosition;
  867. return entry.string
  868. }
  869. end -= 3;
  870. checkPosition = position$1;
  871. }
  872. entry = [];
  873. keyCache[key] = entry;
  874. entry.bytes = length;
  875. while (checkPosition < end) {
  876. chunk = dataView.getUint32(checkPosition);
  877. entry.push(chunk);
  878. checkPosition += 4;
  879. }
  880. end += 3;
  881. while (checkPosition < end) {
  882. chunk = src[checkPosition++];
  883. entry.push(chunk);
  884. }
  885. // for small blocks, avoiding the overhead of the extract call is helpful
  886. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  887. if (string != null)
  888. return entry.string = string
  889. return entry.string = readFixedString(length)
  890. }
  891. function asSafeString(property) {
  892. // protect against expensive (DoS) string conversions
  893. if (typeof property === 'string') return property;
  894. if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();
  895. if (property == null) return property + '';
  896. if (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every(item => ['string', 'number', 'boolean', 'bigint'].includes(typeof item))) {
  897. return property.flat().toString();
  898. }
  899. throw new Error(`Invalid property type for record: ${typeof property}`);
  900. }
  901. // the registration of the record definition extension (as "r")
  902. const recordDefinition = (id, highByte) => {
  903. let structure = read().map(asSafeString); // ensure that all keys are strings and
  904. // that the array is mutable
  905. let firstByte = id;
  906. if (highByte !== undefined) {
  907. id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
  908. structure.highByte = highByte;
  909. }
  910. let existingStructure = currentStructures[id];
  911. // If it is a shared structure, we need to restore any changes after reading.
  912. // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
  913. // to the state prior to an incomplete read in order to properly resume.
  914. if (existingStructure && (existingStructure.isShared || sequentialMode)) {
  915. (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
  916. }
  917. currentStructures[id] = structure;
  918. structure.read = createStructureReader(structure, firstByte);
  919. return structure.read()
  920. };
  921. currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
  922. currentExtensions[0].noBuffer = true;
  923. currentExtensions[0x42] = data => {
  924. let headLength = (data.byteLength % 8) || 8;
  925. let head = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
  926. for (let i = 1; i < headLength; i++) {
  927. head <<= BigInt(8);
  928. head += BigInt(data[i]);
  929. }
  930. if (data.byteLength !== headLength) {
  931. let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  932. let decode = (start, end) => {
  933. let length = end - start;
  934. if (length <= 40) {
  935. let out = view.getBigUint64(start);
  936. for (let i = start + 8; i < end; i += 8) {
  937. out <<= BigInt(64n);
  938. out |= view.getBigUint64(i);
  939. }
  940. return out
  941. }
  942. // if (length === 8) return view.getBigUint64(start)
  943. let middle = start + (length >> 4 << 3);
  944. let left = decode(start, middle);
  945. let right = decode(middle, end);
  946. return (left << BigInt((end - middle) * 8)) | right
  947. };
  948. head = (head << BigInt((view.byteLength - headLength) * 8)) | decode(headLength, view.byteLength);
  949. }
  950. return head
  951. };
  952. let errors = {
  953. Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError: typeof AggregateError === 'function' ? AggregateError : null,
  954. };
  955. currentExtensions[0x65] = () => {
  956. let data = read();
  957. if (!errors[data[0]]) {
  958. let error = Error(data[1], { cause: data[2] });
  959. error.name = data[0];
  960. return error
  961. }
  962. return errors[data[0]](data[1], { cause: data[2] })
  963. };
  964. currentExtensions[0x69] = (data) => {
  965. // id extension (for structured clones)
  966. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  967. let id = dataView.getUint32(position$1 - 4);
  968. if (!referenceMap)
  969. referenceMap = new Map();
  970. let token = src[position$1];
  971. let target;
  972. // TODO: handle any other types that can cycle and make the code more robust if there are other extensions
  973. if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
  974. target = [];
  975. else if (token >= 0x80 && token < 0x90 || token == 0xde || token == 0xdf)
  976. target = new Map();
  977. else if ((token >= 0xc7 && token <= 0xc9 || token >= 0xd4 && token <= 0xd8) && src[position$1 + 1] === 0x73)
  978. target = new Set();
  979. else
  980. target = {};
  981. let refEntry = { target }; // a placeholder object
  982. referenceMap.set(id, refEntry);
  983. let targetProperties = read(); // read the next value as the target object to id
  984. if (!refEntry.used) {
  985. // no cycle, can just use the returned read object
  986. return refEntry.target = targetProperties // replace the placeholder with the real one
  987. } else {
  988. // there is a cycle, so we have to assign properties to original target
  989. Object.assign(target, targetProperties);
  990. }
  991. // copy over map/set entries if we're able to
  992. if (target instanceof Map)
  993. for (let [k, v] of targetProperties.entries()) target.set(k, v);
  994. if (target instanceof Set)
  995. for (let i of Array.from(targetProperties)) target.add(i);
  996. return target
  997. };
  998. currentExtensions[0x70] = (data) => {
  999. // pointer extension (for structured clones)
  1000. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1001. let id = dataView.getUint32(position$1 - 4);
  1002. let refEntry = referenceMap.get(id);
  1003. refEntry.used = true;
  1004. return refEntry.target
  1005. };
  1006. currentExtensions[0x73] = () => new Set(read());
  1007. const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
  1008. let glbl = typeof globalThis === 'object' ? globalThis : window;
  1009. currentExtensions[0x74] = (data) => {
  1010. let typeCode = data[0];
  1011. // we always have to slice to get a new ArrayBuffer that is aligned
  1012. let buffer = Uint8Array.prototype.slice.call(data, 1).buffer;
  1013. let typedArrayName = typedArrays[typeCode];
  1014. if (!typedArrayName) {
  1015. if (typeCode === 16) return buffer
  1016. if (typeCode === 17) return new DataView(buffer)
  1017. throw new Error('Could not find typed array for code ' + typeCode)
  1018. }
  1019. return new glbl[typedArrayName](buffer)
  1020. };
  1021. currentExtensions[0x78] = () => {
  1022. let data = read();
  1023. return new RegExp(data[0], data[1])
  1024. };
  1025. const TEMP_BUNDLE = [];
  1026. currentExtensions[0x62] = (data) => {
  1027. let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  1028. let dataPosition = position$1;
  1029. position$1 += dataSize - data.length;
  1030. bundledStrings$1 = TEMP_BUNDLE;
  1031. bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
  1032. bundledStrings$1.position0 = 0;
  1033. bundledStrings$1.position1 = 0;
  1034. bundledStrings$1.postBundlePosition = position$1;
  1035. position$1 = dataPosition;
  1036. return read()
  1037. };
  1038. currentExtensions[0xff] = (data) => {
  1039. // 32-bit date extension
  1040. if (data.length == 4)
  1041. return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
  1042. else if (data.length == 8)
  1043. return new Date(
  1044. ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
  1045. ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
  1046. else if (data.length == 12)
  1047. return new Date(
  1048. ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
  1049. (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
  1050. else
  1051. return new Date('invalid')
  1052. };
  1053. // registration of bulk record definition?
  1054. // currentExtensions[0x52] = () =>
  1055. function saveState(callback) {
  1056. let savedSrcEnd = srcEnd;
  1057. let savedPosition = position$1;
  1058. let savedSrcStringStart = srcStringStart;
  1059. let savedSrcStringEnd = srcStringEnd;
  1060. let savedSrcString = srcString;
  1061. let savedReferenceMap = referenceMap;
  1062. let savedBundledStrings = bundledStrings$1;
  1063. // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
  1064. let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
  1065. let savedStructures = currentStructures;
  1066. let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
  1067. let savedPackr = currentUnpackr;
  1068. let savedSequentialMode = sequentialMode;
  1069. let value = callback();
  1070. srcEnd = savedSrcEnd;
  1071. position$1 = savedPosition;
  1072. srcStringStart = savedSrcStringStart;
  1073. srcStringEnd = savedSrcStringEnd;
  1074. srcString = savedSrcString;
  1075. referenceMap = savedReferenceMap;
  1076. bundledStrings$1 = savedBundledStrings;
  1077. src = savedSrc;
  1078. sequentialMode = savedSequentialMode;
  1079. currentStructures = savedStructures;
  1080. currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
  1081. currentUnpackr = savedPackr;
  1082. dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  1083. return value
  1084. }
  1085. function clearSource() {
  1086. src = null;
  1087. referenceMap = null;
  1088. currentStructures = null;
  1089. }
  1090. function addExtension$1(extension) {
  1091. if (extension.unpack)
  1092. currentExtensions[extension.type] = extension.unpack;
  1093. else
  1094. currentExtensions[extension.type] = extension;
  1095. }
  1096. const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
  1097. for (let i = 0; i < 256; i++) {
  1098. mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
  1099. }
  1100. const Decoder = Unpackr;
  1101. var defaultUnpackr = new Unpackr({ useRecords: false });
  1102. const unpack = defaultUnpackr.unpack;
  1103. const unpackMultiple = defaultUnpackr.unpackMultiple;
  1104. const decode = defaultUnpackr.unpack;
  1105. const FLOAT32_OPTIONS = {
  1106. NEVER: 0,
  1107. ALWAYS: 1,
  1108. DECIMAL_ROUND: 3,
  1109. DECIMAL_FIT: 4
  1110. };
  1111. let f32Array = new Float32Array(1);
  1112. let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
  1113. function roundFloat32(float32Number) {
  1114. f32Array[0] = float32Number;
  1115. let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
  1116. return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  1117. }
  1118. let textEncoder;
  1119. try {
  1120. textEncoder = new TextEncoder();
  1121. } catch (error) {}
  1122. let extensions, extensionClasses;
  1123. const hasNodeBuffer = typeof Buffer !== 'undefined';
  1124. const ByteArrayAllocate = hasNodeBuffer ?
  1125. function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
  1126. const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
  1127. const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
  1128. let target, keysTarget;
  1129. let targetView;
  1130. let position = 0;
  1131. let safeEnd;
  1132. let bundledStrings = null;
  1133. let writeStructSlots;
  1134. const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
  1135. const hasNonLatin = /[\u0080-\uFFFF]/;
  1136. const RECORD_SYMBOL = Symbol('record-id');
  1137. class Packr extends Unpackr {
  1138. constructor(options) {
  1139. super(options);
  1140. this.offset = 0;
  1141. let start;
  1142. let hasSharedUpdate;
  1143. let structures;
  1144. let referenceMap;
  1145. let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
  1146. return target.utf8Write(string, position, target.byteLength - position)
  1147. } : (textEncoder && textEncoder.encodeInto) ?
  1148. function(string, position) {
  1149. return textEncoder.encodeInto(string, target.subarray(position)).written
  1150. } : false;
  1151. let packr = this;
  1152. if (!options)
  1153. options = {};
  1154. let isSequential = options && options.sequential;
  1155. let hasSharedStructures = options.structures || options.saveStructures;
  1156. let maxSharedStructures = options.maxSharedStructures;
  1157. if (maxSharedStructures == null)
  1158. maxSharedStructures = hasSharedStructures ? 32 : 0;
  1159. if (maxSharedStructures > 8160)
  1160. throw new Error('Maximum maxSharedStructure is 8160')
  1161. if (options.structuredClone && options.moreTypes == undefined) {
  1162. this.moreTypes = true;
  1163. }
  1164. let maxOwnStructures = options.maxOwnStructures;
  1165. if (maxOwnStructures == null)
  1166. maxOwnStructures = hasSharedStructures ? 32 : 64;
  1167. if (!this.structures && options.useRecords != false)
  1168. this.structures = [];
  1169. // two byte record ids for shared structures
  1170. let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
  1171. let sharedLimitId = maxSharedStructures + 0x40;
  1172. let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
  1173. if (maxStructureId > 8256) {
  1174. throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
  1175. }
  1176. let recordIdsToRemove = [];
  1177. let transitionsCount = 0;
  1178. let serializationsSinceTransitionRebuild = 0;
  1179. this.pack = this.encode = function(value, encodeOptions) {
  1180. if (!target) {
  1181. target = new ByteArrayAllocate(8192);
  1182. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
  1183. position = 0;
  1184. }
  1185. safeEnd = target.length - 10;
  1186. if (safeEnd - position < 0x800) {
  1187. // don't start too close to the end,
  1188. target = new ByteArrayAllocate(target.length);
  1189. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
  1190. safeEnd = target.length - 10;
  1191. position = 0;
  1192. } else
  1193. position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
  1194. start = position;
  1195. if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);
  1196. referenceMap = packr.structuredClone ? new Map() : null;
  1197. if (packr.bundleStrings && typeof value !== 'string') {
  1198. bundledStrings = [];
  1199. bundledStrings.size = Infinity; // force a new bundle start on first string
  1200. } else
  1201. bundledStrings = null;
  1202. structures = packr.structures;
  1203. if (structures) {
  1204. if (structures.uninitialized)
  1205. structures = packr._mergeStructures(packr.getStructures());
  1206. let sharedLength = structures.sharedLength || 0;
  1207. if (sharedLength > maxSharedStructures) {
  1208. //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
  1209. throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
  1210. }
  1211. if (!structures.transitions) {
  1212. // rebuild our structure transitions
  1213. structures.transitions = Object.create(null);
  1214. for (let i = 0; i < sharedLength; i++) {
  1215. let keys = structures[i];
  1216. if (!keys)
  1217. continue
  1218. let nextTransition, transition = structures.transitions;
  1219. for (let j = 0, l = keys.length; j < l; j++) {
  1220. let key = keys[j];
  1221. nextTransition = transition[key];
  1222. if (!nextTransition) {
  1223. nextTransition = transition[key] = Object.create(null);
  1224. }
  1225. transition = nextTransition;
  1226. }
  1227. transition[RECORD_SYMBOL] = i + 0x40;
  1228. }
  1229. this.lastNamedStructuresLength = sharedLength;
  1230. }
  1231. if (!isSequential) {
  1232. structures.nextId = sharedLength + 0x40;
  1233. }
  1234. }
  1235. if (hasSharedUpdate)
  1236. hasSharedUpdate = false;
  1237. let encodingError;
  1238. try {
  1239. if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object)
  1240. writeStruct(value);
  1241. else
  1242. pack(value);
  1243. let lastBundle = bundledStrings;
  1244. if (bundledStrings)
  1245. writeBundles(start, pack, 0);
  1246. if (referenceMap && referenceMap.idsToInsert) {
  1247. let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
  1248. let i = idsToInsert.length;
  1249. let incrementPosition = -1;
  1250. while (lastBundle && i > 0) {
  1251. let insertionPoint = idsToInsert[--i].offset + start;
  1252. if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
  1253. incrementPosition = 0;
  1254. if (insertionPoint > (lastBundle.position + start)) {
  1255. if (incrementPosition >= 0)
  1256. incrementPosition += 6;
  1257. } else {
  1258. if (incrementPosition >= 0) {
  1259. // update the bundle reference now
  1260. targetView.setUint32(lastBundle.position + start,
  1261. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1262. incrementPosition = -1; // reset
  1263. }
  1264. lastBundle = lastBundle.previous;
  1265. i++;
  1266. }
  1267. }
  1268. if (incrementPosition >= 0 && lastBundle) {
  1269. // update the bundle reference now
  1270. targetView.setUint32(lastBundle.position + start,
  1271. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1272. }
  1273. position += idsToInsert.length * 6;
  1274. if (position > safeEnd)
  1275. makeRoom(position);
  1276. packr.offset = position;
  1277. let serialized = insertIds(target.subarray(start, position), idsToInsert);
  1278. referenceMap = null;
  1279. return serialized
  1280. }
  1281. packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
  1282. if (encodeOptions & REUSE_BUFFER_MODE) {
  1283. target.start = start;
  1284. target.end = position;
  1285. return target
  1286. }
  1287. return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
  1288. } catch(error) {
  1289. encodingError = error;
  1290. throw error;
  1291. } finally {
  1292. if (structures) {
  1293. resetStructures();
  1294. if (hasSharedUpdate && packr.saveStructures) {
  1295. let sharedLength = structures.sharedLength || 0;
  1296. // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
  1297. let returnBuffer = target.subarray(start, position);
  1298. let newSharedData = prepareStructures(structures, packr);
  1299. if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time
  1300. if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
  1301. // get updated structures and try again if the update failed
  1302. return packr.pack(value, encodeOptions)
  1303. }
  1304. packr.lastNamedStructuresLength = sharedLength;
  1305. // don't keep large buffers around
  1306. if (target.length > 0x40000000) target = null;
  1307. return returnBuffer
  1308. }
  1309. }
  1310. }
  1311. // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)
  1312. if (target.length > 0x40000000) target = null;
  1313. if (encodeOptions & RESET_BUFFER_MODE)
  1314. position = start;
  1315. }
  1316. };
  1317. const resetStructures = () => {
  1318. if (serializationsSinceTransitionRebuild < 10)
  1319. serializationsSinceTransitionRebuild++;
  1320. let sharedLength = structures.sharedLength || 0;
  1321. if (structures.length > sharedLength && !isSequential)
  1322. structures.length = sharedLength;
  1323. if (transitionsCount > 10000) {
  1324. // force a rebuild occasionally after a lot of transitions so it can get cleaned up
  1325. structures.transitions = null;
  1326. serializationsSinceTransitionRebuild = 0;
  1327. transitionsCount = 0;
  1328. if (recordIdsToRemove.length > 0)
  1329. recordIdsToRemove = [];
  1330. } else if (recordIdsToRemove.length > 0 && !isSequential) {
  1331. for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
  1332. recordIdsToRemove[i][RECORD_SYMBOL] = 0;
  1333. }
  1334. recordIdsToRemove = [];
  1335. }
  1336. };
  1337. const packArray = (value) => {
  1338. var length = value.length;
  1339. if (length < 0x10) {
  1340. target[position++] = 0x90 | length;
  1341. } else if (length < 0x10000) {
  1342. target[position++] = 0xdc;
  1343. target[position++] = length >> 8;
  1344. target[position++] = length & 0xff;
  1345. } else {
  1346. target[position++] = 0xdd;
  1347. targetView.setUint32(position, length);
  1348. position += 4;
  1349. }
  1350. for (let i = 0; i < length; i++) {
  1351. pack(value[i]);
  1352. }
  1353. };
  1354. const pack = (value) => {
  1355. if (position > safeEnd)
  1356. target = makeRoom(position);
  1357. var type = typeof value;
  1358. var length;
  1359. if (type === 'string') {
  1360. let strLength = value.length;
  1361. if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
  1362. if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
  1363. let extStart;
  1364. let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
  1365. if (position + maxBytes > safeEnd)
  1366. target = makeRoom(position + maxBytes);
  1367. let lastBundle;
  1368. 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
  1369. lastBundle = bundledStrings;
  1370. target[position] = 0xc8; // ext 16
  1371. position += 3; // reserve for the writing bundle size
  1372. target[position++] = 0x62; // 'b'
  1373. extStart = position - start;
  1374. position += 4; // reserve for writing bundle reference
  1375. writeBundles(start, pack, 0); // write the last bundles
  1376. targetView.setUint16(extStart + start - 3, position - start - extStart);
  1377. } 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)
  1378. target[position++] = 0xd6; // fixext 4
  1379. target[position++] = 0x62; // 'b'
  1380. extStart = position - start;
  1381. position += 4; // reserve for writing bundle reference
  1382. }
  1383. bundledStrings = ['', '']; // create new ones
  1384. bundledStrings.previous = lastBundle;
  1385. bundledStrings.size = 0;
  1386. bundledStrings.position = extStart;
  1387. }
  1388. let twoByte = hasNonLatin.test(value);
  1389. bundledStrings[twoByte ? 0 : 1] += value;
  1390. target[position++] = 0xc1;
  1391. pack(twoByte ? -strLength : strLength);
  1392. return
  1393. }
  1394. let headerSize;
  1395. // first we estimate the header size, so we can write to the correct location
  1396. if (strLength < 0x20) {
  1397. headerSize = 1;
  1398. } else if (strLength < 0x100) {
  1399. headerSize = 2;
  1400. } else if (strLength < 0x10000) {
  1401. headerSize = 3;
  1402. } else {
  1403. headerSize = 5;
  1404. }
  1405. let maxBytes = strLength * 3;
  1406. if (position + maxBytes > safeEnd)
  1407. target = makeRoom(position + maxBytes);
  1408. if (strLength < 0x40 || !encodeUtf8) {
  1409. let i, c1, c2, strPosition = position + headerSize;
  1410. for (i = 0; i < strLength; i++) {
  1411. c1 = value.charCodeAt(i);
  1412. if (c1 < 0x80) {
  1413. target[strPosition++] = c1;
  1414. } else if (c1 < 0x800) {
  1415. target[strPosition++] = c1 >> 6 | 0xc0;
  1416. target[strPosition++] = c1 & 0x3f | 0x80;
  1417. } else if (
  1418. (c1 & 0xfc00) === 0xd800 &&
  1419. ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  1420. ) {
  1421. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  1422. i++;
  1423. target[strPosition++] = c1 >> 18 | 0xf0;
  1424. target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
  1425. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1426. target[strPosition++] = c1 & 0x3f | 0x80;
  1427. } else {
  1428. target[strPosition++] = c1 >> 12 | 0xe0;
  1429. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1430. target[strPosition++] = c1 & 0x3f | 0x80;
  1431. }
  1432. }
  1433. length = strPosition - position - headerSize;
  1434. } else {
  1435. length = encodeUtf8(value, position + headerSize);
  1436. }
  1437. if (length < 0x20) {
  1438. target[position++] = 0xa0 | length;
  1439. } else if (length < 0x100) {
  1440. if (headerSize < 2) {
  1441. target.copyWithin(position + 2, position + 1, position + 1 + length);
  1442. }
  1443. target[position++] = 0xd9;
  1444. target[position++] = length;
  1445. } else if (length < 0x10000) {
  1446. if (headerSize < 3) {
  1447. target.copyWithin(position + 3, position + 2, position + 2 + length);
  1448. }
  1449. target[position++] = 0xda;
  1450. target[position++] = length >> 8;
  1451. target[position++] = length & 0xff;
  1452. } else {
  1453. if (headerSize < 5) {
  1454. target.copyWithin(position + 5, position + 3, position + 3 + length);
  1455. }
  1456. target[position++] = 0xdb;
  1457. targetView.setUint32(position, length);
  1458. position += 4;
  1459. }
  1460. position += length;
  1461. } else if (type === 'number') {
  1462. if (value >>> 0 === value) {// positive integer, 32-bit or less
  1463. // positive uint
  1464. if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
  1465. target[position++] = value;
  1466. } else if (value < 0x100) {
  1467. target[position++] = 0xcc;
  1468. target[position++] = value;
  1469. } else if (value < 0x10000) {
  1470. target[position++] = 0xcd;
  1471. target[position++] = value >> 8;
  1472. target[position++] = value & 0xff;
  1473. } else {
  1474. target[position++] = 0xce;
  1475. targetView.setUint32(position, value);
  1476. position += 4;
  1477. }
  1478. } else if (value >> 0 === value) { // negative integer
  1479. if (value >= -0x20) {
  1480. target[position++] = 0x100 + value;
  1481. } else if (value >= -0x80) {
  1482. target[position++] = 0xd0;
  1483. target[position++] = value + 0x100;
  1484. } else if (value >= -0x8000) {
  1485. target[position++] = 0xd1;
  1486. targetView.setInt16(position, value);
  1487. position += 2;
  1488. } else {
  1489. target[position++] = 0xd2;
  1490. targetView.setInt32(position, value);
  1491. position += 4;
  1492. }
  1493. } else {
  1494. let useFloat32;
  1495. if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
  1496. target[position++] = 0xca;
  1497. targetView.setFloat32(position, value);
  1498. let xShifted;
  1499. if (useFloat32 < 4 ||
  1500. // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  1501. ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
  1502. position += 4;
  1503. return
  1504. } else
  1505. position--; // move back into position for writing a double
  1506. }
  1507. target[position++] = 0xcb;
  1508. targetView.setFloat64(position, value);
  1509. position += 8;
  1510. }
  1511. } else if (type === 'object' || type === 'function') {
  1512. if (!value)
  1513. target[position++] = 0xc0;
  1514. else {
  1515. if (referenceMap) {
  1516. let referee = referenceMap.get(value);
  1517. if (referee) {
  1518. if (!referee.id) {
  1519. let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
  1520. referee.id = idsToInsert.push(referee);
  1521. }
  1522. target[position++] = 0xd6; // fixext 4
  1523. target[position++] = 0x70; // "p" for pointer
  1524. targetView.setUint32(position, referee.id);
  1525. position += 4;
  1526. return
  1527. } else
  1528. referenceMap.set(value, { offset: position - start });
  1529. }
  1530. let constructor = value.constructor;
  1531. if (constructor === Object) {
  1532. writeObject(value);
  1533. } else if (constructor === Array) {
  1534. packArray(value);
  1535. } else if (constructor === Map) {
  1536. if (this.mapAsEmptyObject) target[position++] = 0x80;
  1537. else {
  1538. length = value.size;
  1539. if (length < 0x10) {
  1540. target[position++] = 0x80 | length;
  1541. } else if (length < 0x10000) {
  1542. target[position++] = 0xde;
  1543. target[position++] = length >> 8;
  1544. target[position++] = length & 0xff;
  1545. } else {
  1546. target[position++] = 0xdf;
  1547. targetView.setUint32(position, length);
  1548. position += 4;
  1549. }
  1550. for (let [key, entryValue] of value) {
  1551. pack(key);
  1552. pack(entryValue);
  1553. }
  1554. }
  1555. } else {
  1556. for (let i = 0, l = extensions.length; i < l; i++) {
  1557. let extensionClass = extensionClasses[i];
  1558. if (value instanceof extensionClass) {
  1559. let extension = extensions[i];
  1560. if (extension.write) {
  1561. if (extension.type) {
  1562. target[position++] = 0xd4; // one byte "tag" extension
  1563. target[position++] = extension.type;
  1564. target[position++] = 0;
  1565. }
  1566. let writeResult = extension.write.call(this, value);
  1567. if (writeResult === value) { // avoid infinite recursion
  1568. if (Array.isArray(value)) {
  1569. packArray(value);
  1570. } else {
  1571. writeObject(value);
  1572. }
  1573. } else {
  1574. pack(writeResult);
  1575. }
  1576. return
  1577. }
  1578. let currentTarget = target;
  1579. let currentTargetView = targetView;
  1580. let currentPosition = position;
  1581. target = null;
  1582. let result;
  1583. try {
  1584. result = extension.pack.call(this, value, (size) => {
  1585. // restore target and use it
  1586. target = currentTarget;
  1587. currentTarget = null;
  1588. position += size;
  1589. if (position > safeEnd)
  1590. makeRoom(position);
  1591. return {
  1592. target, targetView, position: position - size
  1593. }
  1594. }, pack);
  1595. } finally {
  1596. // restore current target information (unless already restored)
  1597. if (currentTarget) {
  1598. target = currentTarget;
  1599. targetView = currentTargetView;
  1600. position = currentPosition;
  1601. safeEnd = target.length - 10;
  1602. }
  1603. }
  1604. if (result) {
  1605. if (result.length + position > safeEnd)
  1606. makeRoom(result.length + position);
  1607. position = writeExtensionData(result, target, position, extension.type);
  1608. }
  1609. return
  1610. }
  1611. }
  1612. // check isArray after extensions, because extensions can extend Array
  1613. if (Array.isArray(value)) {
  1614. packArray(value);
  1615. } else {
  1616. // use this as an alternate mechanism for expressing how to serialize
  1617. if (value.toJSON) {
  1618. const json = value.toJSON();
  1619. // if for some reason value.toJSON returns itself it'll loop forever
  1620. if (json !== value)
  1621. return pack(json)
  1622. }
  1623. // if there is a writeFunction, use it, otherwise just encode as undefined
  1624. if (type === 'function')
  1625. return pack(this.writeFunction && this.writeFunction(value));
  1626. // no extension found, write as plain object
  1627. writeObject(value);
  1628. }
  1629. }
  1630. }
  1631. } else if (type === 'boolean') {
  1632. target[position++] = value ? 0xc3 : 0xc2;
  1633. } else if (type === 'bigint') {
  1634. if (value < 0x8000000000000000 && value >= -0x8000000000000000) {
  1635. // use a signed int as long as it fits
  1636. target[position++] = 0xd3;
  1637. targetView.setBigInt64(position, value);
  1638. } else if (value < 0x10000000000000000 && value > 0) {
  1639. // if we can fit an unsigned int, use that
  1640. target[position++] = 0xcf;
  1641. targetView.setBigUint64(position, value);
  1642. } else {
  1643. // overflow
  1644. if (this.largeBigIntToFloat) {
  1645. target[position++] = 0xcb;
  1646. targetView.setFloat64(position, Number(value));
  1647. } else if (this.largeBigIntToString) {
  1648. return pack(value.toString());
  1649. } else if (this.useBigIntExtension || this.moreTypes) {
  1650. let empty = value < 0 ? BigInt(-1) : BigInt(0);
  1651. let array;
  1652. if (value >> BigInt(0x10000) === empty) {
  1653. let mask = BigInt(0x10000000000000000) - BigInt(1); // literal would overflow
  1654. let chunks = [];
  1655. while (true) {
  1656. chunks.push(value & mask);
  1657. if ((value >> BigInt(63)) === empty) break
  1658. value >>= BigInt(64);
  1659. }
  1660. array = new Uint8Array(new BigUint64Array(chunks).buffer);
  1661. array.reverse();
  1662. } else {
  1663. let invert = value < 0;
  1664. let string = (invert ? ~value : value).toString(16);
  1665. if (string.length % 2) {
  1666. string = '0' + string;
  1667. } else if (parseInt(string.charAt(0), 16) >= 8) {
  1668. string = '00' + string;
  1669. }
  1670. if (hasNodeBuffer) {
  1671. array = Buffer.from(string, 'hex');
  1672. } else {
  1673. array = new Uint8Array(string.length / 2);
  1674. for (let i = 0; i < array.length; i++) {
  1675. array[i] = parseInt(string.slice(i * 2, i * 2 + 2), 16);
  1676. }
  1677. }
  1678. if (invert) {
  1679. for (let i = 0; i < array.length; i++) array[i] = ~array[i];
  1680. }
  1681. }
  1682. if (array.length + position > safeEnd)
  1683. makeRoom(array.length + position);
  1684. position = writeExtensionData(array, target, position, 0x42);
  1685. return
  1686. } else {
  1687. throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +
  1688. ' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +
  1689. ' largeBigIntToString to convert to string')
  1690. }
  1691. }
  1692. position += 8;
  1693. } else if (type === 'undefined') {
  1694. if (this.encodeUndefinedAsNil)
  1695. target[position++] = 0xc0;
  1696. else {
  1697. target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
  1698. target[position++] = 0;
  1699. target[position++] = 0;
  1700. }
  1701. } else {
  1702. throw new Error('Unknown type: ' + type)
  1703. }
  1704. };
  1705. const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {
  1706. // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
  1707. let keys;
  1708. if (this.skipValues) {
  1709. keys = [];
  1710. for (let key in object) {
  1711. if ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&
  1712. !this.skipValues.includes(object[key]))
  1713. keys.push(key);
  1714. }
  1715. } else {
  1716. keys = Object.keys(object);
  1717. }
  1718. let length = keys.length;
  1719. if (length < 0x10) {
  1720. target[position++] = 0x80 | length;
  1721. } else if (length < 0x10000) {
  1722. target[position++] = 0xde;
  1723. target[position++] = length >> 8;
  1724. target[position++] = length & 0xff;
  1725. } else {
  1726. target[position++] = 0xdf;
  1727. targetView.setUint32(position, length);
  1728. position += 4;
  1729. }
  1730. let key;
  1731. if (this.coercibleKeyAsNumber) {
  1732. for (let i = 0; i < length; i++) {
  1733. key = keys[i];
  1734. let num = Number(key);
  1735. pack(isNaN(num) ? key : num);
  1736. pack(object[key]);
  1737. }
  1738. } else {
  1739. for (let i = 0; i < length; i++) {
  1740. pack(key = keys[i]);
  1741. pack(object[key]);
  1742. }
  1743. }
  1744. } :
  1745. (object) => {
  1746. target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
  1747. let objectOffset = position - start;
  1748. position += 2;
  1749. let size = 0;
  1750. for (let key in object) {
  1751. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1752. pack(key);
  1753. pack(object[key]);
  1754. size++;
  1755. }
  1756. }
  1757. if (size > 0xffff) {
  1758. throw new Error('Object is too large to serialize with fast 16-bit map size,' +
  1759. ' use the "variableMapSize" option to serialize this object');
  1760. }
  1761. target[objectOffset++ + start] = size >> 8;
  1762. target[objectOffset + start] = size & 0xff;
  1763. };
  1764. const writeRecord = this.useRecords === false ? writePlainObject :
  1765. (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)
  1766. (object) => {
  1767. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1768. let objectOffset = position++ - start;
  1769. let wroteKeys;
  1770. for (let key in object) {
  1771. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1772. nextTransition = transition[key];
  1773. if (nextTransition)
  1774. transition = nextTransition;
  1775. else {
  1776. // record doesn't exist, create full new record and insert it
  1777. let keys = Object.keys(object);
  1778. let lastTransition = transition;
  1779. transition = structures.transitions;
  1780. let newTransitions = 0;
  1781. for (let i = 0, l = keys.length; i < l; i++) {
  1782. let key = keys[i];
  1783. nextTransition = transition[key];
  1784. if (!nextTransition) {
  1785. nextTransition = transition[key] = Object.create(null);
  1786. newTransitions++;
  1787. }
  1788. transition = nextTransition;
  1789. }
  1790. if (objectOffset + start + 1 == position) {
  1791. // first key, so we don't need to insert, we can just write record directly
  1792. position--;
  1793. newRecord(transition, keys, newTransitions);
  1794. } else // otherwise we need to insert the record, moving existing data after the record
  1795. insertNewRecord(transition, keys, objectOffset, newTransitions);
  1796. wroteKeys = true;
  1797. transition = lastTransition[key];
  1798. }
  1799. pack(object[key]);
  1800. }
  1801. }
  1802. if (!wroteKeys) {
  1803. let recordId = transition[RECORD_SYMBOL];
  1804. if (recordId)
  1805. target[objectOffset + start] = recordId;
  1806. else
  1807. insertNewRecord(transition, Object.keys(object), objectOffset, 0);
  1808. }
  1809. } :
  1810. (object) => {
  1811. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1812. let newTransitions = 0;
  1813. for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1814. nextTransition = transition[key];
  1815. if (!nextTransition) {
  1816. nextTransition = transition[key] = Object.create(null);
  1817. newTransitions++;
  1818. }
  1819. transition = nextTransition;
  1820. }
  1821. let recordId = transition[RECORD_SYMBOL];
  1822. if (recordId) {
  1823. if (recordId >= 0x60 && useTwoByteRecords) {
  1824. target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
  1825. target[position++] = recordId >> 5;
  1826. } else
  1827. target[position++] = recordId;
  1828. } else {
  1829. newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
  1830. }
  1831. // now write the values
  1832. for (let key in object)
  1833. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1834. pack(object[key]);
  1835. }
  1836. };
  1837. // create reference to useRecords if useRecords is a function
  1838. const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;
  1839. const writeObject = checkUseRecords ? (object) => {
  1840. checkUseRecords(object) ? writeRecord(object) : writePlainObject(object);
  1841. } : writeRecord;
  1842. const makeRoom = (end) => {
  1843. let newSize;
  1844. if (end > 0x1000000) {
  1845. // special handling for really large buffers
  1846. if ((end - start) > MAX_BUFFER_SIZE)
  1847. throw new Error('Packed buffer would be larger than maximum buffer size')
  1848. newSize = Math.min(MAX_BUFFER_SIZE,
  1849. Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
  1850. } else // faster handling for smaller buffers
  1851. newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
  1852. let newBuffer = new ByteArrayAllocate(newSize);
  1853. targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
  1854. end = Math.min(end, target.length);
  1855. if (target.copy)
  1856. target.copy(newBuffer, 0, start, end);
  1857. else
  1858. newBuffer.set(target.slice(start, end));
  1859. position -= start;
  1860. start = 0;
  1861. safeEnd = newBuffer.length - 10;
  1862. return target = newBuffer
  1863. };
  1864. const newRecord = (transition, keys, newTransitions) => {
  1865. let recordId = structures.nextId;
  1866. if (!recordId)
  1867. recordId = 0x40;
  1868. if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
  1869. recordId = structures.nextOwnId;
  1870. if (!(recordId < maxStructureId))
  1871. recordId = sharedLimitId;
  1872. structures.nextOwnId = recordId + 1;
  1873. } else {
  1874. if (recordId >= maxStructureId)// cycle back around
  1875. recordId = sharedLimitId;
  1876. structures.nextId = recordId + 1;
  1877. }
  1878. let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
  1879. transition[RECORD_SYMBOL] = recordId;
  1880. transition.__keys__ = keys;
  1881. structures[recordId - 0x40] = keys;
  1882. if (recordId < sharedLimitId) {
  1883. keys.isShared = true;
  1884. structures.sharedLength = recordId - 0x3f;
  1885. hasSharedUpdate = true;
  1886. if (highByte >= 0) {
  1887. target[position++] = (recordId & 0x1f) + 0x60;
  1888. target[position++] = highByte;
  1889. } else {
  1890. target[position++] = recordId;
  1891. }
  1892. } else {
  1893. if (highByte >= 0) {
  1894. target[position++] = 0xd5; // fixext 2
  1895. target[position++] = 0x72; // "r" record defintion extension type
  1896. target[position++] = (recordId & 0x1f) + 0x60;
  1897. target[position++] = highByte;
  1898. } else {
  1899. target[position++] = 0xd4; // fixext 1
  1900. target[position++] = 0x72; // "r" record defintion extension type
  1901. target[position++] = recordId;
  1902. }
  1903. if (newTransitions)
  1904. transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
  1905. // record the removal of the id, we can maintain our shared structure
  1906. if (recordIdsToRemove.length >= maxOwnStructures)
  1907. recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
  1908. recordIdsToRemove.push(transition);
  1909. pack(keys);
  1910. }
  1911. };
  1912. const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
  1913. let mainTarget = target;
  1914. let mainPosition = position;
  1915. let mainSafeEnd = safeEnd;
  1916. let mainStart = start;
  1917. target = keysTarget;
  1918. position = 0;
  1919. start = 0;
  1920. if (!target)
  1921. keysTarget = target = new ByteArrayAllocate(8192);
  1922. safeEnd = target.length - 10;
  1923. newRecord(transition, keys, newTransitions);
  1924. keysTarget = target;
  1925. let keysPosition = position;
  1926. target = mainTarget;
  1927. position = mainPosition;
  1928. safeEnd = mainSafeEnd;
  1929. start = mainStart;
  1930. if (keysPosition > 1) {
  1931. let newEnd = position + keysPosition - 1;
  1932. if (newEnd > safeEnd)
  1933. makeRoom(newEnd);
  1934. let insertionPosition = insertionOffset + start;
  1935. target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
  1936. target.set(keysTarget.slice(0, keysPosition), insertionPosition);
  1937. position = newEnd;
  1938. } else {
  1939. target[insertionOffset + start] = keysTarget[0];
  1940. }
  1941. };
  1942. const writeStruct = (object) => {
  1943. let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
  1944. if (notifySharedUpdate)
  1945. return hasSharedUpdate = true;
  1946. position = newPosition;
  1947. let startTarget = target;
  1948. pack(value);
  1949. resetStructures();
  1950. if (startTarget !== target) {
  1951. return { position, targetView, target }; // indicate the buffer was re-allocated
  1952. }
  1953. return position;
  1954. }, this);
  1955. if (newPosition === 0) // bail and go to a msgpack object
  1956. return writeObject(object);
  1957. position = newPosition;
  1958. };
  1959. }
  1960. useBuffer(buffer) {
  1961. // this means we are finished using our own buffer and we can write over it safely
  1962. target = buffer;
  1963. target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength));
  1964. targetView = target.dataView;
  1965. position = 0;
  1966. }
  1967. set position (value) {
  1968. position = value;
  1969. }
  1970. get position() {
  1971. return position;
  1972. }
  1973. clearSharedData() {
  1974. if (this.structures)
  1975. this.structures = [];
  1976. if (this.typedStructs)
  1977. this.typedStructs = [];
  1978. }
  1979. }
  1980. extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, DataView, C1Type ];
  1981. extensions = [{
  1982. pack(date, allocateForWrite, pack) {
  1983. let seconds = date.getTime() / 1000;
  1984. if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
  1985. // Timestamp 32
  1986. let { target, targetView, position} = allocateForWrite(6);
  1987. target[position++] = 0xd6;
  1988. target[position++] = 0xff;
  1989. targetView.setUint32(position, seconds);
  1990. } else if (seconds > 0 && seconds < 0x100000000) {
  1991. // Timestamp 64
  1992. let { target, targetView, position} = allocateForWrite(10);
  1993. target[position++] = 0xd7;
  1994. target[position++] = 0xff;
  1995. targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
  1996. targetView.setUint32(position + 4, seconds);
  1997. } else if (isNaN(seconds)) {
  1998. if (this.onInvalidDate) {
  1999. allocateForWrite(0);
  2000. return pack(this.onInvalidDate())
  2001. }
  2002. // Intentionally invalid timestamp
  2003. let { target, targetView, position} = allocateForWrite(3);
  2004. target[position++] = 0xd4;
  2005. target[position++] = 0xff;
  2006. target[position++] = 0xff;
  2007. } else {
  2008. // Timestamp 96
  2009. let { target, targetView, position} = allocateForWrite(15);
  2010. target[position++] = 0xc7;
  2011. target[position++] = 12;
  2012. target[position++] = 0xff;
  2013. targetView.setUint32(position, date.getMilliseconds() * 1000000);
  2014. targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
  2015. }
  2016. }
  2017. }, {
  2018. pack(set, allocateForWrite, pack) {
  2019. if (this.setAsEmptyObject) {
  2020. allocateForWrite(0);
  2021. return pack({})
  2022. }
  2023. let array = Array.from(set);
  2024. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2025. if (this.moreTypes) {
  2026. target[position++] = 0xd4;
  2027. target[position++] = 0x73; // 's' for Set
  2028. target[position++] = 0;
  2029. }
  2030. pack(array);
  2031. }
  2032. }, {
  2033. pack(error, allocateForWrite, pack) {
  2034. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2035. if (this.moreTypes) {
  2036. target[position++] = 0xd4;
  2037. target[position++] = 0x65; // 'e' for error
  2038. target[position++] = 0;
  2039. }
  2040. pack([ error.name, error.message, error.cause ]);
  2041. }
  2042. }, {
  2043. pack(regex, allocateForWrite, pack) {
  2044. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2045. if (this.moreTypes) {
  2046. target[position++] = 0xd4;
  2047. target[position++] = 0x78; // 'x' for regeXp
  2048. target[position++] = 0;
  2049. }
  2050. pack([ regex.source, regex.flags ]);
  2051. }
  2052. }, {
  2053. pack(arrayBuffer, allocateForWrite) {
  2054. if (this.moreTypes)
  2055. writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
  2056. else
  2057. writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  2058. }
  2059. }, {
  2060. pack(typedArray, allocateForWrite) {
  2061. let constructor = typedArray.constructor;
  2062. if (constructor !== ByteArray && this.moreTypes)
  2063. writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
  2064. else
  2065. writeBuffer(typedArray, allocateForWrite);
  2066. }
  2067. }, {
  2068. pack(arrayBuffer, allocateForWrite) {
  2069. if (this.moreTypes)
  2070. writeExtBuffer(arrayBuffer, 0x11, allocateForWrite);
  2071. else
  2072. writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  2073. }
  2074. }, {
  2075. pack(c1, allocateForWrite) { // specific 0xC1 object
  2076. let { target, position} = allocateForWrite(1);
  2077. target[position] = 0xc1;
  2078. }
  2079. }];
  2080. function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
  2081. let length = typedArray.byteLength;
  2082. if (length + 1 < 0x100) {
  2083. var { target, position } = allocateForWrite(4 + length);
  2084. target[position++] = 0xc7;
  2085. target[position++] = length + 1;
  2086. } else if (length + 1 < 0x10000) {
  2087. var { target, position } = allocateForWrite(5 + length);
  2088. target[position++] = 0xc8;
  2089. target[position++] = (length + 1) >> 8;
  2090. target[position++] = (length + 1) & 0xff;
  2091. } else {
  2092. var { target, position, targetView } = allocateForWrite(7 + length);
  2093. target[position++] = 0xc9;
  2094. targetView.setUint32(position, length + 1); // plus one for the type byte
  2095. position += 4;
  2096. }
  2097. target[position++] = 0x74; // "t" for typed array
  2098. target[position++] = type;
  2099. if (!typedArray.buffer) typedArray = new Uint8Array(typedArray);
  2100. target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
  2101. }
  2102. function writeBuffer(buffer, allocateForWrite) {
  2103. let length = buffer.byteLength;
  2104. var target, position;
  2105. if (length < 0x100) {
  2106. var { target, position } = allocateForWrite(length + 2);
  2107. target[position++] = 0xc4;
  2108. target[position++] = length;
  2109. } else if (length < 0x10000) {
  2110. var { target, position } = allocateForWrite(length + 3);
  2111. target[position++] = 0xc5;
  2112. target[position++] = length >> 8;
  2113. target[position++] = length & 0xff;
  2114. } else {
  2115. var { target, position, targetView } = allocateForWrite(length + 5);
  2116. target[position++] = 0xc6;
  2117. targetView.setUint32(position, length);
  2118. position += 4;
  2119. }
  2120. target.set(buffer, position);
  2121. }
  2122. function writeExtensionData(result, target, position, type) {
  2123. let length = result.length;
  2124. switch (length) {
  2125. case 1:
  2126. target[position++] = 0xd4;
  2127. break
  2128. case 2:
  2129. target[position++] = 0xd5;
  2130. break
  2131. case 4:
  2132. target[position++] = 0xd6;
  2133. break
  2134. case 8:
  2135. target[position++] = 0xd7;
  2136. break
  2137. case 16:
  2138. target[position++] = 0xd8;
  2139. break
  2140. default:
  2141. if (length < 0x100) {
  2142. target[position++] = 0xc7;
  2143. target[position++] = length;
  2144. } else if (length < 0x10000) {
  2145. target[position++] = 0xc8;
  2146. target[position++] = length >> 8;
  2147. target[position++] = length & 0xff;
  2148. } else {
  2149. target[position++] = 0xc9;
  2150. target[position++] = length >> 24;
  2151. target[position++] = (length >> 16) & 0xff;
  2152. target[position++] = (length >> 8) & 0xff;
  2153. target[position++] = length & 0xff;
  2154. }
  2155. }
  2156. target[position++] = type;
  2157. target.set(result, position);
  2158. position += length;
  2159. return position
  2160. }
  2161. function insertIds(serialized, idsToInsert) {
  2162. // insert the ids that need to be referenced for structured clones
  2163. let nextId;
  2164. let distanceToMove = idsToInsert.length * 6;
  2165. let lastEnd = serialized.length - distanceToMove;
  2166. while (nextId = idsToInsert.pop()) {
  2167. let offset = nextId.offset;
  2168. let id = nextId.id;
  2169. serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
  2170. distanceToMove -= 6;
  2171. let position = offset + distanceToMove;
  2172. serialized[position++] = 0xd6;
  2173. serialized[position++] = 0x69; // 'i'
  2174. serialized[position++] = id >> 24;
  2175. serialized[position++] = (id >> 16) & 0xff;
  2176. serialized[position++] = (id >> 8) & 0xff;
  2177. serialized[position++] = id & 0xff;
  2178. lastEnd = offset;
  2179. }
  2180. return serialized
  2181. }
  2182. function writeBundles(start, pack, incrementPosition) {
  2183. if (bundledStrings.length > 0) {
  2184. targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
  2185. bundledStrings.stringsPosition = position - start;
  2186. let writeStrings = bundledStrings;
  2187. bundledStrings = null;
  2188. pack(writeStrings[0]);
  2189. pack(writeStrings[1]);
  2190. }
  2191. }
  2192. function addExtension(extension) {
  2193. if (extension.Class) {
  2194. if (!extension.pack && !extension.write)
  2195. throw new Error('Extension has no pack or write function')
  2196. if (extension.pack && !extension.type)
  2197. throw new Error('Extension has no type (numeric code to identify the extension)')
  2198. extensionClasses.unshift(extension.Class);
  2199. extensions.unshift(extension);
  2200. }
  2201. addExtension$1(extension);
  2202. }
  2203. function prepareStructures(structures, packr) {
  2204. structures.isCompatible = (existingStructures) => {
  2205. let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
  2206. if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
  2207. packr._mergeStructures(existingStructures);
  2208. return compatible;
  2209. };
  2210. return structures
  2211. }
  2212. let defaultPackr = new Packr({ useRecords: false });
  2213. const pack = defaultPackr.pack;
  2214. const encode = defaultPackr.pack;
  2215. const Encoder = Packr;
  2216. const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
  2217. const REUSE_BUFFER_MODE = 512;
  2218. const RESET_BUFFER_MODE = 1024;
  2219. const RESERVE_START_SPACE = 2048;
  2220. /**
  2221. * Given an Iterable first argument, returns an Iterable where each value is packed as a Buffer
  2222. * If the argument is only Async Iterable, the return value will be an Async Iterable.
  2223. * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
  2224. * @param {options} [options] - msgpackr pack options
  2225. * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
  2226. */
  2227. function packIter (objectIterator, options = {}) {
  2228. if (!objectIterator || typeof objectIterator !== 'object') {
  2229. throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
  2230. } else if (typeof objectIterator[Symbol.iterator] === 'function') {
  2231. return packIterSync(objectIterator, options)
  2232. } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
  2233. return packIterAsync(objectIterator, options)
  2234. } else {
  2235. throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
  2236. }
  2237. }
  2238. function * packIterSync (objectIterator, options) {
  2239. const packr = new Packr(options);
  2240. for (const value of objectIterator) {
  2241. yield packr.pack(value);
  2242. }
  2243. }
  2244. async function * packIterAsync (objectIterator, options) {
  2245. const packr = new Packr(options);
  2246. for await (const value of objectIterator) {
  2247. yield packr.pack(value);
  2248. }
  2249. }
  2250. /**
  2251. * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
  2252. * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
  2253. * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
  2254. * @param {object} [options] - unpackr options
  2255. * @returns {IterableIterator|Promise.<AsyncIterableIterator}
  2256. */
  2257. function unpackIter (bufferIterator, options = {}) {
  2258. if (!bufferIterator || typeof bufferIterator !== 'object') {
  2259. throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
  2260. }
  2261. const unpackr = new Unpackr(options);
  2262. let incomplete;
  2263. const parser = (chunk) => {
  2264. let yields;
  2265. // if there's incomplete data from previous chunk, concatinate and try again
  2266. if (incomplete) {
  2267. chunk = Buffer.concat([incomplete, chunk]);
  2268. incomplete = undefined;
  2269. }
  2270. try {
  2271. yields = unpackr.unpackMultiple(chunk);
  2272. } catch (err) {
  2273. if (err.incomplete) {
  2274. incomplete = chunk.slice(err.lastPosition);
  2275. yields = err.values;
  2276. } else {
  2277. throw err
  2278. }
  2279. }
  2280. return yields
  2281. };
  2282. if (typeof bufferIterator[Symbol.iterator] === 'function') {
  2283. return (function * iter () {
  2284. for (const value of bufferIterator) {
  2285. yield * parser(value);
  2286. }
  2287. })()
  2288. } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
  2289. return (async function * iter () {
  2290. for await (const value of bufferIterator) {
  2291. yield * parser(value);
  2292. }
  2293. })()
  2294. }
  2295. }
  2296. const decodeIter = unpackIter;
  2297. const encodeIter = packIter;
  2298. const useRecords = false;
  2299. const mapsAsObjects = true;
  2300. exports.ALWAYS = ALWAYS;
  2301. exports.C1 = C1;
  2302. exports.DECIMAL_FIT = DECIMAL_FIT;
  2303. exports.DECIMAL_ROUND = DECIMAL_ROUND;
  2304. exports.Decoder = Decoder;
  2305. exports.Encoder = Encoder;
  2306. exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
  2307. exports.NEVER = NEVER;
  2308. exports.Packr = Packr;
  2309. exports.RESERVE_START_SPACE = RESERVE_START_SPACE;
  2310. exports.RESET_BUFFER_MODE = RESET_BUFFER_MODE;
  2311. exports.REUSE_BUFFER_MODE = REUSE_BUFFER_MODE;
  2312. exports.Unpackr = Unpackr;
  2313. exports.addExtension = addExtension;
  2314. exports.clearSource = clearSource;
  2315. exports.decode = decode;
  2316. exports.decodeIter = decodeIter;
  2317. exports.encode = encode;
  2318. exports.encodeIter = encodeIter;
  2319. exports.isNativeAccelerationEnabled = isNativeAccelerationEnabled;
  2320. exports.mapsAsObjects = mapsAsObjects;
  2321. exports.pack = pack;
  2322. exports.roundFloat32 = roundFloat32;
  2323. exports.unpack = unpack;
  2324. exports.unpackMultiple = unpackMultiple;
  2325. exports.useRecords = useRecords;
  2326. }));
  2327. //# sourceMappingURL=index.js.map