unpack-no-eval.cjs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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 = 0;
  13. const EMPTY_ARRAY = [];
  14. var strings = EMPTY_ARRAY;
  15. var stringPosition = 0;
  16. var currentUnpackr = {};
  17. var currentStructures;
  18. var srcString;
  19. var srcStringStart = 0;
  20. var srcStringEnd = 0;
  21. var bundledStrings;
  22. var referenceMap;
  23. var currentExtensions = [];
  24. var dataView;
  25. var defaultOptions = {
  26. useRecords: false,
  27. mapsAsObjects: true
  28. };
  29. class C1Type {}
  30. const C1 = new C1Type();
  31. C1.name = 'MessagePack 0xC1';
  32. var sequentialMode = false;
  33. var inlineObjectReadThreshold = 2;
  34. var readStruct, onLoadedStructures, onSaveState;
  35. var BlockedFunction; // we use search and replace to change the next call to BlockedFunction to avoid CSP issues for
  36. // no-eval build
  37. try {
  38. new BlockedFunction ('');
  39. } catch(error) {
  40. // if eval variants are not supported, do not create inline object readers ever
  41. inlineObjectReadThreshold = Infinity;
  42. }
  43. class Unpackr {
  44. constructor(options) {
  45. if (options) {
  46. if (options.useRecords === false && options.mapsAsObjects === undefined)
  47. options.mapsAsObjects = true;
  48. if (options.sequential && options.trusted !== false) {
  49. options.trusted = true;
  50. if (!options.structures && options.useRecords != false) {
  51. options.structures = [];
  52. if (!options.maxSharedStructures)
  53. options.maxSharedStructures = 0;
  54. }
  55. }
  56. if (options.structures)
  57. options.structures.sharedLength = options.structures.length;
  58. else if (options.getStructures) {
  59. (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
  60. options.structures.sharedLength = 0;
  61. }
  62. if (options.int64AsNumber) {
  63. options.int64AsType = 'number';
  64. }
  65. }
  66. Object.assign(this, options);
  67. }
  68. unpack(source, options) {
  69. if (src) {
  70. // re-entrant execution, save the state and restore it after we do this unpack
  71. return saveState(() => {
  72. clearSource();
  73. return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options)
  74. })
  75. }
  76. if (!source.buffer && source.constructor === ArrayBuffer)
  77. source = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);
  78. if (typeof options === 'object') {
  79. srcEnd = options.end || source.length;
  80. position = options.start || 0;
  81. } else {
  82. position = 0;
  83. srcEnd = options > -1 ? options : source.length;
  84. }
  85. stringPosition = 0;
  86. srcStringEnd = 0;
  87. srcString = null;
  88. strings = EMPTY_ARRAY;
  89. bundledStrings = null;
  90. src = source;
  91. // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
  92. // technique for getting data from a database where it can be copied into an existing buffer instead of creating
  93. // new ones
  94. try {
  95. dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
  96. } catch(error) {
  97. // if it doesn't have a buffer, maybe it is the wrong type of object
  98. src = null;
  99. if (source instanceof Uint8Array)
  100. throw error
  101. throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
  102. }
  103. if (this instanceof Unpackr) {
  104. currentUnpackr = this;
  105. if (this.structures) {
  106. currentStructures = this.structures;
  107. return checkedRead(options)
  108. } else if (!currentStructures || currentStructures.length > 0) {
  109. currentStructures = [];
  110. }
  111. } else {
  112. currentUnpackr = defaultOptions;
  113. if (!currentStructures || currentStructures.length > 0)
  114. currentStructures = [];
  115. }
  116. return checkedRead(options)
  117. }
  118. unpackMultiple(source, forEach) {
  119. let values, lastPosition = 0;
  120. try {
  121. sequentialMode = true;
  122. let size = source.length;
  123. let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
  124. if (forEach) {
  125. if (forEach(value, lastPosition, position) === false) return;
  126. while(position < size) {
  127. lastPosition = position;
  128. if (forEach(checkedRead(), lastPosition, position) === false) {
  129. return
  130. }
  131. }
  132. }
  133. else {
  134. values = [ value ];
  135. while(position < size) {
  136. lastPosition = position;
  137. values.push(checkedRead());
  138. }
  139. return values
  140. }
  141. } catch(error) {
  142. error.lastPosition = lastPosition;
  143. error.values = values;
  144. throw error
  145. } finally {
  146. sequentialMode = false;
  147. clearSource();
  148. }
  149. }
  150. _mergeStructures(loadedStructures, existingStructures) {
  151. if (onLoadedStructures)
  152. loadedStructures = onLoadedStructures.call(this, loadedStructures);
  153. loadedStructures = loadedStructures || [];
  154. if (Object.isFrozen(loadedStructures))
  155. loadedStructures = loadedStructures.map(structure => structure.slice(0));
  156. for (let i = 0, l = loadedStructures.length; i < l; i++) {
  157. let structure = loadedStructures[i];
  158. if (structure) {
  159. structure.isShared = true;
  160. if (i >= 32)
  161. structure.highByte = (i - 32) >> 5;
  162. }
  163. }
  164. loadedStructures.sharedLength = loadedStructures.length;
  165. for (let id in existingStructures || []) {
  166. if (id >= 0) {
  167. let structure = loadedStructures[id];
  168. let existing = existingStructures[id];
  169. if (existing) {
  170. if (structure)
  171. (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
  172. loadedStructures[id] = existing;
  173. }
  174. }
  175. }
  176. return this.structures = loadedStructures
  177. }
  178. decode(source, options) {
  179. return this.unpack(source, options)
  180. }
  181. }
  182. function getPosition() {
  183. return position
  184. }
  185. function checkedRead(options) {
  186. try {
  187. if (!currentUnpackr.trusted && !sequentialMode) {
  188. let sharedLength = currentStructures.sharedLength || 0;
  189. if (sharedLength < currentStructures.length)
  190. currentStructures.length = sharedLength;
  191. }
  192. let result;
  193. if (currentUnpackr.randomAccessStructure && src[position] < 0x40 && src[position] >= 0x20 && readStruct) {
  194. result = readStruct(src, position, srcEnd, currentUnpackr);
  195. src = null; // dispose of this so that recursive unpack calls don't save state
  196. if (!(options && options.lazy) && result)
  197. result = result.toJSON();
  198. position = srcEnd;
  199. } else
  200. result = read();
  201. if (bundledStrings) { // bundled strings to skip past
  202. position = bundledStrings.postBundlePosition;
  203. bundledStrings = null;
  204. }
  205. if (sequentialMode)
  206. // we only need to restore the structures if there was an error, but if we completed a read,
  207. // we can clear this out and keep the structures we read
  208. currentStructures.restoreStructures = null;
  209. if (position == srcEnd) {
  210. // finished reading this source, cleanup references
  211. if (currentStructures && currentStructures.restoreStructures)
  212. restoreStructures();
  213. currentStructures = null;
  214. src = null;
  215. if (referenceMap)
  216. referenceMap = null;
  217. } else if (position > srcEnd) {
  218. // over read
  219. throw new Error('Unexpected end of MessagePack data')
  220. } else if (!sequentialMode) {
  221. let jsonView;
  222. try {
  223. jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100);
  224. } catch(error) {
  225. jsonView = '(JSON view not available ' + error + ')';
  226. }
  227. throw new Error('Data read, but end of buffer not reached ' + jsonView)
  228. }
  229. // else more to read, but we are reading sequentially, so don't clear source yet
  230. return result
  231. } catch(error) {
  232. if (currentStructures && currentStructures.restoreStructures)
  233. restoreStructures();
  234. clearSource();
  235. if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {
  236. error.incomplete = true;
  237. }
  238. throw error
  239. }
  240. }
  241. function restoreStructures() {
  242. for (let id in currentStructures.restoreStructures) {
  243. currentStructures[id] = currentStructures.restoreStructures[id];
  244. }
  245. currentStructures.restoreStructures = null;
  246. }
  247. function read() {
  248. let token = src[position++];
  249. if (token < 0xa0) {
  250. if (token < 0x80) {
  251. if (token < 0x40)
  252. return token
  253. else {
  254. let structure = currentStructures[token & 0x3f] ||
  255. currentUnpackr.getStructures && loadStructures()[token & 0x3f];
  256. if (structure) {
  257. if (!structure.read) {
  258. structure.read = createStructureReader(structure, token & 0x3f);
  259. }
  260. return structure.read()
  261. } else
  262. return token
  263. }
  264. } else if (token < 0x90) {
  265. // map
  266. token -= 0x80;
  267. if (currentUnpackr.mapsAsObjects) {
  268. let object = {};
  269. for (let i = 0; i < token; i++) {
  270. let key = readKey();
  271. if (key === '__proto__')
  272. key = '__proto_';
  273. object[key] = read();
  274. }
  275. return object
  276. } else {
  277. let map = new Map();
  278. for (let i = 0; i < token; i++) {
  279. map.set(read(), read());
  280. }
  281. return map
  282. }
  283. } else {
  284. token -= 0x90;
  285. let array = new Array(token);
  286. for (let i = 0; i < token; i++) {
  287. array[i] = read();
  288. }
  289. if (currentUnpackr.freezeData)
  290. return Object.freeze(array)
  291. return array
  292. }
  293. } else if (token < 0xc0) {
  294. // fixstr
  295. let length = token - 0xa0;
  296. if (srcStringEnd >= position) {
  297. return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
  298. }
  299. if (srcStringEnd == 0 && srcEnd < 140) {
  300. // for small blocks, avoiding the overhead of the extract call is helpful
  301. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  302. if (string != null)
  303. return string
  304. }
  305. return readFixedString(length)
  306. } else {
  307. let value;
  308. switch (token) {
  309. case 0xc0: return null
  310. case 0xc1:
  311. if (bundledStrings) {
  312. value = read(); // followed by the length of the string in characters (not bytes!)
  313. if (value > 0)
  314. return bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)
  315. else
  316. return bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value)
  317. }
  318. return C1; // "never-used", return special object to denote that
  319. case 0xc2: return false
  320. case 0xc3: return true
  321. case 0xc4:
  322. // bin 8
  323. value = src[position++];
  324. if (value === undefined)
  325. throw new Error('Unexpected end of buffer')
  326. return readBin(value)
  327. case 0xc5:
  328. // bin 16
  329. value = dataView.getUint16(position);
  330. position += 2;
  331. return readBin(value)
  332. case 0xc6:
  333. // bin 32
  334. value = dataView.getUint32(position);
  335. position += 4;
  336. return readBin(value)
  337. case 0xc7:
  338. // ext 8
  339. return readExt(src[position++])
  340. case 0xc8:
  341. // ext 16
  342. value = dataView.getUint16(position);
  343. position += 2;
  344. return readExt(value)
  345. case 0xc9:
  346. // ext 32
  347. value = dataView.getUint32(position);
  348. position += 4;
  349. return readExt(value)
  350. case 0xca:
  351. value = dataView.getFloat32(position);
  352. if (currentUnpackr.useFloat32 > 2) {
  353. // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  354. let multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];
  355. position += 4;
  356. return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  357. }
  358. position += 4;
  359. return value
  360. case 0xcb:
  361. value = dataView.getFloat64(position);
  362. position += 8;
  363. return value
  364. // uint handlers
  365. case 0xcc:
  366. return src[position++]
  367. case 0xcd:
  368. value = dataView.getUint16(position);
  369. position += 2;
  370. return value
  371. case 0xce:
  372. value = dataView.getUint32(position);
  373. position += 4;
  374. return value
  375. case 0xcf:
  376. if (currentUnpackr.int64AsType === 'number') {
  377. value = dataView.getUint32(position) * 0x100000000;
  378. value += dataView.getUint32(position + 4);
  379. } else if (currentUnpackr.int64AsType === 'string') {
  380. value = dataView.getBigUint64(position).toString();
  381. } else if (currentUnpackr.int64AsType === 'auto') {
  382. value = dataView.getBigUint64(position);
  383. if (value<=BigInt(2)<<BigInt(52)) value=Number(value);
  384. } else
  385. value = dataView.getBigUint64(position);
  386. position += 8;
  387. return value
  388. // int handlers
  389. case 0xd0:
  390. return dataView.getInt8(position++)
  391. case 0xd1:
  392. value = dataView.getInt16(position);
  393. position += 2;
  394. return value
  395. case 0xd2:
  396. value = dataView.getInt32(position);
  397. position += 4;
  398. return value
  399. case 0xd3:
  400. if (currentUnpackr.int64AsType === 'number') {
  401. value = dataView.getInt32(position) * 0x100000000;
  402. value += dataView.getUint32(position + 4);
  403. } else if (currentUnpackr.int64AsType === 'string') {
  404. value = dataView.getBigInt64(position).toString();
  405. } else if (currentUnpackr.int64AsType === 'auto') {
  406. value = dataView.getBigInt64(position);
  407. if (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);
  408. } else
  409. value = dataView.getBigInt64(position);
  410. position += 8;
  411. return value
  412. case 0xd4:
  413. // fixext 1
  414. value = src[position++];
  415. if (value == 0x72) {
  416. return recordDefinition(src[position++] & 0x3f)
  417. } else {
  418. let extension = currentExtensions[value];
  419. if (extension) {
  420. if (extension.read) {
  421. position++; // skip filler byte
  422. return extension.read(read())
  423. } else if (extension.noBuffer) {
  424. position++; // skip filler byte
  425. return extension()
  426. } else
  427. return extension(src.subarray(position, ++position))
  428. } else
  429. throw new Error('Unknown extension ' + value)
  430. }
  431. case 0xd5:
  432. // fixext 2
  433. value = src[position];
  434. if (value == 0x72) {
  435. position++;
  436. return recordDefinition(src[position++] & 0x3f, src[position++])
  437. } else
  438. return readExt(2)
  439. case 0xd6:
  440. // fixext 4
  441. return readExt(4)
  442. case 0xd7:
  443. // fixext 8
  444. return readExt(8)
  445. case 0xd8:
  446. // fixext 16
  447. return readExt(16)
  448. case 0xd9:
  449. // str 8
  450. value = src[position++];
  451. if (srcStringEnd >= position) {
  452. return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
  453. }
  454. return readString8(value)
  455. case 0xda:
  456. // str 16
  457. value = dataView.getUint16(position);
  458. position += 2;
  459. if (srcStringEnd >= position) {
  460. return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
  461. }
  462. return readString16(value)
  463. case 0xdb:
  464. // str 32
  465. value = dataView.getUint32(position);
  466. position += 4;
  467. if (srcStringEnd >= position) {
  468. return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
  469. }
  470. return readString32(value)
  471. case 0xdc:
  472. // array 16
  473. value = dataView.getUint16(position);
  474. position += 2;
  475. return readArray(value)
  476. case 0xdd:
  477. // array 32
  478. value = dataView.getUint32(position);
  479. position += 4;
  480. return readArray(value)
  481. case 0xde:
  482. // map 16
  483. value = dataView.getUint16(position);
  484. position += 2;
  485. return readMap(value)
  486. case 0xdf:
  487. // map 32
  488. value = dataView.getUint32(position);
  489. position += 4;
  490. return readMap(value)
  491. default: // negative int
  492. if (token >= 0xe0)
  493. return token - 0x100
  494. if (token === undefined) {
  495. let error = new Error('Unexpected end of MessagePack data');
  496. error.incomplete = true;
  497. throw error
  498. }
  499. throw new Error('Unknown MessagePack token ' + token)
  500. }
  501. }
  502. }
  503. const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
  504. function createStructureReader(structure, firstId) {
  505. function readObject() {
  506. // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
  507. if (readObject.count++ > inlineObjectReadThreshold) {
  508. let readObject = structure.read = (new BlockedFunction ('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
  509. '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
  510. if (structure.highByte === 0)
  511. structure.read = createSecondByteReader(firstId, structure.read);
  512. return readObject() // second byte is already read, if there is one so immediately read object
  513. }
  514. let object = {};
  515. for (let i = 0, l = structure.length; i < l; i++) {
  516. let key = structure[i];
  517. if (key === '__proto__')
  518. key = '__proto_';
  519. object[key] = read();
  520. }
  521. if (currentUnpackr.freezeData)
  522. return Object.freeze(object);
  523. return object
  524. }
  525. readObject.count = 0;
  526. if (structure.highByte === 0) {
  527. return createSecondByteReader(firstId, readObject)
  528. }
  529. return readObject
  530. }
  531. const createSecondByteReader = (firstId, read0) => {
  532. return function() {
  533. let highByte = src[position++];
  534. if (highByte === 0)
  535. return read0()
  536. let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
  537. let structure = currentStructures[id] || loadStructures()[id];
  538. if (!structure) {
  539. throw new Error('Record id is not defined for ' + id)
  540. }
  541. if (!structure.read)
  542. structure.read = createStructureReader(structure, firstId);
  543. return structure.read()
  544. }
  545. };
  546. function loadStructures() {
  547. let loadedStructures = saveState(() => {
  548. // save the state in case getStructures modifies our buffer
  549. src = null;
  550. return currentUnpackr.getStructures()
  551. });
  552. return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
  553. }
  554. var readFixedString = readStringJS;
  555. var readString8 = readStringJS;
  556. var readString16 = readStringJS;
  557. var readString32 = readStringJS;
  558. exports.isNativeAccelerationEnabled = false;
  559. function setExtractor(extractStrings) {
  560. exports.isNativeAccelerationEnabled = true;
  561. readFixedString = readString(1);
  562. readString8 = readString(2);
  563. readString16 = readString(3);
  564. readString32 = readString(5);
  565. function readString(headerLength) {
  566. return function readString(length) {
  567. let string = strings[stringPosition++];
  568. if (string == null) {
  569. if (bundledStrings)
  570. return readStringJS(length)
  571. let byteOffset = src.byteOffset;
  572. let extraction = extractStrings(position - headerLength + byteOffset, srcEnd + byteOffset, src.buffer);
  573. if (typeof extraction == 'string') {
  574. string = extraction;
  575. strings = EMPTY_ARRAY;
  576. } else {
  577. strings = extraction;
  578. stringPosition = 1;
  579. srcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings
  580. string = strings[0];
  581. if (string === undefined)
  582. throw new Error('Unexpected end of buffer')
  583. }
  584. }
  585. let srcStringLength = string.length;
  586. if (srcStringLength <= length) {
  587. position += length;
  588. return string
  589. }
  590. srcString = string;
  591. srcStringStart = position;
  592. srcStringEnd = position + srcStringLength;
  593. position += length;
  594. return string.slice(0, length) // we know we just want the beginning
  595. }
  596. }
  597. }
  598. function readStringJS(length) {
  599. let result;
  600. if (length < 16) {
  601. if (result = shortStringInJS(length))
  602. return result
  603. }
  604. if (length > 64 && decoder)
  605. return decoder.decode(src.subarray(position, position += length))
  606. const end = position + length;
  607. const units = [];
  608. result = '';
  609. while (position < end) {
  610. const byte1 = src[position++];
  611. if ((byte1 & 0x80) === 0) {
  612. // 1 byte
  613. units.push(byte1);
  614. } else if ((byte1 & 0xe0) === 0xc0) {
  615. // 2 bytes
  616. const byte2 = src[position++] & 0x3f;
  617. units.push(((byte1 & 0x1f) << 6) | byte2);
  618. } else if ((byte1 & 0xf0) === 0xe0) {
  619. // 3 bytes
  620. const byte2 = src[position++] & 0x3f;
  621. const byte3 = src[position++] & 0x3f;
  622. units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
  623. } else if ((byte1 & 0xf8) === 0xf0) {
  624. // 4 bytes
  625. const byte2 = src[position++] & 0x3f;
  626. const byte3 = src[position++] & 0x3f;
  627. const byte4 = src[position++] & 0x3f;
  628. let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
  629. if (unit > 0xffff) {
  630. unit -= 0x10000;
  631. units.push(((unit >>> 10) & 0x3ff) | 0xd800);
  632. unit = 0xdc00 | (unit & 0x3ff);
  633. }
  634. units.push(unit);
  635. } else {
  636. units.push(byte1);
  637. }
  638. if (units.length >= 0x1000) {
  639. result += fromCharCode.apply(String, units);
  640. units.length = 0;
  641. }
  642. }
  643. if (units.length > 0) {
  644. result += fromCharCode.apply(String, units);
  645. }
  646. return result
  647. }
  648. function readString(source, start, length) {
  649. let existingSrc = src;
  650. src = source;
  651. position = start;
  652. try {
  653. return readStringJS(length);
  654. } finally {
  655. src = existingSrc;
  656. }
  657. }
  658. function readArray(length) {
  659. let array = new Array(length);
  660. for (let i = 0; i < length; i++) {
  661. array[i] = read();
  662. }
  663. if (currentUnpackr.freezeData)
  664. return Object.freeze(array)
  665. return array
  666. }
  667. function readMap(length) {
  668. if (currentUnpackr.mapsAsObjects) {
  669. let object = {};
  670. for (let i = 0; i < length; i++) {
  671. let key = readKey();
  672. if (key === '__proto__')
  673. key = '__proto_';
  674. object[key] = read();
  675. }
  676. return object
  677. } else {
  678. let map = new Map();
  679. for (let i = 0; i < length; i++) {
  680. map.set(read(), read());
  681. }
  682. return map
  683. }
  684. }
  685. var fromCharCode = String.fromCharCode;
  686. function longStringInJS(length) {
  687. let start = position;
  688. let bytes = new Array(length);
  689. for (let i = 0; i < length; i++) {
  690. const byte = src[position++];
  691. if ((byte & 0x80) > 0) {
  692. position = start;
  693. return
  694. }
  695. bytes[i] = byte;
  696. }
  697. return fromCharCode.apply(String, bytes)
  698. }
  699. function shortStringInJS(length) {
  700. if (length < 4) {
  701. if (length < 2) {
  702. if (length === 0)
  703. return ''
  704. else {
  705. let a = src[position++];
  706. if ((a & 0x80) > 1) {
  707. position -= 1;
  708. return
  709. }
  710. return fromCharCode(a)
  711. }
  712. } else {
  713. let a = src[position++];
  714. let b = src[position++];
  715. if ((a & 0x80) > 0 || (b & 0x80) > 0) {
  716. position -= 2;
  717. return
  718. }
  719. if (length < 3)
  720. return fromCharCode(a, b)
  721. let c = src[position++];
  722. if ((c & 0x80) > 0) {
  723. position -= 3;
  724. return
  725. }
  726. return fromCharCode(a, b, c)
  727. }
  728. } else {
  729. let a = src[position++];
  730. let b = src[position++];
  731. let c = src[position++];
  732. let d = src[position++];
  733. if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
  734. position -= 4;
  735. return
  736. }
  737. if (length < 6) {
  738. if (length === 4)
  739. return fromCharCode(a, b, c, d)
  740. else {
  741. let e = src[position++];
  742. if ((e & 0x80) > 0) {
  743. position -= 5;
  744. return
  745. }
  746. return fromCharCode(a, b, c, d, e)
  747. }
  748. } else if (length < 8) {
  749. let e = src[position++];
  750. let f = src[position++];
  751. if ((e & 0x80) > 0 || (f & 0x80) > 0) {
  752. position -= 6;
  753. return
  754. }
  755. if (length < 7)
  756. return fromCharCode(a, b, c, d, e, f)
  757. let g = src[position++];
  758. if ((g & 0x80) > 0) {
  759. position -= 7;
  760. return
  761. }
  762. return fromCharCode(a, b, c, d, e, f, g)
  763. } else {
  764. let e = src[position++];
  765. let f = src[position++];
  766. let g = src[position++];
  767. let h = src[position++];
  768. if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
  769. position -= 8;
  770. return
  771. }
  772. if (length < 10) {
  773. if (length === 8)
  774. return fromCharCode(a, b, c, d, e, f, g, h)
  775. else {
  776. let i = src[position++];
  777. if ((i & 0x80) > 0) {
  778. position -= 9;
  779. return
  780. }
  781. return fromCharCode(a, b, c, d, e, f, g, h, i)
  782. }
  783. } else if (length < 12) {
  784. let i = src[position++];
  785. let j = src[position++];
  786. if ((i & 0x80) > 0 || (j & 0x80) > 0) {
  787. position -= 10;
  788. return
  789. }
  790. if (length < 11)
  791. return fromCharCode(a, b, c, d, e, f, g, h, i, j)
  792. let k = src[position++];
  793. if ((k & 0x80) > 0) {
  794. position -= 11;
  795. return
  796. }
  797. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
  798. } else {
  799. let i = src[position++];
  800. let j = src[position++];
  801. let k = src[position++];
  802. let l = src[position++];
  803. if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
  804. position -= 12;
  805. return
  806. }
  807. if (length < 14) {
  808. if (length === 12)
  809. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
  810. else {
  811. let m = src[position++];
  812. if ((m & 0x80) > 0) {
  813. position -= 13;
  814. return
  815. }
  816. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
  817. }
  818. } else {
  819. let m = src[position++];
  820. let n = src[position++];
  821. if ((m & 0x80) > 0 || (n & 0x80) > 0) {
  822. position -= 14;
  823. return
  824. }
  825. if (length < 15)
  826. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
  827. let o = src[position++];
  828. if ((o & 0x80) > 0) {
  829. position -= 15;
  830. return
  831. }
  832. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
  833. }
  834. }
  835. }
  836. }
  837. }
  838. function readOnlyJSString() {
  839. let token = src[position++];
  840. let length;
  841. if (token < 0xc0) {
  842. // fixstr
  843. length = token - 0xa0;
  844. } else {
  845. switch(token) {
  846. case 0xd9:
  847. // str 8
  848. length = src[position++];
  849. break
  850. case 0xda:
  851. // str 16
  852. length = dataView.getUint16(position);
  853. position += 2;
  854. break
  855. case 0xdb:
  856. // str 32
  857. length = dataView.getUint32(position);
  858. position += 4;
  859. break
  860. default:
  861. throw new Error('Expected string')
  862. }
  863. }
  864. return readStringJS(length)
  865. }
  866. function readBin(length) {
  867. return currentUnpackr.copyBuffers ?
  868. // specifically use the copying slice (not the node one)
  869. Uint8Array.prototype.slice.call(src, position, position += length) :
  870. src.subarray(position, position += length)
  871. }
  872. function readExt(length) {
  873. let type = src[position++];
  874. if (currentExtensions[type]) {
  875. let end;
  876. return currentExtensions[type](src.subarray(position, end = (position += length)), (readPosition) => {
  877. position = readPosition;
  878. try {
  879. return read();
  880. } finally {
  881. position = end;
  882. }
  883. })
  884. }
  885. else
  886. throw new Error('Unknown extension type ' + type)
  887. }
  888. var keyCache = new Array(4096);
  889. function readKey() {
  890. let length = src[position++];
  891. if (length >= 0xa0 && length < 0xc0) {
  892. // fixstr, potentially use key cache
  893. length = length - 0xa0;
  894. if (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)
  895. return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
  896. else if (!(srcStringEnd == 0 && srcEnd < 180))
  897. return readFixedString(length)
  898. } else { // not cacheable, go back and do a standard read
  899. position--;
  900. return asSafeString(read())
  901. }
  902. let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff;
  903. let entry = keyCache[key];
  904. let checkPosition = position;
  905. let end = position + length - 3;
  906. let chunk;
  907. let i = 0;
  908. if (entry && entry.bytes == length) {
  909. while (checkPosition < end) {
  910. chunk = dataView.getUint32(checkPosition);
  911. if (chunk != entry[i++]) {
  912. checkPosition = 0x70000000;
  913. break
  914. }
  915. checkPosition += 4;
  916. }
  917. end += 3;
  918. while (checkPosition < end) {
  919. chunk = src[checkPosition++];
  920. if (chunk != entry[i++]) {
  921. checkPosition = 0x70000000;
  922. break
  923. }
  924. }
  925. if (checkPosition === end) {
  926. position = checkPosition;
  927. return entry.string
  928. }
  929. end -= 3;
  930. checkPosition = position;
  931. }
  932. entry = [];
  933. keyCache[key] = entry;
  934. entry.bytes = length;
  935. while (checkPosition < end) {
  936. chunk = dataView.getUint32(checkPosition);
  937. entry.push(chunk);
  938. checkPosition += 4;
  939. }
  940. end += 3;
  941. while (checkPosition < end) {
  942. chunk = src[checkPosition++];
  943. entry.push(chunk);
  944. }
  945. // for small blocks, avoiding the overhead of the extract call is helpful
  946. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  947. if (string != null)
  948. return entry.string = string
  949. return entry.string = readFixedString(length)
  950. }
  951. function asSafeString(property) {
  952. // protect against expensive (DoS) string conversions
  953. if (typeof property === 'string') return property;
  954. if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();
  955. if (property == null) return property + '';
  956. if (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every(item => ['string', 'number', 'boolean', 'bigint'].includes(typeof item))) {
  957. return property.flat().toString();
  958. }
  959. throw new Error(`Invalid property type for record: ${typeof property}`);
  960. }
  961. // the registration of the record definition extension (as "r")
  962. const recordDefinition = (id, highByte) => {
  963. let structure = read().map(asSafeString); // ensure that all keys are strings and
  964. // that the array is mutable
  965. let firstByte = id;
  966. if (highByte !== undefined) {
  967. id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
  968. structure.highByte = highByte;
  969. }
  970. let existingStructure = currentStructures[id];
  971. // If it is a shared structure, we need to restore any changes after reading.
  972. // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
  973. // to the state prior to an incomplete read in order to properly resume.
  974. if (existingStructure && (existingStructure.isShared || sequentialMode)) {
  975. (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
  976. }
  977. currentStructures[id] = structure;
  978. structure.read = createStructureReader(structure, firstByte);
  979. return structure.read()
  980. };
  981. currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
  982. currentExtensions[0].noBuffer = true;
  983. currentExtensions[0x42] = data => {
  984. let headLength = (data.byteLength % 8) || 8;
  985. let head = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
  986. for (let i = 1; i < headLength; i++) {
  987. head <<= BigInt(8);
  988. head += BigInt(data[i]);
  989. }
  990. if (data.byteLength !== headLength) {
  991. let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  992. let decode = (start, end) => {
  993. let length = end - start;
  994. if (length <= 40) {
  995. let out = view.getBigUint64(start);
  996. for (let i = start + 8; i < end; i += 8) {
  997. out <<= BigInt(64n);
  998. out |= view.getBigUint64(i);
  999. }
  1000. return out
  1001. }
  1002. // if (length === 8) return view.getBigUint64(start)
  1003. let middle = start + (length >> 4 << 3);
  1004. let left = decode(start, middle);
  1005. let right = decode(middle, end);
  1006. return (left << BigInt((end - middle) * 8)) | right
  1007. };
  1008. head = (head << BigInt((view.byteLength - headLength) * 8)) | decode(headLength, view.byteLength);
  1009. }
  1010. return head
  1011. };
  1012. let errors = {
  1013. Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError: typeof AggregateError === 'function' ? AggregateError : null,
  1014. };
  1015. currentExtensions[0x65] = () => {
  1016. let data = read();
  1017. if (!errors[data[0]]) {
  1018. let error = Error(data[1], { cause: data[2] });
  1019. error.name = data[0];
  1020. return error
  1021. }
  1022. return errors[data[0]](data[1], { cause: data[2] })
  1023. };
  1024. currentExtensions[0x69] = (data) => {
  1025. // id extension (for structured clones)
  1026. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1027. let id = dataView.getUint32(position - 4);
  1028. if (!referenceMap)
  1029. referenceMap = new Map();
  1030. let token = src[position];
  1031. let target;
  1032. // TODO: handle any other types that can cycle and make the code more robust if there are other extensions
  1033. if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
  1034. target = [];
  1035. else if (token >= 0x80 && token < 0x90 || token == 0xde || token == 0xdf)
  1036. target = new Map();
  1037. else if ((token >= 0xc7 && token <= 0xc9 || token >= 0xd4 && token <= 0xd8) && src[position + 1] === 0x73)
  1038. target = new Set();
  1039. else
  1040. target = {};
  1041. let refEntry = { target }; // a placeholder object
  1042. referenceMap.set(id, refEntry);
  1043. let targetProperties = read(); // read the next value as the target object to id
  1044. if (!refEntry.used) {
  1045. // no cycle, can just use the returned read object
  1046. return refEntry.target = targetProperties // replace the placeholder with the real one
  1047. } else {
  1048. // there is a cycle, so we have to assign properties to original target
  1049. Object.assign(target, targetProperties);
  1050. }
  1051. // copy over map/set entries if we're able to
  1052. if (target instanceof Map)
  1053. for (let [k, v] of targetProperties.entries()) target.set(k, v);
  1054. if (target instanceof Set)
  1055. for (let i of Array.from(targetProperties)) target.add(i);
  1056. return target
  1057. };
  1058. currentExtensions[0x70] = (data) => {
  1059. // pointer extension (for structured clones)
  1060. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1061. let id = dataView.getUint32(position - 4);
  1062. let refEntry = referenceMap.get(id);
  1063. refEntry.used = true;
  1064. return refEntry.target
  1065. };
  1066. currentExtensions[0x73] = () => new Set(read());
  1067. const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
  1068. let glbl = typeof globalThis === 'object' ? globalThis : window;
  1069. currentExtensions[0x74] = (data) => {
  1070. let typeCode = data[0];
  1071. // we always have to slice to get a new ArrayBuffer that is aligned
  1072. let buffer = Uint8Array.prototype.slice.call(data, 1).buffer;
  1073. let typedArrayName = typedArrays[typeCode];
  1074. if (!typedArrayName) {
  1075. if (typeCode === 16) return buffer
  1076. if (typeCode === 17) return new DataView(buffer)
  1077. throw new Error('Could not find typed array for code ' + typeCode)
  1078. }
  1079. return new glbl[typedArrayName](buffer)
  1080. };
  1081. currentExtensions[0x78] = () => {
  1082. let data = read();
  1083. return new RegExp(data[0], data[1])
  1084. };
  1085. const TEMP_BUNDLE = [];
  1086. currentExtensions[0x62] = (data) => {
  1087. let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  1088. let dataPosition = position;
  1089. position += dataSize - data.length;
  1090. bundledStrings = TEMP_BUNDLE;
  1091. bundledStrings = [readOnlyJSString(), readOnlyJSString()];
  1092. bundledStrings.position0 = 0;
  1093. bundledStrings.position1 = 0;
  1094. bundledStrings.postBundlePosition = position;
  1095. position = dataPosition;
  1096. return read()
  1097. };
  1098. currentExtensions[0xff] = (data) => {
  1099. // 32-bit date extension
  1100. if (data.length == 4)
  1101. return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
  1102. else if (data.length == 8)
  1103. return new Date(
  1104. ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
  1105. ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
  1106. else if (data.length == 12)
  1107. return new Date(
  1108. ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
  1109. (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
  1110. else
  1111. return new Date('invalid')
  1112. };
  1113. // registration of bulk record definition?
  1114. // currentExtensions[0x52] = () =>
  1115. function saveState(callback) {
  1116. if (onSaveState)
  1117. onSaveState();
  1118. let savedSrcEnd = srcEnd;
  1119. let savedPosition = position;
  1120. let savedStringPosition = stringPosition;
  1121. let savedSrcStringStart = srcStringStart;
  1122. let savedSrcStringEnd = srcStringEnd;
  1123. let savedSrcString = srcString;
  1124. let savedStrings = strings;
  1125. let savedReferenceMap = referenceMap;
  1126. let savedBundledStrings = bundledStrings;
  1127. // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
  1128. let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
  1129. let savedStructures = currentStructures;
  1130. let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
  1131. let savedPackr = currentUnpackr;
  1132. let savedSequentialMode = sequentialMode;
  1133. let value = callback();
  1134. srcEnd = savedSrcEnd;
  1135. position = savedPosition;
  1136. stringPosition = savedStringPosition;
  1137. srcStringStart = savedSrcStringStart;
  1138. srcStringEnd = savedSrcStringEnd;
  1139. srcString = savedSrcString;
  1140. strings = savedStrings;
  1141. referenceMap = savedReferenceMap;
  1142. bundledStrings = savedBundledStrings;
  1143. src = savedSrc;
  1144. sequentialMode = savedSequentialMode;
  1145. currentStructures = savedStructures;
  1146. currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
  1147. currentUnpackr = savedPackr;
  1148. dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  1149. return value
  1150. }
  1151. function clearSource() {
  1152. src = null;
  1153. referenceMap = null;
  1154. currentStructures = null;
  1155. }
  1156. function addExtension(extension) {
  1157. if (extension.unpack)
  1158. currentExtensions[extension.type] = extension.unpack;
  1159. else
  1160. currentExtensions[extension.type] = extension;
  1161. }
  1162. const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
  1163. for (let i = 0; i < 256; i++) {
  1164. mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
  1165. }
  1166. const Decoder = Unpackr;
  1167. var defaultUnpackr = new Unpackr({ useRecords: false });
  1168. const unpack = defaultUnpackr.unpack;
  1169. const unpackMultiple = defaultUnpackr.unpackMultiple;
  1170. const decode = defaultUnpackr.unpack;
  1171. const FLOAT32_OPTIONS = {
  1172. NEVER: 0,
  1173. ALWAYS: 1,
  1174. DECIMAL_ROUND: 3,
  1175. DECIMAL_FIT: 4
  1176. };
  1177. let f32Array = new Float32Array(1);
  1178. let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
  1179. function roundFloat32(float32Number) {
  1180. f32Array[0] = float32Number;
  1181. let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
  1182. return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  1183. }
  1184. function setReadStruct(updatedReadStruct, loadedStructs, saveState) {
  1185. readStruct = updatedReadStruct;
  1186. onLoadedStructures = loadedStructs;
  1187. onSaveState = saveState;
  1188. }
  1189. exports.C1 = C1;
  1190. exports.C1Type = C1Type;
  1191. exports.Decoder = Decoder;
  1192. exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
  1193. exports.Unpackr = Unpackr;
  1194. exports.addExtension = addExtension;
  1195. exports.checkedRead = checkedRead;
  1196. exports.clearSource = clearSource;
  1197. exports.decode = decode;
  1198. exports.getPosition = getPosition;
  1199. exports.loadStructures = loadStructures;
  1200. exports.mult10 = mult10;
  1201. exports.read = read;
  1202. exports.readString = readString;
  1203. exports.roundFloat32 = roundFloat32;
  1204. exports.setExtractor = setExtractor;
  1205. exports.setReadStruct = setReadStruct;
  1206. exports.typedArrays = typedArrays;
  1207. exports.unpack = unpack;
  1208. exports.unpackMultiple = unpackMultiple;
  1209. }));
  1210. //# sourceMappingURL=unpack-no-eval.cjs.map