unpack-no-eval.cjs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. throw new Error('Invalid property type for record', typeof property);
  957. }
  958. // the registration of the record definition extension (as "r")
  959. const recordDefinition = (id, highByte) => {
  960. let structure = read().map(asSafeString); // ensure that all keys are strings and
  961. // that the array is mutable
  962. let firstByte = id;
  963. if (highByte !== undefined) {
  964. id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
  965. structure.highByte = highByte;
  966. }
  967. let existingStructure = currentStructures[id];
  968. // If it is a shared structure, we need to restore any changes after reading.
  969. // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
  970. // to the state prior to an incomplete read in order to properly resume.
  971. if (existingStructure && (existingStructure.isShared || sequentialMode)) {
  972. (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
  973. }
  974. currentStructures[id] = structure;
  975. structure.read = createStructureReader(structure, firstByte);
  976. return structure.read()
  977. };
  978. currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
  979. currentExtensions[0].noBuffer = true;
  980. currentExtensions[0x42] = (data) => {
  981. // decode bigint
  982. let length = data.length;
  983. let value = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
  984. for (let i = 1; i < length; i++) {
  985. value <<= BigInt(8);
  986. value += BigInt(data[i]);
  987. }
  988. return value;
  989. };
  990. let errors = { Error, TypeError, ReferenceError };
  991. currentExtensions[0x65] = () => {
  992. let data = read();
  993. return (errors[data[0]] || Error)(data[1], { cause: data[2] })
  994. };
  995. currentExtensions[0x69] = (data) => {
  996. // id extension (for structured clones)
  997. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  998. let id = dataView.getUint32(position - 4);
  999. if (!referenceMap)
  1000. referenceMap = new Map();
  1001. let token = src[position];
  1002. let target;
  1003. // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
  1004. // ahead past references to record structure definitions
  1005. if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
  1006. target = [];
  1007. else
  1008. target = {};
  1009. let refEntry = { target }; // a placeholder object
  1010. referenceMap.set(id, refEntry);
  1011. let targetProperties = read(); // read the next value as the target object to id
  1012. if (refEntry.used) // there is a cycle, so we have to assign properties to original target
  1013. return Object.assign(target, targetProperties)
  1014. refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
  1015. return targetProperties // no cycle, can just use the returned read object
  1016. };
  1017. currentExtensions[0x70] = (data) => {
  1018. // pointer extension (for structured clones)
  1019. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1020. let id = dataView.getUint32(position - 4);
  1021. let refEntry = referenceMap.get(id);
  1022. refEntry.used = true;
  1023. return refEntry.target
  1024. };
  1025. currentExtensions[0x73] = () => new Set(read());
  1026. const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
  1027. let glbl = typeof globalThis === 'object' ? globalThis : window;
  1028. currentExtensions[0x74] = (data) => {
  1029. let typeCode = data[0];
  1030. let typedArrayName = typedArrays[typeCode];
  1031. if (!typedArrayName) {
  1032. if (typeCode === 16) {
  1033. let ab = new ArrayBuffer(data.length - 1);
  1034. let u8 = new Uint8Array(ab);
  1035. u8.set(data.subarray(1));
  1036. return ab;
  1037. }
  1038. throw new Error('Could not find typed array for code ' + typeCode)
  1039. }
  1040. // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
  1041. return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
  1042. };
  1043. currentExtensions[0x78] = () => {
  1044. let data = read();
  1045. return new RegExp(data[0], data[1])
  1046. };
  1047. const TEMP_BUNDLE = [];
  1048. currentExtensions[0x62] = (data) => {
  1049. let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  1050. let dataPosition = position;
  1051. position += dataSize - data.length;
  1052. bundledStrings = TEMP_BUNDLE;
  1053. bundledStrings = [readOnlyJSString(), readOnlyJSString()];
  1054. bundledStrings.position0 = 0;
  1055. bundledStrings.position1 = 0;
  1056. bundledStrings.postBundlePosition = position;
  1057. position = dataPosition;
  1058. return read()
  1059. };
  1060. currentExtensions[0xff] = (data) => {
  1061. // 32-bit date extension
  1062. if (data.length == 4)
  1063. return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
  1064. else if (data.length == 8)
  1065. return new Date(
  1066. ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
  1067. ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
  1068. else if (data.length == 12)// TODO: Implement support for negative
  1069. return new Date(
  1070. ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
  1071. (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
  1072. else
  1073. return new Date('invalid')
  1074. }; // notepack defines extension 0 to mean undefined, so use that as the default here
  1075. // registration of bulk record definition?
  1076. // currentExtensions[0x52] = () =>
  1077. function saveState(callback) {
  1078. if (onSaveState)
  1079. onSaveState();
  1080. let savedSrcEnd = srcEnd;
  1081. let savedPosition = position;
  1082. let savedStringPosition = stringPosition;
  1083. let savedSrcStringStart = srcStringStart;
  1084. let savedSrcStringEnd = srcStringEnd;
  1085. let savedSrcString = srcString;
  1086. let savedStrings = strings;
  1087. let savedReferenceMap = referenceMap;
  1088. let savedBundledStrings = bundledStrings;
  1089. // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
  1090. let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
  1091. let savedStructures = currentStructures;
  1092. let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
  1093. let savedPackr = currentUnpackr;
  1094. let savedSequentialMode = sequentialMode;
  1095. let value = callback();
  1096. srcEnd = savedSrcEnd;
  1097. position = savedPosition;
  1098. stringPosition = savedStringPosition;
  1099. srcStringStart = savedSrcStringStart;
  1100. srcStringEnd = savedSrcStringEnd;
  1101. srcString = savedSrcString;
  1102. strings = savedStrings;
  1103. referenceMap = savedReferenceMap;
  1104. bundledStrings = savedBundledStrings;
  1105. src = savedSrc;
  1106. sequentialMode = savedSequentialMode;
  1107. currentStructures = savedStructures;
  1108. currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
  1109. currentUnpackr = savedPackr;
  1110. dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  1111. return value
  1112. }
  1113. function clearSource() {
  1114. src = null;
  1115. referenceMap = null;
  1116. currentStructures = null;
  1117. }
  1118. function addExtension(extension) {
  1119. if (extension.unpack)
  1120. currentExtensions[extension.type] = extension.unpack;
  1121. else
  1122. currentExtensions[extension.type] = extension;
  1123. }
  1124. const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
  1125. for (let i = 0; i < 256; i++) {
  1126. mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
  1127. }
  1128. const Decoder = Unpackr;
  1129. var defaultUnpackr = new Unpackr({ useRecords: false });
  1130. const unpack = defaultUnpackr.unpack;
  1131. const unpackMultiple = defaultUnpackr.unpackMultiple;
  1132. const decode = defaultUnpackr.unpack;
  1133. const FLOAT32_OPTIONS = {
  1134. NEVER: 0,
  1135. ALWAYS: 1,
  1136. DECIMAL_ROUND: 3,
  1137. DECIMAL_FIT: 4
  1138. };
  1139. let f32Array = new Float32Array(1);
  1140. let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
  1141. function roundFloat32(float32Number) {
  1142. f32Array[0] = float32Number;
  1143. let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
  1144. return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  1145. }
  1146. function setReadStruct(updatedReadStruct, loadedStructs, saveState) {
  1147. readStruct = updatedReadStruct;
  1148. onLoadedStructures = loadedStructs;
  1149. onSaveState = saveState;
  1150. }
  1151. exports.C1 = C1;
  1152. exports.C1Type = C1Type;
  1153. exports.Decoder = Decoder;
  1154. exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
  1155. exports.Unpackr = Unpackr;
  1156. exports.addExtension = addExtension;
  1157. exports.checkedRead = checkedRead;
  1158. exports.clearSource = clearSource;
  1159. exports.decode = decode;
  1160. exports.getPosition = getPosition;
  1161. exports.loadStructures = loadStructures;
  1162. exports.mult10 = mult10;
  1163. exports.read = read;
  1164. exports.readString = readString;
  1165. exports.roundFloat32 = roundFloat32;
  1166. exports.setExtractor = setExtractor;
  1167. exports.setReadStruct = setReadStruct;
  1168. exports.typedArrays = typedArrays;
  1169. exports.unpack = unpack;
  1170. exports.unpackMultiple = unpackMultiple;
  1171. }));
  1172. //# sourceMappingURL=unpack-no-eval.cjs.map