jaelis-node 1.3.2 → 1.5.0

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