jaelis-node 1.10.0 → 2.1.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 (173) hide show
  1. package/README.md +156 -439
  2. package/bin/jaelis-node.js +83 -504
  3. package/lib/index.js +31 -2840
  4. package/lib/node.js +309 -0
  5. package/lib/rpc.js +315 -0
  6. package/lib/storage.js +198 -0
  7. package/lib/sync.js +366 -0
  8. package/package.json +19 -53
  9. package/config/default.json +0 -74
  10. package/config/mainnet.json +0 -30
  11. package/config/testnet.json +0 -26
  12. package/lib/JAELIS-VM/lib/adapters/evm-adapter.js +0 -454
  13. package/lib/JAELIS-VM/lib/adapters/index.js +0 -411
  14. package/lib/JAELIS-VM/lib/adapters/svm-adapter.js +0 -457
  15. package/lib/JAELIS-VM/lib/compiler/jir-compiler.js +0 -1097
  16. package/lib/JAELIS-VM/lib/execution/engine.js +0 -1183
  17. package/lib/JAELIS-VM/lib/index.js +0 -440
  18. package/lib/JAELIS-VM/lib/integration/jaelis-integration.js +0 -543
  19. package/lib/JAELIS-VM/lib/serialization/serializer.js +0 -819
  20. package/lib/JAELIS-VM/lib/state/state-manager.js +0 -1116
  21. package/lib/JAELIS-VM/lib/translator/bytecode-translator.js +0 -1222
  22. package/lib/JAELIS-VM/lib/unified/cross-chain-deploy.js +0 -1678
  23. package/lib/JAELIS-VM/lib/unified/cross-chain-state.js +0 -836
  24. package/lib/JAELIS-VM/lib/unified/dynamic-contracts.js +0 -1127
  25. package/lib/JAELIS-VM/lib/unified/index.js +0 -456
  26. package/lib/JAELIS-VM/lib/unified/jaelis-abi.js +0 -1150
  27. package/lib/JAELIS-VM/lib/unified/unified-compiler.js +0 -1350
  28. package/lib/JAELIS-VM/node_modules/.bin/download-cbor-prebuilds +0 -12
  29. package/lib/JAELIS-VM/node_modules/.bin/download-cbor-prebuilds.cmd +0 -17
  30. package/lib/JAELIS-VM/node_modules/.bin/download-cbor-prebuilds.ps1 +0 -28
  31. package/lib/JAELIS-VM/node_modules/.bin/download-msgpackr-prebuilds +0 -12
  32. package/lib/JAELIS-VM/node_modules/.bin/download-msgpackr-prebuilds.cmd +0 -17
  33. package/lib/JAELIS-VM/node_modules/.bin/download-msgpackr-prebuilds.ps1 +0 -28
  34. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages +0 -12
  35. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages-optional +0 -12
  36. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages-optional.cmd +0 -17
  37. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages-optional.ps1 +0 -28
  38. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages-test +0 -12
  39. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages-test.cmd +0 -17
  40. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages-test.ps1 +0 -28
  41. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages.cmd +0 -17
  42. package/lib/JAELIS-VM/node_modules/.bin/node-gyp-build-optional-packages.ps1 +0 -28
  43. package/lib/JAELIS-VM/node_modules/.package-lock.json +0 -127
  44. package/lib/JAELIS-VM/node_modules/@cbor-extract/cbor-extract-win32-x64/README.md +0 -1
  45. package/lib/JAELIS-VM/node_modules/@cbor-extract/cbor-extract-win32-x64/index.js +0 -0
  46. package/lib/JAELIS-VM/node_modules/@cbor-extract/cbor-extract-win32-x64/node.abi115.node +0 -0
  47. package/lib/JAELIS-VM/node_modules/@cbor-extract/cbor-extract-win32-x64/node.napi.node +0 -0
  48. package/lib/JAELIS-VM/node_modules/@cbor-extract/cbor-extract-win32-x64/package.json +0 -17
  49. package/lib/JAELIS-VM/node_modules/@msgpackr-extract/msgpackr-extract-win32-x64/README.md +0 -1
  50. package/lib/JAELIS-VM/node_modules/@msgpackr-extract/msgpackr-extract-win32-x64/index.js +0 -0
  51. package/lib/JAELIS-VM/node_modules/@msgpackr-extract/msgpackr-extract-win32-x64/node.abi115.node +0 -0
  52. package/lib/JAELIS-VM/node_modules/@msgpackr-extract/msgpackr-extract-win32-x64/node.napi.node +0 -0
  53. package/lib/JAELIS-VM/node_modules/@msgpackr-extract/msgpackr-extract-win32-x64/package.json +0 -17
  54. package/lib/JAELIS-VM/node_modules/cbor-extract/LICENSE +0 -21
  55. package/lib/JAELIS-VM/node_modules/cbor-extract/README.md +0 -5
  56. package/lib/JAELIS-VM/node_modules/cbor-extract/bin/download-prebuilds.js +0 -11
  57. package/lib/JAELIS-VM/node_modules/cbor-extract/binding.gyp +0 -60
  58. package/lib/JAELIS-VM/node_modules/cbor-extract/index.js +0 -1
  59. package/lib/JAELIS-VM/node_modules/cbor-extract/package.json +0 -50
  60. package/lib/JAELIS-VM/node_modules/cbor-extract/src/extract.cpp +0 -198
  61. package/lib/JAELIS-VM/node_modules/cbor-x/LICENSE +0 -21
  62. package/lib/JAELIS-VM/node_modules/cbor-x/README.md +0 -380
  63. package/lib/JAELIS-VM/node_modules/cbor-x/SECURITY.md +0 -11
  64. package/lib/JAELIS-VM/node_modules/cbor-x/benchmark.md +0 -73
  65. package/lib/JAELIS-VM/node_modules/cbor-x/browser.js +0 -11
  66. package/lib/JAELIS-VM/node_modules/cbor-x/decode.d.ts +0 -2
  67. package/lib/JAELIS-VM/node_modules/cbor-x/decode.js +0 -1300
  68. package/lib/JAELIS-VM/node_modules/cbor-x/dist/decode-no-eval.cjs +0 -1244
  69. package/lib/JAELIS-VM/node_modules/cbor-x/dist/decode-no-eval.cjs.map +0 -1
  70. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index-no-eval.cjs +0 -2509
  71. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index-no-eval.cjs.map +0 -1
  72. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index-no-eval.min.js +0 -2
  73. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index-no-eval.min.js.map +0 -1
  74. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index.js +0 -2508
  75. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index.js.map +0 -1
  76. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index.min.js +0 -2
  77. package/lib/JAELIS-VM/node_modules/cbor-x/dist/index.min.js.map +0 -1
  78. package/lib/JAELIS-VM/node_modules/cbor-x/dist/node.cjs +0 -2629
  79. package/lib/JAELIS-VM/node_modules/cbor-x/dist/node.cjs.map +0 -1
  80. package/lib/JAELIS-VM/node_modules/cbor-x/dist/test.js +0 -3343
  81. package/lib/JAELIS-VM/node_modules/cbor-x/dist/test.js.map +0 -1
  82. package/lib/JAELIS-VM/node_modules/cbor-x/encode.d.ts +0 -1
  83. package/lib/JAELIS-VM/node_modules/cbor-x/encode.js +0 -1231
  84. package/lib/JAELIS-VM/node_modules/cbor-x/index.d.ts +0 -79
  85. package/lib/JAELIS-VM/node_modules/cbor-x/index.js +0 -3
  86. package/lib/JAELIS-VM/node_modules/cbor-x/iterators.js +0 -85
  87. package/lib/JAELIS-VM/node_modules/cbor-x/node-index.js +0 -24
  88. package/lib/JAELIS-VM/node_modules/cbor-x/package.json +0 -94
  89. package/lib/JAELIS-VM/node_modules/cbor-x/rollup.config.js +0 -88
  90. package/lib/JAELIS-VM/node_modules/cbor-x/stream.js +0 -61
  91. package/lib/JAELIS-VM/node_modules/cbor-x/webpack.config.js +0 -19
  92. package/lib/JAELIS-VM/node_modules/detect-libc/LICENSE +0 -201
  93. package/lib/JAELIS-VM/node_modules/detect-libc/README.md +0 -163
  94. package/lib/JAELIS-VM/node_modules/detect-libc/index.d.ts +0 -14
  95. package/lib/JAELIS-VM/node_modules/detect-libc/lib/detect-libc.js +0 -313
  96. package/lib/JAELIS-VM/node_modules/detect-libc/lib/elf.js +0 -39
  97. package/lib/JAELIS-VM/node_modules/detect-libc/lib/filesystem.js +0 -51
  98. package/lib/JAELIS-VM/node_modules/detect-libc/lib/process.js +0 -24
  99. package/lib/JAELIS-VM/node_modules/detect-libc/package.json +0 -44
  100. package/lib/JAELIS-VM/node_modules/msgpackr/LICENSE +0 -21
  101. package/lib/JAELIS-VM/node_modules/msgpackr/README.md +0 -372
  102. package/lib/JAELIS-VM/node_modules/msgpackr/SECURITY.md +0 -11
  103. package/lib/JAELIS-VM/node_modules/msgpackr/benchmark.md +0 -67
  104. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index-no-eval.cjs +0 -2407
  105. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index-no-eval.cjs.map +0 -1
  106. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index-no-eval.min.js +0 -2
  107. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index-no-eval.min.js.map +0 -1
  108. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index.js +0 -2406
  109. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index.js.map +0 -1
  110. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index.min.js +0 -2
  111. package/lib/JAELIS-VM/node_modules/msgpackr/dist/index.min.js.map +0 -1
  112. package/lib/JAELIS-VM/node_modules/msgpackr/dist/node.cjs +0 -3320
  113. package/lib/JAELIS-VM/node_modules/msgpackr/dist/node.cjs.map +0 -1
  114. package/lib/JAELIS-VM/node_modules/msgpackr/dist/test.js +0 -4540
  115. package/lib/JAELIS-VM/node_modules/msgpackr/dist/test.js.map +0 -1
  116. package/lib/JAELIS-VM/node_modules/msgpackr/dist/unpack-no-eval.cjs +0 -1250
  117. package/lib/JAELIS-VM/node_modules/msgpackr/dist/unpack-no-eval.cjs.map +0 -1
  118. package/lib/JAELIS-VM/node_modules/msgpackr/index.d.cts +0 -91
  119. package/lib/JAELIS-VM/node_modules/msgpackr/index.d.ts +0 -91
  120. package/lib/JAELIS-VM/node_modules/msgpackr/index.js +0 -5
  121. package/lib/JAELIS-VM/node_modules/msgpackr/iterators.js +0 -87
  122. package/lib/JAELIS-VM/node_modules/msgpackr/node-index.js +0 -25
  123. package/lib/JAELIS-VM/node_modules/msgpackr/pack.d.cts +0 -1
  124. package/lib/JAELIS-VM/node_modules/msgpackr/pack.d.ts +0 -1
  125. package/lib/JAELIS-VM/node_modules/msgpackr/pack.js +0 -1141
  126. package/lib/JAELIS-VM/node_modules/msgpackr/package.json +0 -104
  127. package/lib/JAELIS-VM/node_modules/msgpackr/rollup.config.js +0 -88
  128. package/lib/JAELIS-VM/node_modules/msgpackr/stream.js +0 -57
  129. package/lib/JAELIS-VM/node_modules/msgpackr/struct.js +0 -815
  130. package/lib/JAELIS-VM/node_modules/msgpackr/test-worker.js +0 -3
  131. package/lib/JAELIS-VM/node_modules/msgpackr/unpack.d.cts +0 -2
  132. package/lib/JAELIS-VM/node_modules/msgpackr/unpack.d.ts +0 -2
  133. package/lib/JAELIS-VM/node_modules/msgpackr/unpack.js +0 -1221
  134. package/lib/JAELIS-VM/node_modules/msgpackr-extract/LICENSE +0 -21
  135. package/lib/JAELIS-VM/node_modules/msgpackr-extract/README.md +0 -5
  136. package/lib/JAELIS-VM/node_modules/msgpackr-extract/bin/download-prebuilds.js +0 -13
  137. package/lib/JAELIS-VM/node_modules/msgpackr-extract/binding.gyp +0 -63
  138. package/lib/JAELIS-VM/node_modules/msgpackr-extract/index.js +0 -1
  139. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages +0 -12
  140. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages-optional +0 -12
  141. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages-optional.cmd +0 -17
  142. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages-optional.ps1 +0 -28
  143. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages-test +0 -12
  144. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages-test.cmd +0 -17
  145. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages-test.ps1 +0 -28
  146. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages.cmd +0 -17
  147. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/.bin/node-gyp-build-optional-packages.ps1 +0 -28
  148. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/LICENSE +0 -21
  149. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/README.md +0 -58
  150. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/bin.js +0 -82
  151. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/build-test.js +0 -19
  152. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/index.js +0 -6
  153. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/node-gyp-build.js +0 -236
  154. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/optional.js +0 -7
  155. package/lib/JAELIS-VM/node_modules/msgpackr-extract/node_modules/node-gyp-build-optional-packages/package.json +0 -32
  156. package/lib/JAELIS-VM/node_modules/msgpackr-extract/package.json +0 -50
  157. package/lib/JAELIS-VM/node_modules/msgpackr-extract/src/extract.cpp +0 -274
  158. package/lib/JAELIS-VM/node_modules/node-gyp-build-optional-packages/LICENSE +0 -21
  159. package/lib/JAELIS-VM/node_modules/node-gyp-build-optional-packages/README.md +0 -58
  160. package/lib/JAELIS-VM/node_modules/node-gyp-build-optional-packages/bin.js +0 -77
  161. package/lib/JAELIS-VM/node_modules/node-gyp-build-optional-packages/build-test.js +0 -19
  162. package/lib/JAELIS-VM/node_modules/node-gyp-build-optional-packages/index.js +0 -224
  163. package/lib/JAELIS-VM/node_modules/node-gyp-build-optional-packages/optional.js +0 -7
  164. package/lib/JAELIS-VM/node_modules/node-gyp-build-optional-packages/package.json +0 -32
  165. package/lib/JAELIS-VM/package-lock.json +0 -284
  166. package/lib/JAELIS-VM/package.json +0 -38
  167. package/lib/JAELIS-VM/test/comprehensive.test.js +0 -267
  168. package/lib/JAELIS-VM/test/cross-chain-test.js +0 -470
  169. package/lib/JAELIS-VM/test/unified-vm-test.js +0 -459
  170. package/lib/JAELIS-VM/test/unified.test.js +0 -166
  171. package/lib/JAELIS-VM/test/vm.test.js +0 -599
  172. package/lib/settlement-server.js +0 -999
  173. package/lib/vm/index.js +0 -397
@@ -1,4540 +0,0 @@
1
- (function (chai, stream, module, fs) {
2
- 'use strict';
3
-
4
- var decoder;
5
- try {
6
- decoder = new TextDecoder();
7
- } catch(error) {}
8
- var src;
9
- var srcEnd;
10
- var position$1 = 0;
11
- const EMPTY_ARRAY = [];
12
- var strings = EMPTY_ARRAY;
13
- var stringPosition = 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$1, onLoadedStructures$1, onSaveState;
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
- let Unpackr$1 = 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$1(() => {
70
- clearSource();
71
- return this ? this.unpack(source, options) : Unpackr$1.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
- stringPosition = 0;
84
- srcStringEnd = 0;
85
- srcString = null;
86
- strings = EMPTY_ARRAY;
87
- bundledStrings$1 = null;
88
- src = source;
89
- // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
90
- // technique for getting data from a database where it can be copied into an existing buffer instead of creating
91
- // new ones
92
- try {
93
- dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
94
- } catch(error) {
95
- // if it doesn't have a buffer, maybe it is the wrong type of object
96
- src = null;
97
- if (source instanceof Uint8Array)
98
- throw error
99
- throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
100
- }
101
- if (this instanceof Unpackr$1) {
102
- currentUnpackr = this;
103
- if (this.structures) {
104
- currentStructures = this.structures;
105
- return checkedRead(options)
106
- } else if (!currentStructures || currentStructures.length > 0) {
107
- currentStructures = [];
108
- }
109
- } else {
110
- currentUnpackr = defaultOptions;
111
- if (!currentStructures || currentStructures.length > 0)
112
- currentStructures = [];
113
- }
114
- return checkedRead(options)
115
- }
116
- unpackMultiple(source, forEach) {
117
- let values, lastPosition = 0;
118
- try {
119
- sequentialMode = true;
120
- let size = source.length;
121
- let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
122
- if (forEach) {
123
- if (forEach(value, lastPosition, position$1) === false) return;
124
- while(position$1 < size) {
125
- lastPosition = position$1;
126
- if (forEach(checkedRead(), lastPosition, position$1) === false) {
127
- return
128
- }
129
- }
130
- }
131
- else {
132
- values = [ value ];
133
- while(position$1 < size) {
134
- lastPosition = position$1;
135
- values.push(checkedRead());
136
- }
137
- return values
138
- }
139
- } catch(error) {
140
- error.lastPosition = lastPosition;
141
- error.values = values;
142
- throw error
143
- } finally {
144
- sequentialMode = false;
145
- clearSource();
146
- }
147
- }
148
- _mergeStructures(loadedStructures, existingStructures) {
149
- if (onLoadedStructures$1)
150
- loadedStructures = onLoadedStructures$1.call(this, loadedStructures);
151
- loadedStructures = loadedStructures || [];
152
- if (Object.isFrozen(loadedStructures))
153
- loadedStructures = loadedStructures.map(structure => structure.slice(0));
154
- for (let i = 0, l = loadedStructures.length; i < l; i++) {
155
- let structure = loadedStructures[i];
156
- if (structure) {
157
- structure.isShared = true;
158
- if (i >= 32)
159
- structure.highByte = (i - 32) >> 5;
160
- }
161
- }
162
- loadedStructures.sharedLength = loadedStructures.length;
163
- for (let id in existingStructures || []) {
164
- if (id >= 0) {
165
- let structure = loadedStructures[id];
166
- let existing = existingStructures[id];
167
- if (existing) {
168
- if (structure)
169
- (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
170
- loadedStructures[id] = existing;
171
- }
172
- }
173
- }
174
- return this.structures = loadedStructures
175
- }
176
- decode(source, options) {
177
- return this.unpack(source, options)
178
- }
179
- };
180
- function checkedRead(options) {
181
- try {
182
- if (!currentUnpackr.trusted && !sequentialMode) {
183
- let sharedLength = currentStructures.sharedLength || 0;
184
- if (sharedLength < currentStructures.length)
185
- currentStructures.length = sharedLength;
186
- }
187
- let result;
188
- if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct$1) {
189
- result = readStruct$1(src, position$1, srcEnd, currentUnpackr);
190
- src = null; // dispose of this so that recursive unpack calls don't save state
191
- if (!(options && options.lazy) && result)
192
- result = result.toJSON();
193
- position$1 = srcEnd;
194
- } else
195
- result = read();
196
- if (bundledStrings$1) { // bundled strings to skip past
197
- position$1 = bundledStrings$1.postBundlePosition;
198
- bundledStrings$1 = null;
199
- }
200
- if (sequentialMode)
201
- // we only need to restore the structures if there was an error, but if we completed a read,
202
- // we can clear this out and keep the structures we read
203
- currentStructures.restoreStructures = null;
204
-
205
- if (position$1 == srcEnd) {
206
- // finished reading this source, cleanup references
207
- if (currentStructures && currentStructures.restoreStructures)
208
- restoreStructures();
209
- currentStructures = null;
210
- src = null;
211
- if (referenceMap)
212
- referenceMap = null;
213
- } else if (position$1 > srcEnd) {
214
- // over read
215
- throw new Error('Unexpected end of MessagePack data')
216
- } else if (!sequentialMode) {
217
- let jsonView;
218
- try {
219
- jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100);
220
- } catch(error) {
221
- jsonView = '(JSON view not available ' + error + ')';
222
- }
223
- throw new Error('Data read, but end of buffer not reached ' + jsonView)
224
- }
225
- // else more to read, but we are reading sequentially, so don't clear source yet
226
- return result
227
- } catch(error) {
228
- if (currentStructures && currentStructures.restoreStructures)
229
- restoreStructures();
230
- clearSource();
231
- if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) {
232
- error.incomplete = true;
233
- }
234
- throw error
235
- }
236
- }
237
-
238
- function restoreStructures() {
239
- for (let id in currentStructures.restoreStructures) {
240
- currentStructures[id] = currentStructures.restoreStructures[id];
241
- }
242
- currentStructures.restoreStructures = null;
243
- }
244
-
245
- function read() {
246
- let token = src[position$1++];
247
- if (token < 0xa0) {
248
- if (token < 0x80) {
249
- if (token < 0x40)
250
- return token
251
- else {
252
- let structure = currentStructures[token & 0x3f] ||
253
- currentUnpackr.getStructures && loadStructures()[token & 0x3f];
254
- if (structure) {
255
- if (!structure.read) {
256
- structure.read = createStructureReader(structure, token & 0x3f);
257
- }
258
- return structure.read()
259
- } else
260
- return token
261
- }
262
- } else if (token < 0x90) {
263
- // map
264
- token -= 0x80;
265
- if (currentUnpackr.mapsAsObjects) {
266
- let object = {};
267
- for (let i = 0; i < token; i++) {
268
- let key = readKey();
269
- if (key === '__proto__')
270
- key = '__proto_';
271
- object[key] = read();
272
- }
273
- return object
274
- } else {
275
- let map = new Map();
276
- for (let i = 0; i < token; i++) {
277
- map.set(read(), read());
278
- }
279
- return map
280
- }
281
- } else {
282
- token -= 0x90;
283
- let array = new Array(token);
284
- for (let i = 0; i < token; i++) {
285
- array[i] = read();
286
- }
287
- if (currentUnpackr.freezeData)
288
- return Object.freeze(array)
289
- return array
290
- }
291
- } else if (token < 0xc0) {
292
- // fixstr
293
- let length = token - 0xa0;
294
- if (srcStringEnd >= position$1) {
295
- return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
296
- }
297
- if (srcStringEnd == 0 && srcEnd < 140) {
298
- // for small blocks, avoiding the overhead of the extract call is helpful
299
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
300
- if (string != null)
301
- return string
302
- }
303
- return readFixedString(length)
304
- } else {
305
- let value;
306
- switch (token) {
307
- case 0xc0: return null
308
- case 0xc1:
309
- if (bundledStrings$1) {
310
- value = read(); // followed by the length of the string in characters (not bytes!)
311
- if (value > 0)
312
- return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
313
- else
314
- return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value)
315
- }
316
- return C1; // "never-used", return special object to denote that
317
- case 0xc2: return false
318
- case 0xc3: return true
319
- case 0xc4:
320
- // bin 8
321
- value = src[position$1++];
322
- if (value === undefined)
323
- throw new Error('Unexpected end of buffer')
324
- return readBin(value)
325
- case 0xc5:
326
- // bin 16
327
- value = dataView.getUint16(position$1);
328
- position$1 += 2;
329
- return readBin(value)
330
- case 0xc6:
331
- // bin 32
332
- value = dataView.getUint32(position$1);
333
- position$1 += 4;
334
- return readBin(value)
335
- case 0xc7:
336
- // ext 8
337
- return readExt(src[position$1++])
338
- case 0xc8:
339
- // ext 16
340
- value = dataView.getUint16(position$1);
341
- position$1 += 2;
342
- return readExt(value)
343
- case 0xc9:
344
- // ext 32
345
- value = dataView.getUint32(position$1);
346
- position$1 += 4;
347
- return readExt(value)
348
- case 0xca:
349
- value = dataView.getFloat32(position$1);
350
- if (currentUnpackr.useFloat32 > 2) {
351
- // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
352
- let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
353
- position$1 += 4;
354
- return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
355
- }
356
- position$1 += 4;
357
- return value
358
- case 0xcb:
359
- value = dataView.getFloat64(position$1);
360
- position$1 += 8;
361
- return value
362
- // uint handlers
363
- case 0xcc:
364
- return src[position$1++]
365
- case 0xcd:
366
- value = dataView.getUint16(position$1);
367
- position$1 += 2;
368
- return value
369
- case 0xce:
370
- value = dataView.getUint32(position$1);
371
- position$1 += 4;
372
- return value
373
- case 0xcf:
374
- if (currentUnpackr.int64AsType === 'number') {
375
- value = dataView.getUint32(position$1) * 0x100000000;
376
- value += dataView.getUint32(position$1 + 4);
377
- } else if (currentUnpackr.int64AsType === 'string') {
378
- value = dataView.getBigUint64(position$1).toString();
379
- } else if (currentUnpackr.int64AsType === 'auto') {
380
- value = dataView.getBigUint64(position$1);
381
- if (value<=BigInt(2)<<BigInt(52)) value=Number(value);
382
- } else
383
- value = dataView.getBigUint64(position$1);
384
- position$1 += 8;
385
- return value
386
-
387
- // int handlers
388
- case 0xd0:
389
- return dataView.getInt8(position$1++)
390
- case 0xd1:
391
- value = dataView.getInt16(position$1);
392
- position$1 += 2;
393
- return value
394
- case 0xd2:
395
- value = dataView.getInt32(position$1);
396
- position$1 += 4;
397
- return value
398
- case 0xd3:
399
- if (currentUnpackr.int64AsType === 'number') {
400
- value = dataView.getInt32(position$1) * 0x100000000;
401
- value += dataView.getUint32(position$1 + 4);
402
- } else if (currentUnpackr.int64AsType === 'string') {
403
- value = dataView.getBigInt64(position$1).toString();
404
- } else if (currentUnpackr.int64AsType === 'auto') {
405
- value = dataView.getBigInt64(position$1);
406
- if (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);
407
- } else
408
- value = dataView.getBigInt64(position$1);
409
- position$1 += 8;
410
- return value
411
-
412
- case 0xd4:
413
- // fixext 1
414
- value = src[position$1++];
415
- if (value == 0x72) {
416
- return recordDefinition(src[position$1++] & 0x3f)
417
- } else {
418
- let extension = currentExtensions[value];
419
- if (extension) {
420
- if (extension.read) {
421
- position$1++; // skip filler byte
422
- return extension.read(read())
423
- } else if (extension.noBuffer) {
424
- position$1++; // skip filler byte
425
- return extension()
426
- } else
427
- return extension(src.subarray(position$1, ++position$1))
428
- } else
429
- throw new Error('Unknown extension ' + value)
430
- }
431
- case 0xd5:
432
- // fixext 2
433
- value = src[position$1];
434
- if (value == 0x72) {
435
- position$1++;
436
- return recordDefinition(src[position$1++] & 0x3f, src[position$1++])
437
- } else
438
- return readExt(2)
439
- case 0xd6:
440
- // fixext 4
441
- return readExt(4)
442
- case 0xd7:
443
- // fixext 8
444
- return readExt(8)
445
- case 0xd8:
446
- // fixext 16
447
- return readExt(16)
448
- case 0xd9:
449
- // str 8
450
- value = src[position$1++];
451
- if (srcStringEnd >= position$1) {
452
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
453
- }
454
- return readString8(value)
455
- case 0xda:
456
- // str 16
457
- value = dataView.getUint16(position$1);
458
- position$1 += 2;
459
- if (srcStringEnd >= position$1) {
460
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
461
- }
462
- return readString16(value)
463
- case 0xdb:
464
- // str 32
465
- value = dataView.getUint32(position$1);
466
- position$1 += 4;
467
- if (srcStringEnd >= position$1) {
468
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
469
- }
470
- return readString32(value)
471
- case 0xdc:
472
- // array 16
473
- value = dataView.getUint16(position$1);
474
- position$1 += 2;
475
- return readArray(value)
476
- case 0xdd:
477
- // array 32
478
- value = dataView.getUint32(position$1);
479
- position$1 += 4;
480
- return readArray(value)
481
- case 0xde:
482
- // map 16
483
- value = dataView.getUint16(position$1);
484
- position$1 += 2;
485
- return readMap(value)
486
- case 0xdf:
487
- // map 32
488
- value = dataView.getUint32(position$1);
489
- position$1 += 4;
490
- return readMap(value)
491
- default: // negative int
492
- if (token >= 0xe0)
493
- return token - 0x100
494
- if (token === undefined) {
495
- let error = new Error('Unexpected end of MessagePack data');
496
- error.incomplete = true;
497
- throw error
498
- }
499
- throw new Error('Unknown MessagePack token ' + token)
500
-
501
- }
502
- }
503
- }
504
- const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
505
- function createStructureReader(structure, firstId) {
506
- function readObject() {
507
- // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
508
- if (readObject.count++ > inlineObjectReadThreshold) {
509
- let readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
510
- '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
511
- if (structure.highByte === 0)
512
- structure.read = createSecondByteReader(firstId, structure.read);
513
- return readObject() // second byte is already read, if there is one so immediately read object
514
- }
515
- let object = {};
516
- for (let i = 0, l = structure.length; i < l; i++) {
517
- let key = structure[i];
518
- if (key === '__proto__')
519
- key = '__proto_';
520
- object[key] = read();
521
- }
522
- if (currentUnpackr.freezeData)
523
- return Object.freeze(object);
524
- return object
525
- }
526
- readObject.count = 0;
527
- if (structure.highByte === 0) {
528
- return createSecondByteReader(firstId, readObject)
529
- }
530
- return readObject
531
- }
532
-
533
- const createSecondByteReader = (firstId, read0) => {
534
- return function() {
535
- let highByte = src[position$1++];
536
- if (highByte === 0)
537
- return read0()
538
- let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
539
- let structure = currentStructures[id] || loadStructures()[id];
540
- if (!structure) {
541
- throw new Error('Record id is not defined for ' + id)
542
- }
543
- if (!structure.read)
544
- structure.read = createStructureReader(structure, firstId);
545
- return structure.read()
546
- }
547
- };
548
-
549
- function loadStructures() {
550
- let loadedStructures = saveState$1(() => {
551
- // save the state in case getStructures modifies our buffer
552
- src = null;
553
- return currentUnpackr.getStructures()
554
- });
555
- return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
556
- }
557
-
558
- var readFixedString = readStringJS;
559
- var readString8 = readStringJS;
560
- var readString16 = readStringJS;
561
- var readString32 = readStringJS;
562
-
563
- function setExtractor(extractStrings) {
564
- readFixedString = readString(1);
565
- readString8 = readString(2);
566
- readString16 = readString(3);
567
- readString32 = readString(5);
568
- function readString(headerLength) {
569
- return function readString(length) {
570
- let string = strings[stringPosition++];
571
- if (string == null) {
572
- if (bundledStrings$1)
573
- return readStringJS(length)
574
- let byteOffset = src.byteOffset;
575
- let extraction = extractStrings(position$1 - headerLength + byteOffset, srcEnd + byteOffset, src.buffer);
576
- if (typeof extraction == 'string') {
577
- string = extraction;
578
- strings = EMPTY_ARRAY;
579
- } else {
580
- strings = extraction;
581
- stringPosition = 1;
582
- srcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings
583
- string = strings[0];
584
- if (string === undefined)
585
- throw new Error('Unexpected end of buffer')
586
- }
587
- }
588
- let srcStringLength = string.length;
589
- if (srcStringLength <= length) {
590
- position$1 += length;
591
- return string
592
- }
593
- srcString = string;
594
- srcStringStart = position$1;
595
- srcStringEnd = position$1 + srcStringLength;
596
- position$1 += length;
597
- return string.slice(0, length) // we know we just want the beginning
598
- }
599
- }
600
- }
601
- function readStringJS(length) {
602
- let result;
603
- if (length < 16) {
604
- if (result = shortStringInJS(length))
605
- return result
606
- }
607
- if (length > 64 && decoder)
608
- return decoder.decode(src.subarray(position$1, position$1 += length))
609
- const end = position$1 + length;
610
- const units = [];
611
- result = '';
612
- while (position$1 < end) {
613
- const byte1 = src[position$1++];
614
- if ((byte1 & 0x80) === 0) {
615
- // 1 byte
616
- units.push(byte1);
617
- } else if ((byte1 & 0xe0) === 0xc0) {
618
- // 2 bytes
619
- const byte2 = src[position$1++] & 0x3f;
620
- units.push(((byte1 & 0x1f) << 6) | byte2);
621
- } else if ((byte1 & 0xf0) === 0xe0) {
622
- // 3 bytes
623
- const byte2 = src[position$1++] & 0x3f;
624
- const byte3 = src[position$1++] & 0x3f;
625
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
626
- } else if ((byte1 & 0xf8) === 0xf0) {
627
- // 4 bytes
628
- const byte2 = src[position$1++] & 0x3f;
629
- const byte3 = src[position$1++] & 0x3f;
630
- const byte4 = src[position$1++] & 0x3f;
631
- let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
632
- if (unit > 0xffff) {
633
- unit -= 0x10000;
634
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
635
- unit = 0xdc00 | (unit & 0x3ff);
636
- }
637
- units.push(unit);
638
- } else {
639
- units.push(byte1);
640
- }
641
-
642
- if (units.length >= 0x1000) {
643
- result += fromCharCode.apply(String, units);
644
- units.length = 0;
645
- }
646
- }
647
-
648
- if (units.length > 0) {
649
- result += fromCharCode.apply(String, units);
650
- }
651
-
652
- return result
653
- }
654
- function readString(source, start, length) {
655
- let existingSrc = src;
656
- src = source;
657
- position$1 = start;
658
- try {
659
- return readStringJS(length);
660
- } finally {
661
- src = existingSrc;
662
- }
663
- }
664
-
665
- function readArray(length) {
666
- let array = new Array(length);
667
- for (let i = 0; i < length; i++) {
668
- array[i] = read();
669
- }
670
- if (currentUnpackr.freezeData)
671
- return Object.freeze(array)
672
- return array
673
- }
674
-
675
- function readMap(length) {
676
- if (currentUnpackr.mapsAsObjects) {
677
- let object = {};
678
- for (let i = 0; i < length; i++) {
679
- let key = readKey();
680
- if (key === '__proto__')
681
- key = '__proto_';
682
- object[key] = read();
683
- }
684
- return object
685
- } else {
686
- let map = new Map();
687
- for (let i = 0; i < length; i++) {
688
- map.set(read(), read());
689
- }
690
- return map
691
- }
692
- }
693
-
694
- var fromCharCode = String.fromCharCode;
695
- function longStringInJS(length) {
696
- let start = position$1;
697
- let bytes = new Array(length);
698
- for (let i = 0; i < length; i++) {
699
- const byte = src[position$1++];
700
- if ((byte & 0x80) > 0) {
701
- position$1 = start;
702
- return
703
- }
704
- bytes[i] = byte;
705
- }
706
- return fromCharCode.apply(String, bytes)
707
- }
708
- function shortStringInJS(length) {
709
- if (length < 4) {
710
- if (length < 2) {
711
- if (length === 0)
712
- return ''
713
- else {
714
- let a = src[position$1++];
715
- if ((a & 0x80) > 1) {
716
- position$1 -= 1;
717
- return
718
- }
719
- return fromCharCode(a)
720
- }
721
- } else {
722
- let a = src[position$1++];
723
- let b = src[position$1++];
724
- if ((a & 0x80) > 0 || (b & 0x80) > 0) {
725
- position$1 -= 2;
726
- return
727
- }
728
- if (length < 3)
729
- return fromCharCode(a, b)
730
- let c = src[position$1++];
731
- if ((c & 0x80) > 0) {
732
- position$1 -= 3;
733
- return
734
- }
735
- return fromCharCode(a, b, c)
736
- }
737
- } else {
738
- let a = src[position$1++];
739
- let b = src[position$1++];
740
- let c = src[position$1++];
741
- let d = src[position$1++];
742
- if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
743
- position$1 -= 4;
744
- return
745
- }
746
- if (length < 6) {
747
- if (length === 4)
748
- return fromCharCode(a, b, c, d)
749
- else {
750
- let e = src[position$1++];
751
- if ((e & 0x80) > 0) {
752
- position$1 -= 5;
753
- return
754
- }
755
- return fromCharCode(a, b, c, d, e)
756
- }
757
- } else if (length < 8) {
758
- let e = src[position$1++];
759
- let f = src[position$1++];
760
- if ((e & 0x80) > 0 || (f & 0x80) > 0) {
761
- position$1 -= 6;
762
- return
763
- }
764
- if (length < 7)
765
- return fromCharCode(a, b, c, d, e, f)
766
- let g = src[position$1++];
767
- if ((g & 0x80) > 0) {
768
- position$1 -= 7;
769
- return
770
- }
771
- return fromCharCode(a, b, c, d, e, f, g)
772
- } else {
773
- let e = src[position$1++];
774
- let f = src[position$1++];
775
- let g = src[position$1++];
776
- let h = src[position$1++];
777
- if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
778
- position$1 -= 8;
779
- return
780
- }
781
- if (length < 10) {
782
- if (length === 8)
783
- return fromCharCode(a, b, c, d, e, f, g, h)
784
- else {
785
- let i = src[position$1++];
786
- if ((i & 0x80) > 0) {
787
- position$1 -= 9;
788
- return
789
- }
790
- return fromCharCode(a, b, c, d, e, f, g, h, i)
791
- }
792
- } else if (length < 12) {
793
- let i = src[position$1++];
794
- let j = src[position$1++];
795
- if ((i & 0x80) > 0 || (j & 0x80) > 0) {
796
- position$1 -= 10;
797
- return
798
- }
799
- if (length < 11)
800
- return fromCharCode(a, b, c, d, e, f, g, h, i, j)
801
- let k = src[position$1++];
802
- if ((k & 0x80) > 0) {
803
- position$1 -= 11;
804
- return
805
- }
806
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
807
- } else {
808
- let i = src[position$1++];
809
- let j = src[position$1++];
810
- let k = src[position$1++];
811
- let l = src[position$1++];
812
- if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
813
- position$1 -= 12;
814
- return
815
- }
816
- if (length < 14) {
817
- if (length === 12)
818
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
819
- else {
820
- let m = src[position$1++];
821
- if ((m & 0x80) > 0) {
822
- position$1 -= 13;
823
- return
824
- }
825
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
826
- }
827
- } else {
828
- let m = src[position$1++];
829
- let n = src[position$1++];
830
- if ((m & 0x80) > 0 || (n & 0x80) > 0) {
831
- position$1 -= 14;
832
- return
833
- }
834
- if (length < 15)
835
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
836
- let o = src[position$1++];
837
- if ((o & 0x80) > 0) {
838
- position$1 -= 15;
839
- return
840
- }
841
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
842
- }
843
- }
844
- }
845
- }
846
- }
847
-
848
- function readOnlyJSString() {
849
- let token = src[position$1++];
850
- let length;
851
- if (token < 0xc0) {
852
- // fixstr
853
- length = token - 0xa0;
854
- } else {
855
- switch(token) {
856
- case 0xd9:
857
- // str 8
858
- length = src[position$1++];
859
- break
860
- case 0xda:
861
- // str 16
862
- length = dataView.getUint16(position$1);
863
- position$1 += 2;
864
- break
865
- case 0xdb:
866
- // str 32
867
- length = dataView.getUint32(position$1);
868
- position$1 += 4;
869
- break
870
- default:
871
- throw new Error('Expected string')
872
- }
873
- }
874
- return readStringJS(length)
875
- }
876
-
877
-
878
- function readBin(length) {
879
- return currentUnpackr.copyBuffers ?
880
- // specifically use the copying slice (not the node one)
881
- Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
882
- src.subarray(position$1, position$1 += length)
883
- }
884
- function readExt(length) {
885
- let type = src[position$1++];
886
- if (currentExtensions[type]) {
887
- let end;
888
- return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => {
889
- position$1 = readPosition;
890
- try {
891
- return read();
892
- } finally {
893
- position$1 = end;
894
- }
895
- })
896
- }
897
- else
898
- throw new Error('Unknown extension type ' + type)
899
- }
900
-
901
- var keyCache = new Array(4096);
902
- function readKey() {
903
- let length = src[position$1++];
904
- if (length >= 0xa0 && length < 0xc0) {
905
- // fixstr, potentially use key cache
906
- length = length - 0xa0;
907
- if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway)
908
- return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
909
- else if (!(srcStringEnd == 0 && srcEnd < 180))
910
- return readFixedString(length)
911
- } else { // not cacheable, go back and do a standard read
912
- position$1--;
913
- return asSafeString(read())
914
- }
915
- let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff;
916
- let entry = keyCache[key];
917
- let checkPosition = position$1;
918
- let end = position$1 + length - 3;
919
- let chunk;
920
- let i = 0;
921
- if (entry && entry.bytes == length) {
922
- while (checkPosition < end) {
923
- chunk = dataView.getUint32(checkPosition);
924
- if (chunk != entry[i++]) {
925
- checkPosition = 0x70000000;
926
- break
927
- }
928
- checkPosition += 4;
929
- }
930
- end += 3;
931
- while (checkPosition < end) {
932
- chunk = src[checkPosition++];
933
- if (chunk != entry[i++]) {
934
- checkPosition = 0x70000000;
935
- break
936
- }
937
- }
938
- if (checkPosition === end) {
939
- position$1 = checkPosition;
940
- return entry.string
941
- }
942
- end -= 3;
943
- checkPosition = position$1;
944
- }
945
- entry = [];
946
- keyCache[key] = entry;
947
- entry.bytes = length;
948
- while (checkPosition < end) {
949
- chunk = dataView.getUint32(checkPosition);
950
- entry.push(chunk);
951
- checkPosition += 4;
952
- }
953
- end += 3;
954
- while (checkPosition < end) {
955
- chunk = src[checkPosition++];
956
- entry.push(chunk);
957
- }
958
- // for small blocks, avoiding the overhead of the extract call is helpful
959
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
960
- if (string != null)
961
- return entry.string = string
962
- return entry.string = readFixedString(length)
963
- }
964
-
965
- function asSafeString(property) {
966
- // protect against expensive (DoS) string conversions
967
- if (typeof property === 'string') return property;
968
- if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();
969
- if (property == null) return property + '';
970
- if (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every(item => ['string', 'number', 'boolean', 'bigint'].includes(typeof item))) {
971
- return property.flat().toString();
972
- }
973
- throw new Error(`Invalid property type for record: ${typeof property}`);
974
- }
975
- // the registration of the record definition extension (as "r")
976
- const recordDefinition = (id, highByte) => {
977
- let structure = read().map(asSafeString); // ensure that all keys are strings and
978
- // that the array is mutable
979
- let firstByte = id;
980
- if (highByte !== undefined) {
981
- id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
982
- structure.highByte = highByte;
983
- }
984
- let existingStructure = currentStructures[id];
985
- // If it is a shared structure, we need to restore any changes after reading.
986
- // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
987
- // to the state prior to an incomplete read in order to properly resume.
988
- if (existingStructure && (existingStructure.isShared || sequentialMode)) {
989
- (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
990
- }
991
- currentStructures[id] = structure;
992
- structure.read = createStructureReader(structure, firstByte);
993
- return structure.read()
994
- };
995
- currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
996
- currentExtensions[0].noBuffer = true;
997
-
998
- currentExtensions[0x42] = data => {
999
- let headLength = (data.byteLength % 8) || 8;
1000
- let head = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
1001
- for (let i = 1; i < headLength; i++) {
1002
- head <<= BigInt(8);
1003
- head += BigInt(data[i]);
1004
- }
1005
- if (data.byteLength !== headLength) {
1006
- let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1007
- let decode = (start, end) => {
1008
- let length = end - start;
1009
- if (length <= 40) {
1010
- let out = view.getBigUint64(start);
1011
- for (let i = start + 8; i < end; i += 8) {
1012
- out <<= BigInt(64n);
1013
- out |= view.getBigUint64(i);
1014
- }
1015
- return out
1016
- }
1017
- // if (length === 8) return view.getBigUint64(start)
1018
- let middle = start + (length >> 4 << 3);
1019
- let left = decode(start, middle);
1020
- let right = decode(middle, end);
1021
- return (left << BigInt((end - middle) * 8)) | right
1022
- };
1023
- head = (head << BigInt((view.byteLength - headLength) * 8)) | decode(headLength, view.byteLength);
1024
- }
1025
- return head
1026
- };
1027
-
1028
- let errors = {
1029
- Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError: typeof AggregateError === 'function' ? AggregateError : null,
1030
- };
1031
- currentExtensions[0x65] = () => {
1032
- let data = read();
1033
- if (!errors[data[0]]) {
1034
- let error = Error(data[1], { cause: data[2] });
1035
- error.name = data[0];
1036
- return error
1037
- }
1038
- return errors[data[0]](data[1], { cause: data[2] })
1039
- };
1040
-
1041
- currentExtensions[0x69] = (data) => {
1042
- // id extension (for structured clones)
1043
- if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
1044
- let id = dataView.getUint32(position$1 - 4);
1045
- if (!referenceMap)
1046
- referenceMap = new Map();
1047
- let token = src[position$1];
1048
- let target;
1049
- // TODO: handle any other types that can cycle and make the code more robust if there are other extensions
1050
- if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
1051
- target = [];
1052
- else if (token >= 0x80 && token < 0x90 || token == 0xde || token == 0xdf)
1053
- target = new Map();
1054
- else if ((token >= 0xc7 && token <= 0xc9 || token >= 0xd4 && token <= 0xd8) && src[position$1 + 1] === 0x73)
1055
- target = new Set();
1056
- else
1057
- target = {};
1058
-
1059
- let refEntry = { target }; // a placeholder object
1060
- referenceMap.set(id, refEntry);
1061
- let targetProperties = read(); // read the next value as the target object to id
1062
- if (!refEntry.used) {
1063
- // no cycle, can just use the returned read object
1064
- return refEntry.target = targetProperties // replace the placeholder with the real one
1065
- } else {
1066
- // there is a cycle, so we have to assign properties to original target
1067
- Object.assign(target, targetProperties);
1068
- }
1069
-
1070
- // copy over map/set entries if we're able to
1071
- if (target instanceof Map)
1072
- for (let [k, v] of targetProperties.entries()) target.set(k, v);
1073
- if (target instanceof Set)
1074
- for (let i of Array.from(targetProperties)) target.add(i);
1075
- return target
1076
- };
1077
-
1078
- currentExtensions[0x70] = (data) => {
1079
- // pointer extension (for structured clones)
1080
- if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
1081
- let id = dataView.getUint32(position$1 - 4);
1082
- let refEntry = referenceMap.get(id);
1083
- refEntry.used = true;
1084
- return refEntry.target
1085
- };
1086
-
1087
- currentExtensions[0x73] = () => new Set(read());
1088
-
1089
- const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
1090
-
1091
- let glbl = typeof globalThis === 'object' ? globalThis : window;
1092
- currentExtensions[0x74] = (data) => {
1093
- let typeCode = data[0];
1094
- // we always have to slice to get a new ArrayBuffer that is aligned
1095
- let buffer = Uint8Array.prototype.slice.call(data, 1).buffer;
1096
-
1097
- let typedArrayName = typedArrays[typeCode];
1098
- if (!typedArrayName) {
1099
- if (typeCode === 16) return buffer
1100
- if (typeCode === 17) return new DataView(buffer)
1101
- throw new Error('Could not find typed array for code ' + typeCode)
1102
- }
1103
- return new glbl[typedArrayName](buffer)
1104
- };
1105
- currentExtensions[0x78] = () => {
1106
- let data = read();
1107
- return new RegExp(data[0], data[1])
1108
- };
1109
- const TEMP_BUNDLE = [];
1110
- currentExtensions[0x62] = (data) => {
1111
- let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
1112
- let dataPosition = position$1;
1113
- position$1 += dataSize - data.length;
1114
- bundledStrings$1 = TEMP_BUNDLE;
1115
- bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
1116
- bundledStrings$1.position0 = 0;
1117
- bundledStrings$1.position1 = 0;
1118
- bundledStrings$1.postBundlePosition = position$1;
1119
- position$1 = dataPosition;
1120
- return read()
1121
- };
1122
-
1123
- currentExtensions[0xff] = (data) => {
1124
- // 32-bit date extension
1125
- if (data.length == 4)
1126
- return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
1127
- else if (data.length == 8)
1128
- return new Date(
1129
- ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
1130
- ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
1131
- else if (data.length == 12)
1132
- return new Date(
1133
- ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
1134
- (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
1135
- else
1136
- return new Date('invalid')
1137
- };
1138
- // registration of bulk record definition?
1139
- // currentExtensions[0x52] = () =>
1140
-
1141
- function saveState$1(callback) {
1142
- if (onSaveState)
1143
- onSaveState();
1144
- let savedSrcEnd = srcEnd;
1145
- let savedPosition = position$1;
1146
- let savedStringPosition = stringPosition;
1147
- let savedSrcStringStart = srcStringStart;
1148
- let savedSrcStringEnd = srcStringEnd;
1149
- let savedSrcString = srcString;
1150
- let savedStrings = strings;
1151
- let savedReferenceMap = referenceMap;
1152
- let savedBundledStrings = bundledStrings$1;
1153
-
1154
- // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
1155
- let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
1156
- let savedStructures = currentStructures;
1157
- let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
1158
- let savedPackr = currentUnpackr;
1159
- let savedSequentialMode = sequentialMode;
1160
- let value = callback();
1161
- srcEnd = savedSrcEnd;
1162
- position$1 = savedPosition;
1163
- stringPosition = savedStringPosition;
1164
- srcStringStart = savedSrcStringStart;
1165
- srcStringEnd = savedSrcStringEnd;
1166
- srcString = savedSrcString;
1167
- strings = savedStrings;
1168
- referenceMap = savedReferenceMap;
1169
- bundledStrings$1 = savedBundledStrings;
1170
- src = savedSrc;
1171
- sequentialMode = savedSequentialMode;
1172
- currentStructures = savedStructures;
1173
- currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
1174
- currentUnpackr = savedPackr;
1175
- dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1176
- return value
1177
- }
1178
- function clearSource() {
1179
- src = null;
1180
- referenceMap = null;
1181
- currentStructures = null;
1182
- }
1183
-
1184
- function addExtension$2(extension) {
1185
- if (extension.unpack)
1186
- currentExtensions[extension.type] = extension.unpack;
1187
- else
1188
- currentExtensions[extension.type] = extension;
1189
- }
1190
-
1191
- const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1192
- for (let i = 0; i < 256; i++) {
1193
- mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1194
- }
1195
- var defaultUnpackr = new Unpackr$1({ useRecords: false });
1196
- const unpack$1 = defaultUnpackr.unpack;
1197
- const unpackMultiple$1 = defaultUnpackr.unpackMultiple;
1198
- defaultUnpackr.unpack;
1199
- const FLOAT32_OPTIONS = {
1200
- NEVER: 0,
1201
- ALWAYS: 1,
1202
- DECIMAL_ROUND: 3,
1203
- DECIMAL_FIT: 4
1204
- };
1205
- let f32Array = new Float32Array(1);
1206
- let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
1207
- function roundFloat32$1(float32Number) {
1208
- f32Array[0] = float32Number;
1209
- let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1210
- return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
1211
- }
1212
- function setReadStruct(updatedReadStruct, loadedStructs, saveState) {
1213
- readStruct$1 = updatedReadStruct;
1214
- onLoadedStructures$1 = loadedStructs;
1215
- onSaveState = saveState;
1216
- }
1217
-
1218
- let textEncoder$1;
1219
- try {
1220
- textEncoder$1 = new TextEncoder();
1221
- } catch (error) {}
1222
- let extensions, extensionClasses;
1223
- const hasNodeBuffer$1 = typeof Buffer !== 'undefined';
1224
- const ByteArrayAllocate = hasNodeBuffer$1 ?
1225
- function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
1226
- const ByteArray = hasNodeBuffer$1 ? Buffer : Uint8Array;
1227
- const MAX_BUFFER_SIZE = hasNodeBuffer$1 ? 0x100000000 : 0x7fd00000;
1228
- let target, keysTarget;
1229
- let targetView;
1230
- let position = 0;
1231
- let safeEnd;
1232
- let bundledStrings = null;
1233
- let writeStructSlots;
1234
- const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
1235
- const hasNonLatin = /[\u0080-\uFFFF]/;
1236
- const RECORD_SYMBOL = Symbol('record-id');
1237
- let Packr$1 = class Packr extends Unpackr$1 {
1238
- constructor(options) {
1239
- super(options);
1240
- this.offset = 0;
1241
- let start;
1242
- let hasSharedUpdate;
1243
- let structures;
1244
- let referenceMap;
1245
- let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
1246
- return target.utf8Write(string, position, target.byteLength - position)
1247
- } : (textEncoder$1 && textEncoder$1.encodeInto) ?
1248
- function(string, position) {
1249
- return textEncoder$1.encodeInto(string, target.subarray(position)).written
1250
- } : false;
1251
-
1252
- let packr = this;
1253
- if (!options)
1254
- options = {};
1255
- let isSequential = options && options.sequential;
1256
- let hasSharedStructures = options.structures || options.saveStructures;
1257
- let maxSharedStructures = options.maxSharedStructures;
1258
- if (maxSharedStructures == null)
1259
- maxSharedStructures = hasSharedStructures ? 32 : 0;
1260
- if (maxSharedStructures > 8160)
1261
- throw new Error('Maximum maxSharedStructure is 8160')
1262
- if (options.structuredClone && options.moreTypes == undefined) {
1263
- this.moreTypes = true;
1264
- }
1265
- let maxOwnStructures = options.maxOwnStructures;
1266
- if (maxOwnStructures == null)
1267
- maxOwnStructures = hasSharedStructures ? 32 : 64;
1268
- if (!this.structures && options.useRecords != false)
1269
- this.structures = [];
1270
- // two byte record ids for shared structures
1271
- let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
1272
- let sharedLimitId = maxSharedStructures + 0x40;
1273
- let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
1274
- if (maxStructureId > 8256) {
1275
- throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
1276
- }
1277
- let recordIdsToRemove = [];
1278
- let transitionsCount = 0;
1279
- let serializationsSinceTransitionRebuild = 0;
1280
-
1281
- this.pack = this.encode = function(value, encodeOptions) {
1282
- if (!target) {
1283
- target = new ByteArrayAllocate(8192);
1284
- targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
1285
- position = 0;
1286
- }
1287
- safeEnd = target.length - 10;
1288
- if (safeEnd - position < 0x800) {
1289
- // don't start too close to the end,
1290
- target = new ByteArrayAllocate(target.length);
1291
- targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
1292
- safeEnd = target.length - 10;
1293
- position = 0;
1294
- } else
1295
- position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1296
- start = position;
1297
- if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);
1298
- referenceMap = packr.structuredClone ? new Map() : null;
1299
- if (packr.bundleStrings && typeof value !== 'string') {
1300
- bundledStrings = [];
1301
- bundledStrings.size = Infinity; // force a new bundle start on first string
1302
- } else
1303
- bundledStrings = null;
1304
- structures = packr.structures;
1305
- if (structures) {
1306
- if (structures.uninitialized)
1307
- structures = packr._mergeStructures(packr.getStructures());
1308
- let sharedLength = structures.sharedLength || 0;
1309
- if (sharedLength > maxSharedStructures) {
1310
- //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
1311
- throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
1312
- }
1313
- if (!structures.transitions) {
1314
- // rebuild our structure transitions
1315
- structures.transitions = Object.create(null);
1316
- for (let i = 0; i < sharedLength; i++) {
1317
- let keys = structures[i];
1318
- if (!keys)
1319
- continue
1320
- let nextTransition, transition = structures.transitions;
1321
- for (let j = 0, l = keys.length; j < l; j++) {
1322
- let key = keys[j];
1323
- nextTransition = transition[key];
1324
- if (!nextTransition) {
1325
- nextTransition = transition[key] = Object.create(null);
1326
- }
1327
- transition = nextTransition;
1328
- }
1329
- transition[RECORD_SYMBOL] = i + 0x40;
1330
- }
1331
- this.lastNamedStructuresLength = sharedLength;
1332
- }
1333
- if (!isSequential) {
1334
- structures.nextId = sharedLength + 0x40;
1335
- }
1336
- }
1337
- if (hasSharedUpdate)
1338
- hasSharedUpdate = false;
1339
- let encodingError;
1340
- try {
1341
- if (packr.randomAccessStructure && value && typeof value === 'object') {
1342
- if (value.constructor === Object) writeStruct(value); // simple object
1343
- else if (value.constructor !== Map && !Array.isArray(value) && !extensionClasses.some(extClass => value instanceof extClass)) {
1344
- // allow user classes, if they don't need special handling (but do use toJSON if available)
1345
- writeStruct(value.toJSON ? value.toJSON() : value);
1346
- } else pack(value);
1347
- } else
1348
- pack(value);
1349
- let lastBundle = bundledStrings;
1350
- if (bundledStrings)
1351
- writeBundles(start, pack, 0);
1352
- if (referenceMap && referenceMap.idsToInsert) {
1353
- let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
1354
- let i = idsToInsert.length;
1355
- let incrementPosition = -1;
1356
- while (lastBundle && i > 0) {
1357
- let insertionPoint = idsToInsert[--i].offset + start;
1358
- if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
1359
- incrementPosition = 0;
1360
- if (insertionPoint > (lastBundle.position + start)) {
1361
- if (incrementPosition >= 0)
1362
- incrementPosition += 6;
1363
- } else {
1364
- if (incrementPosition >= 0) {
1365
- // update the bundle reference now
1366
- targetView.setUint32(lastBundle.position + start,
1367
- targetView.getUint32(lastBundle.position + start) + incrementPosition);
1368
- incrementPosition = -1; // reset
1369
- }
1370
- lastBundle = lastBundle.previous;
1371
- i++;
1372
- }
1373
- }
1374
- if (incrementPosition >= 0 && lastBundle) {
1375
- // update the bundle reference now
1376
- targetView.setUint32(lastBundle.position + start,
1377
- targetView.getUint32(lastBundle.position + start) + incrementPosition);
1378
- }
1379
- position += idsToInsert.length * 6;
1380
- if (position > safeEnd)
1381
- makeRoom(position);
1382
- packr.offset = position;
1383
- let serialized = insertIds(target.subarray(start, position), idsToInsert);
1384
- referenceMap = null;
1385
- return serialized
1386
- }
1387
- packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1388
- if (encodeOptions & REUSE_BUFFER_MODE) {
1389
- target.start = start;
1390
- target.end = position;
1391
- return target
1392
- }
1393
- return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
1394
- } catch(error) {
1395
- encodingError = error;
1396
- throw error;
1397
- } finally {
1398
- if (structures) {
1399
- resetStructures();
1400
- if (hasSharedUpdate && packr.saveStructures) {
1401
- let sharedLength = structures.sharedLength || 0;
1402
- // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1403
- let returnBuffer = target.subarray(start, position);
1404
- let newSharedData = prepareStructures$1(structures, packr);
1405
- if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time
1406
- if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
1407
- // get updated structures and try again if the update failed
1408
- return packr.pack(value, encodeOptions)
1409
- }
1410
- packr.lastNamedStructuresLength = sharedLength;
1411
- // don't keep large buffers around
1412
- if (target.length > 0x40000000) target = null;
1413
- return returnBuffer
1414
- }
1415
- }
1416
- }
1417
- // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)
1418
- if (target.length > 0x40000000) target = null;
1419
- if (encodeOptions & RESET_BUFFER_MODE)
1420
- position = start;
1421
- }
1422
- };
1423
- const resetStructures = () => {
1424
- if (serializationsSinceTransitionRebuild < 10)
1425
- serializationsSinceTransitionRebuild++;
1426
- let sharedLength = structures.sharedLength || 0;
1427
- if (structures.length > sharedLength && !isSequential)
1428
- structures.length = sharedLength;
1429
- if (transitionsCount > 10000) {
1430
- // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1431
- structures.transitions = null;
1432
- serializationsSinceTransitionRebuild = 0;
1433
- transitionsCount = 0;
1434
- if (recordIdsToRemove.length > 0)
1435
- recordIdsToRemove = [];
1436
- } else if (recordIdsToRemove.length > 0 && !isSequential) {
1437
- for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1438
- recordIdsToRemove[i][RECORD_SYMBOL] = 0;
1439
- }
1440
- recordIdsToRemove = [];
1441
- }
1442
- };
1443
- const packArray = (value) => {
1444
- var length = value.length;
1445
- if (length < 0x10) {
1446
- target[position++] = 0x90 | length;
1447
- } else if (length < 0x10000) {
1448
- target[position++] = 0xdc;
1449
- target[position++] = length >> 8;
1450
- target[position++] = length & 0xff;
1451
- } else {
1452
- target[position++] = 0xdd;
1453
- targetView.setUint32(position, length);
1454
- position += 4;
1455
- }
1456
- for (let i = 0; i < length; i++) {
1457
- pack(value[i]);
1458
- }
1459
- };
1460
- const pack = (value) => {
1461
- if (position > safeEnd)
1462
- target = makeRoom(position);
1463
-
1464
- var type = typeof value;
1465
- var length;
1466
- if (type === 'string') {
1467
- let strLength = value.length;
1468
- if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
1469
- if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
1470
- let extStart;
1471
- let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
1472
- if (position + maxBytes > safeEnd)
1473
- target = makeRoom(position + maxBytes);
1474
- let lastBundle;
1475
- 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
1476
- lastBundle = bundledStrings;
1477
- target[position] = 0xc8; // ext 16
1478
- position += 3; // reserve for the writing bundle size
1479
- target[position++] = 0x62; // 'b'
1480
- extStart = position - start;
1481
- position += 4; // reserve for writing bundle reference
1482
- writeBundles(start, pack, 0); // write the last bundles
1483
- targetView.setUint16(extStart + start - 3, position - start - extStart);
1484
- } 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)
1485
- target[position++] = 0xd6; // fixext 4
1486
- target[position++] = 0x62; // 'b'
1487
- extStart = position - start;
1488
- position += 4; // reserve for writing bundle reference
1489
- }
1490
- bundledStrings = ['', '']; // create new ones
1491
- bundledStrings.previous = lastBundle;
1492
- bundledStrings.size = 0;
1493
- bundledStrings.position = extStart;
1494
- }
1495
- let twoByte = hasNonLatin.test(value);
1496
- bundledStrings[twoByte ? 0 : 1] += value;
1497
- target[position++] = 0xc1;
1498
- pack(twoByte ? -strLength : strLength);
1499
- return
1500
- }
1501
- let headerSize;
1502
- // first we estimate the header size, so we can write to the correct location
1503
- if (strLength < 0x20) {
1504
- headerSize = 1;
1505
- } else if (strLength < 0x100) {
1506
- headerSize = 2;
1507
- } else if (strLength < 0x10000) {
1508
- headerSize = 3;
1509
- } else {
1510
- headerSize = 5;
1511
- }
1512
- let maxBytes = strLength * 3;
1513
- if (position + maxBytes > safeEnd)
1514
- target = makeRoom(position + maxBytes);
1515
-
1516
- if (strLength < 0x40 || !encodeUtf8) {
1517
- let i, c1, c2, strPosition = position + headerSize;
1518
- for (i = 0; i < strLength; i++) {
1519
- c1 = value.charCodeAt(i);
1520
- if (c1 < 0x80) {
1521
- target[strPosition++] = c1;
1522
- } else if (c1 < 0x800) {
1523
- target[strPosition++] = c1 >> 6 | 0xc0;
1524
- target[strPosition++] = c1 & 0x3f | 0x80;
1525
- } else if (
1526
- (c1 & 0xfc00) === 0xd800 &&
1527
- ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1528
- ) {
1529
- c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1530
- i++;
1531
- target[strPosition++] = c1 >> 18 | 0xf0;
1532
- target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1533
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1534
- target[strPosition++] = c1 & 0x3f | 0x80;
1535
- } else {
1536
- target[strPosition++] = c1 >> 12 | 0xe0;
1537
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1538
- target[strPosition++] = c1 & 0x3f | 0x80;
1539
- }
1540
- }
1541
- length = strPosition - position - headerSize;
1542
- } else {
1543
- length = encodeUtf8(value, position + headerSize);
1544
- }
1545
-
1546
- if (length < 0x20) {
1547
- target[position++] = 0xa0 | length;
1548
- } else if (length < 0x100) {
1549
- if (headerSize < 2) {
1550
- target.copyWithin(position + 2, position + 1, position + 1 + length);
1551
- }
1552
- target[position++] = 0xd9;
1553
- target[position++] = length;
1554
- } else if (length < 0x10000) {
1555
- if (headerSize < 3) {
1556
- target.copyWithin(position + 3, position + 2, position + 2 + length);
1557
- }
1558
- target[position++] = 0xda;
1559
- target[position++] = length >> 8;
1560
- target[position++] = length & 0xff;
1561
- } else {
1562
- if (headerSize < 5) {
1563
- target.copyWithin(position + 5, position + 3, position + 3 + length);
1564
- }
1565
- target[position++] = 0xdb;
1566
- targetView.setUint32(position, length);
1567
- position += 4;
1568
- }
1569
- position += length;
1570
- } else if (type === 'number') {
1571
- if (value >>> 0 === value) {// positive integer, 32-bit or less
1572
- // positive uint
1573
- if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
1574
- target[position++] = value;
1575
- } else if (value < 0x100) {
1576
- target[position++] = 0xcc;
1577
- target[position++] = value;
1578
- } else if (value < 0x10000) {
1579
- target[position++] = 0xcd;
1580
- target[position++] = value >> 8;
1581
- target[position++] = value & 0xff;
1582
- } else {
1583
- target[position++] = 0xce;
1584
- targetView.setUint32(position, value);
1585
- position += 4;
1586
- }
1587
- } else if (value >> 0 === value) { // negative integer
1588
- if (value >= -0x20) {
1589
- target[position++] = 0x100 + value;
1590
- } else if (value >= -0x80) {
1591
- target[position++] = 0xd0;
1592
- target[position++] = value + 0x100;
1593
- } else if (value >= -0x8000) {
1594
- target[position++] = 0xd1;
1595
- targetView.setInt16(position, value);
1596
- position += 2;
1597
- } else {
1598
- target[position++] = 0xd2;
1599
- targetView.setInt32(position, value);
1600
- position += 4;
1601
- }
1602
- } else {
1603
- let useFloat32;
1604
- if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1605
- target[position++] = 0xca;
1606
- targetView.setFloat32(position, value);
1607
- let xShifted;
1608
- if (useFloat32 < 4 ||
1609
- // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1610
- ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
1611
- position += 4;
1612
- return
1613
- } else
1614
- position--; // move back into position for writing a double
1615
- }
1616
- target[position++] = 0xcb;
1617
- targetView.setFloat64(position, value);
1618
- position += 8;
1619
- }
1620
- } else if (type === 'object' || type === 'function') {
1621
- if (!value)
1622
- target[position++] = 0xc0;
1623
- else {
1624
- if (referenceMap) {
1625
- let referee = referenceMap.get(value);
1626
- if (referee) {
1627
- if (!referee.id) {
1628
- let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1629
- referee.id = idsToInsert.push(referee);
1630
- }
1631
- target[position++] = 0xd6; // fixext 4
1632
- target[position++] = 0x70; // "p" for pointer
1633
- targetView.setUint32(position, referee.id);
1634
- position += 4;
1635
- return
1636
- } else
1637
- referenceMap.set(value, { offset: position - start });
1638
- }
1639
- let constructor = value.constructor;
1640
- if (constructor === Object) {
1641
- writeObject(value);
1642
- } else if (constructor === Array) {
1643
- packArray(value);
1644
- } else if (constructor === Map) {
1645
- if (this.mapAsEmptyObject) target[position++] = 0x80;
1646
- else {
1647
- length = value.size;
1648
- if (length < 0x10) {
1649
- target[position++] = 0x80 | length;
1650
- } else if (length < 0x10000) {
1651
- target[position++] = 0xde;
1652
- target[position++] = length >> 8;
1653
- target[position++] = length & 0xff;
1654
- } else {
1655
- target[position++] = 0xdf;
1656
- targetView.setUint32(position, length);
1657
- position += 4;
1658
- }
1659
- for (let [key, entryValue] of value) {
1660
- pack(key);
1661
- pack(entryValue);
1662
- }
1663
- }
1664
- } else {
1665
- for (let i = 0, l = extensions.length; i < l; i++) {
1666
- let extensionClass = extensionClasses[i];
1667
- if (value instanceof extensionClass) {
1668
- let extension = extensions[i];
1669
- if (extension.write) {
1670
- if (extension.type) {
1671
- target[position++] = 0xd4; // one byte "tag" extension
1672
- target[position++] = extension.type;
1673
- target[position++] = 0;
1674
- }
1675
- let writeResult = extension.write.call(this, value);
1676
- if (writeResult === value) { // avoid infinite recursion
1677
- if (Array.isArray(value)) {
1678
- packArray(value);
1679
- } else {
1680
- writeObject(value);
1681
- }
1682
- } else {
1683
- pack(writeResult);
1684
- }
1685
- return
1686
- }
1687
- let currentTarget = target;
1688
- let currentTargetView = targetView;
1689
- let currentPosition = position;
1690
- target = null;
1691
- let result;
1692
- try {
1693
- result = extension.pack.call(this, value, (size) => {
1694
- // restore target and use it
1695
- target = currentTarget;
1696
- currentTarget = null;
1697
- position += size;
1698
- if (position > safeEnd)
1699
- makeRoom(position);
1700
- return {
1701
- target, targetView, position: position - size
1702
- }
1703
- }, pack);
1704
- } finally {
1705
- // restore current target information (unless already restored)
1706
- if (currentTarget) {
1707
- target = currentTarget;
1708
- targetView = currentTargetView;
1709
- position = currentPosition;
1710
- safeEnd = target.length - 10;
1711
- }
1712
- }
1713
- if (result) {
1714
- if (result.length + position > safeEnd)
1715
- makeRoom(result.length + position);
1716
- position = writeExtensionData(result, target, position, extension.type);
1717
- }
1718
- return
1719
- }
1720
- }
1721
- // check isArray after extensions, because extensions can extend Array
1722
- if (Array.isArray(value)) {
1723
- packArray(value);
1724
- } else {
1725
- // use this as an alternate mechanism for expressing how to serialize
1726
- if (value.toJSON) {
1727
- const json = value.toJSON();
1728
- // if for some reason value.toJSON returns itself it'll loop forever
1729
- if (json !== value)
1730
- return pack(json)
1731
- }
1732
-
1733
- // if there is a writeFunction, use it, otherwise just encode as undefined
1734
- if (type === 'function')
1735
- return pack(this.writeFunction && this.writeFunction(value));
1736
-
1737
- // no extension found, write as plain object
1738
- writeObject(value);
1739
- }
1740
- }
1741
- }
1742
- } else if (type === 'boolean') {
1743
- target[position++] = value ? 0xc3 : 0xc2;
1744
- } else if (type === 'bigint') {
1745
- if (value < 0x8000000000000000 && value >= -0x8000000000000000) {
1746
- // use a signed int as long as it fits
1747
- target[position++] = 0xd3;
1748
- targetView.setBigInt64(position, value);
1749
- } else if (value < 0x10000000000000000 && value > 0) {
1750
- // if we can fit an unsigned int, use that
1751
- target[position++] = 0xcf;
1752
- targetView.setBigUint64(position, value);
1753
- } else {
1754
- // overflow
1755
- if (this.largeBigIntToFloat) {
1756
- target[position++] = 0xcb;
1757
- targetView.setFloat64(position, Number(value));
1758
- } else if (this.largeBigIntToString) {
1759
- return pack(value.toString());
1760
- } else if (this.useBigIntExtension || this.moreTypes) {
1761
- let empty = value < 0 ? BigInt(-1) : BigInt(0);
1762
-
1763
- let array;
1764
- if (value >> BigInt(0x10000) === empty) {
1765
- let mask = BigInt(0x10000000000000000) - BigInt(1); // literal would overflow
1766
- let chunks = [];
1767
- while (true) {
1768
- chunks.push(value & mask);
1769
- if ((value >> BigInt(63)) === empty) break
1770
- value >>= BigInt(64);
1771
- }
1772
-
1773
- array = new Uint8Array(new BigUint64Array(chunks).buffer);
1774
- array.reverse();
1775
- } else {
1776
- let invert = value < 0;
1777
- let string = (invert ? ~value : value).toString(16);
1778
- if (string.length % 2) {
1779
- string = '0' + string;
1780
- } else if (parseInt(string.charAt(0), 16) >= 8) {
1781
- string = '00' + string;
1782
- }
1783
-
1784
- if (hasNodeBuffer$1) {
1785
- array = Buffer.from(string, 'hex');
1786
- } else {
1787
- array = new Uint8Array(string.length / 2);
1788
- for (let i = 0; i < array.length; i++) {
1789
- array[i] = parseInt(string.slice(i * 2, i * 2 + 2), 16);
1790
- }
1791
- }
1792
-
1793
- if (invert) {
1794
- for (let i = 0; i < array.length; i++) array[i] = ~array[i];
1795
- }
1796
- }
1797
-
1798
- if (array.length + position > safeEnd)
1799
- makeRoom(array.length + position);
1800
- position = writeExtensionData(array, target, position, 0x42);
1801
- return
1802
- } else {
1803
- throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +
1804
- ' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +
1805
- ' largeBigIntToString to convert to string')
1806
- }
1807
- }
1808
- position += 8;
1809
- } else if (type === 'undefined') {
1810
- if (this.encodeUndefinedAsNil)
1811
- target[position++] = 0xc0;
1812
- else {
1813
- target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
1814
- target[position++] = 0;
1815
- target[position++] = 0;
1816
- }
1817
- } else {
1818
- throw new Error('Unknown type: ' + type)
1819
- }
1820
- };
1821
-
1822
- const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {
1823
- // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1824
- let keys;
1825
- if (this.skipValues) {
1826
- keys = [];
1827
- for (let key in object) {
1828
- if ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&
1829
- !this.skipValues.includes(object[key]))
1830
- keys.push(key);
1831
- }
1832
- } else {
1833
- keys = Object.keys(object);
1834
- }
1835
- let length = keys.length;
1836
- if (length < 0x10) {
1837
- target[position++] = 0x80 | length;
1838
- } else if (length < 0x10000) {
1839
- target[position++] = 0xde;
1840
- target[position++] = length >> 8;
1841
- target[position++] = length & 0xff;
1842
- } else {
1843
- target[position++] = 0xdf;
1844
- targetView.setUint32(position, length);
1845
- position += 4;
1846
- }
1847
- let key;
1848
- if (this.coercibleKeyAsNumber) {
1849
- for (let i = 0; i < length; i++) {
1850
- key = keys[i];
1851
- let num = Number(key);
1852
- pack(isNaN(num) ? key : num);
1853
- pack(object[key]);
1854
- }
1855
-
1856
- } else {
1857
- for (let i = 0; i < length; i++) {
1858
- pack(key = keys[i]);
1859
- pack(object[key]);
1860
- }
1861
- }
1862
- } :
1863
- (object) => {
1864
- target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
1865
- let objectOffset = position - start;
1866
- position += 2;
1867
- let size = 0;
1868
- for (let key in object) {
1869
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
1870
- pack(key);
1871
- pack(object[key]);
1872
- size++;
1873
- }
1874
- }
1875
- if (size > 0xffff) {
1876
- throw new Error('Object is too large to serialize with fast 16-bit map size,' +
1877
- ' use the "variableMapSize" option to serialize this object');
1878
- }
1879
- target[objectOffset++ + start] = size >> 8;
1880
- target[objectOffset + start] = size & 0xff;
1881
- };
1882
-
1883
- const writeRecord = this.useRecords === false ? writePlainObject :
1884
- (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)
1885
- (object) => {
1886
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1887
- let objectOffset = position++ - start;
1888
- let wroteKeys;
1889
- for (let key in object) {
1890
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
1891
- nextTransition = transition[key];
1892
- if (nextTransition)
1893
- transition = nextTransition;
1894
- else {
1895
- // record doesn't exist, create full new record and insert it
1896
- let keys = Object.keys(object);
1897
- let lastTransition = transition;
1898
- transition = structures.transitions;
1899
- let newTransitions = 0;
1900
- for (let i = 0, l = keys.length; i < l; i++) {
1901
- let key = keys[i];
1902
- nextTransition = transition[key];
1903
- if (!nextTransition) {
1904
- nextTransition = transition[key] = Object.create(null);
1905
- newTransitions++;
1906
- }
1907
- transition = nextTransition;
1908
- }
1909
- if (objectOffset + start + 1 == position) {
1910
- // first key, so we don't need to insert, we can just write record directly
1911
- position--;
1912
- newRecord(transition, keys, newTransitions);
1913
- } else // otherwise we need to insert the record, moving existing data after the record
1914
- insertNewRecord(transition, keys, objectOffset, newTransitions);
1915
- wroteKeys = true;
1916
- transition = lastTransition[key];
1917
- }
1918
- pack(object[key]);
1919
- }
1920
- }
1921
- if (!wroteKeys) {
1922
- let recordId = transition[RECORD_SYMBOL];
1923
- if (recordId)
1924
- target[objectOffset + start] = recordId;
1925
- else
1926
- insertNewRecord(transition, Object.keys(object), objectOffset, 0);
1927
- }
1928
- } :
1929
- (object) => {
1930
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1931
- let newTransitions = 0;
1932
- for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
1933
- nextTransition = transition[key];
1934
- if (!nextTransition) {
1935
- nextTransition = transition[key] = Object.create(null);
1936
- newTransitions++;
1937
- }
1938
- transition = nextTransition;
1939
- }
1940
- let recordId = transition[RECORD_SYMBOL];
1941
- if (recordId) {
1942
- if (recordId >= 0x60 && useTwoByteRecords) {
1943
- target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
1944
- target[position++] = recordId >> 5;
1945
- } else
1946
- target[position++] = recordId;
1947
- } else {
1948
- newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
1949
- }
1950
- // now write the values
1951
- for (let key in object)
1952
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
1953
- pack(object[key]);
1954
- }
1955
- };
1956
-
1957
- // create reference to useRecords if useRecords is a function
1958
- const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;
1959
-
1960
- const writeObject = checkUseRecords ? (object) => {
1961
- checkUseRecords(object) ? writeRecord(object) : writePlainObject(object);
1962
- } : writeRecord;
1963
-
1964
- const makeRoom = (end) => {
1965
- let newSize;
1966
- if (end > 0x1000000) {
1967
- // special handling for really large buffers
1968
- if ((end - start) > MAX_BUFFER_SIZE)
1969
- throw new Error('Packed buffer would be larger than maximum buffer size')
1970
- newSize = Math.min(MAX_BUFFER_SIZE,
1971
- Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1972
- } else // faster handling for smaller buffers
1973
- newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1974
- let newBuffer = new ByteArrayAllocate(newSize);
1975
- targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
1976
- end = Math.min(end, target.length);
1977
- if (target.copy)
1978
- target.copy(newBuffer, 0, start, end);
1979
- else
1980
- newBuffer.set(target.slice(start, end));
1981
- position -= start;
1982
- start = 0;
1983
- safeEnd = newBuffer.length - 10;
1984
- return target = newBuffer
1985
- };
1986
- const newRecord = (transition, keys, newTransitions) => {
1987
- let recordId = structures.nextId;
1988
- if (!recordId)
1989
- recordId = 0x40;
1990
- if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
1991
- recordId = structures.nextOwnId;
1992
- if (!(recordId < maxStructureId))
1993
- recordId = sharedLimitId;
1994
- structures.nextOwnId = recordId + 1;
1995
- } else {
1996
- if (recordId >= maxStructureId)// cycle back around
1997
- recordId = sharedLimitId;
1998
- structures.nextId = recordId + 1;
1999
- }
2000
- let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
2001
- transition[RECORD_SYMBOL] = recordId;
2002
- transition.__keys__ = keys;
2003
- structures[recordId - 0x40] = keys;
2004
-
2005
- if (recordId < sharedLimitId) {
2006
- keys.isShared = true;
2007
- structures.sharedLength = recordId - 0x3f;
2008
- hasSharedUpdate = true;
2009
- if (highByte >= 0) {
2010
- target[position++] = (recordId & 0x1f) + 0x60;
2011
- target[position++] = highByte;
2012
- } else {
2013
- target[position++] = recordId;
2014
- }
2015
- } else {
2016
- if (highByte >= 0) {
2017
- target[position++] = 0xd5; // fixext 2
2018
- target[position++] = 0x72; // "r" record defintion extension type
2019
- target[position++] = (recordId & 0x1f) + 0x60;
2020
- target[position++] = highByte;
2021
- } else {
2022
- target[position++] = 0xd4; // fixext 1
2023
- target[position++] = 0x72; // "r" record defintion extension type
2024
- target[position++] = recordId;
2025
- }
2026
-
2027
- if (newTransitions)
2028
- transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
2029
- // record the removal of the id, we can maintain our shared structure
2030
- if (recordIdsToRemove.length >= maxOwnStructures)
2031
- recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
2032
- recordIdsToRemove.push(transition);
2033
- pack(keys);
2034
- }
2035
- };
2036
- const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
2037
- let mainTarget = target;
2038
- let mainPosition = position;
2039
- let mainSafeEnd = safeEnd;
2040
- let mainStart = start;
2041
- target = keysTarget;
2042
- position = 0;
2043
- start = 0;
2044
- if (!target)
2045
- keysTarget = target = new ByteArrayAllocate(8192);
2046
- safeEnd = target.length - 10;
2047
- newRecord(transition, keys, newTransitions);
2048
- keysTarget = target;
2049
- let keysPosition = position;
2050
- target = mainTarget;
2051
- position = mainPosition;
2052
- safeEnd = mainSafeEnd;
2053
- start = mainStart;
2054
- if (keysPosition > 1) {
2055
- let newEnd = position + keysPosition - 1;
2056
- if (newEnd > safeEnd)
2057
- makeRoom(newEnd);
2058
- let insertionPosition = insertionOffset + start;
2059
- target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
2060
- target.set(keysTarget.slice(0, keysPosition), insertionPosition);
2061
- position = newEnd;
2062
- } else {
2063
- target[insertionOffset + start] = keysTarget[0];
2064
- }
2065
- };
2066
- const writeStruct = (object) => {
2067
- let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
2068
- if (notifySharedUpdate)
2069
- return hasSharedUpdate = true;
2070
- position = newPosition;
2071
- let startTarget = target;
2072
- pack(value);
2073
- resetStructures();
2074
- if (startTarget !== target) {
2075
- return { position, targetView, target }; // indicate the buffer was re-allocated
2076
- }
2077
- return position;
2078
- }, this);
2079
- if (newPosition === 0) // bail and go to a msgpack object
2080
- return writeObject(object);
2081
- position = newPosition;
2082
- };
2083
- }
2084
- useBuffer(buffer) {
2085
- // this means we are finished using our own buffer and we can write over it safely
2086
- target = buffer;
2087
- target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength));
2088
- targetView = target.dataView;
2089
- position = 0;
2090
- }
2091
- set position (value) {
2092
- position = value;
2093
- }
2094
- get position() {
2095
- return position;
2096
- }
2097
- clearSharedData() {
2098
- if (this.structures)
2099
- this.structures = [];
2100
- if (this.typedStructs)
2101
- this.typedStructs = [];
2102
- }
2103
- };
2104
-
2105
- extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, DataView, C1Type ];
2106
- extensions = [{
2107
- pack(date, allocateForWrite, pack) {
2108
- let seconds = date.getTime() / 1000;
2109
- if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
2110
- // Timestamp 32
2111
- let { target, targetView, position} = allocateForWrite(6);
2112
- target[position++] = 0xd6;
2113
- target[position++] = 0xff;
2114
- targetView.setUint32(position, seconds);
2115
- } else if (seconds > 0 && seconds < 0x100000000) {
2116
- // Timestamp 64
2117
- let { target, targetView, position} = allocateForWrite(10);
2118
- target[position++] = 0xd7;
2119
- target[position++] = 0xff;
2120
- targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
2121
- targetView.setUint32(position + 4, seconds);
2122
- } else if (isNaN(seconds)) {
2123
- if (this.onInvalidDate) {
2124
- allocateForWrite(0);
2125
- return pack(this.onInvalidDate())
2126
- }
2127
- // Intentionally invalid timestamp
2128
- let { target, targetView, position} = allocateForWrite(3);
2129
- target[position++] = 0xd4;
2130
- target[position++] = 0xff;
2131
- target[position++] = 0xff;
2132
- } else {
2133
- // Timestamp 96
2134
- let { target, targetView, position} = allocateForWrite(15);
2135
- target[position++] = 0xc7;
2136
- target[position++] = 12;
2137
- target[position++] = 0xff;
2138
- targetView.setUint32(position, date.getMilliseconds() * 1000000);
2139
- targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
2140
- }
2141
- }
2142
- }, {
2143
- pack(set, allocateForWrite, pack) {
2144
- if (this.setAsEmptyObject) {
2145
- allocateForWrite(0);
2146
- return pack({})
2147
- }
2148
- let array = Array.from(set);
2149
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
2150
- if (this.moreTypes) {
2151
- target[position++] = 0xd4;
2152
- target[position++] = 0x73; // 's' for Set
2153
- target[position++] = 0;
2154
- }
2155
- pack(array);
2156
- }
2157
- }, {
2158
- pack(error, allocateForWrite, pack) {
2159
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
2160
- if (this.moreTypes) {
2161
- target[position++] = 0xd4;
2162
- target[position++] = 0x65; // 'e' for error
2163
- target[position++] = 0;
2164
- }
2165
- pack([ error.name, error.message, error.cause ]);
2166
- }
2167
- }, {
2168
- pack(regex, allocateForWrite, pack) {
2169
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
2170
- if (this.moreTypes) {
2171
- target[position++] = 0xd4;
2172
- target[position++] = 0x78; // 'x' for regeXp
2173
- target[position++] = 0;
2174
- }
2175
- pack([ regex.source, regex.flags ]);
2176
- }
2177
- }, {
2178
- pack(arrayBuffer, allocateForWrite) {
2179
- if (this.moreTypes)
2180
- writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
2181
- else
2182
- writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
2183
- }
2184
- }, {
2185
- pack(typedArray, allocateForWrite) {
2186
- let constructor = typedArray.constructor;
2187
- if (constructor !== ByteArray && this.moreTypes)
2188
- writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
2189
- else
2190
- writeBuffer(typedArray, allocateForWrite);
2191
- }
2192
- }, {
2193
- pack(arrayBuffer, allocateForWrite) {
2194
- if (this.moreTypes)
2195
- writeExtBuffer(arrayBuffer, 0x11, allocateForWrite);
2196
- else
2197
- writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
2198
- }
2199
- }, {
2200
- pack(c1, allocateForWrite) { // specific 0xC1 object
2201
- let { target, position} = allocateForWrite(1);
2202
- target[position] = 0xc1;
2203
- }
2204
- }];
2205
-
2206
- function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
2207
- let length = typedArray.byteLength;
2208
- if (length + 1 < 0x100) {
2209
- var { target, position } = allocateForWrite(4 + length);
2210
- target[position++] = 0xc7;
2211
- target[position++] = length + 1;
2212
- } else if (length + 1 < 0x10000) {
2213
- var { target, position } = allocateForWrite(5 + length);
2214
- target[position++] = 0xc8;
2215
- target[position++] = (length + 1) >> 8;
2216
- target[position++] = (length + 1) & 0xff;
2217
- } else {
2218
- var { target, position, targetView } = allocateForWrite(7 + length);
2219
- target[position++] = 0xc9;
2220
- targetView.setUint32(position, length + 1); // plus one for the type byte
2221
- position += 4;
2222
- }
2223
- target[position++] = 0x74; // "t" for typed array
2224
- target[position++] = type;
2225
- if (!typedArray.buffer) typedArray = new Uint8Array(typedArray);
2226
- target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
2227
- }
2228
- function writeBuffer(buffer, allocateForWrite) {
2229
- let length = buffer.byteLength;
2230
- var target, position;
2231
- if (length < 0x100) {
2232
- var { target, position } = allocateForWrite(length + 2);
2233
- target[position++] = 0xc4;
2234
- target[position++] = length;
2235
- } else if (length < 0x10000) {
2236
- var { target, position } = allocateForWrite(length + 3);
2237
- target[position++] = 0xc5;
2238
- target[position++] = length >> 8;
2239
- target[position++] = length & 0xff;
2240
- } else {
2241
- var { target, position, targetView } = allocateForWrite(length + 5);
2242
- target[position++] = 0xc6;
2243
- targetView.setUint32(position, length);
2244
- position += 4;
2245
- }
2246
- target.set(buffer, position);
2247
- }
2248
-
2249
- function writeExtensionData(result, target, position, type) {
2250
- let length = result.length;
2251
- switch (length) {
2252
- case 1:
2253
- target[position++] = 0xd4;
2254
- break
2255
- case 2:
2256
- target[position++] = 0xd5;
2257
- break
2258
- case 4:
2259
- target[position++] = 0xd6;
2260
- break
2261
- case 8:
2262
- target[position++] = 0xd7;
2263
- break
2264
- case 16:
2265
- target[position++] = 0xd8;
2266
- break
2267
- default:
2268
- if (length < 0x100) {
2269
- target[position++] = 0xc7;
2270
- target[position++] = length;
2271
- } else if (length < 0x10000) {
2272
- target[position++] = 0xc8;
2273
- target[position++] = length >> 8;
2274
- target[position++] = length & 0xff;
2275
- } else {
2276
- target[position++] = 0xc9;
2277
- target[position++] = length >> 24;
2278
- target[position++] = (length >> 16) & 0xff;
2279
- target[position++] = (length >> 8) & 0xff;
2280
- target[position++] = length & 0xff;
2281
- }
2282
- }
2283
- target[position++] = type;
2284
- target.set(result, position);
2285
- position += length;
2286
- return position
2287
- }
2288
-
2289
- function insertIds(serialized, idsToInsert) {
2290
- // insert the ids that need to be referenced for structured clones
2291
- let nextId;
2292
- let distanceToMove = idsToInsert.length * 6;
2293
- let lastEnd = serialized.length - distanceToMove;
2294
- while (nextId = idsToInsert.pop()) {
2295
- let offset = nextId.offset;
2296
- let id = nextId.id;
2297
- serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
2298
- distanceToMove -= 6;
2299
- let position = offset + distanceToMove;
2300
- serialized[position++] = 0xd6;
2301
- serialized[position++] = 0x69; // 'i'
2302
- serialized[position++] = id >> 24;
2303
- serialized[position++] = (id >> 16) & 0xff;
2304
- serialized[position++] = (id >> 8) & 0xff;
2305
- serialized[position++] = id & 0xff;
2306
- lastEnd = offset;
2307
- }
2308
- return serialized
2309
- }
2310
-
2311
- function writeBundles(start, pack, incrementPosition) {
2312
- if (bundledStrings.length > 0) {
2313
- targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
2314
- bundledStrings.stringsPosition = position - start;
2315
- let writeStrings = bundledStrings;
2316
- bundledStrings = null;
2317
- pack(writeStrings[0]);
2318
- pack(writeStrings[1]);
2319
- }
2320
- }
2321
-
2322
- function addExtension$1(extension) {
2323
- if (extension.Class) {
2324
- if (!extension.pack && !extension.write)
2325
- throw new Error('Extension has no pack or write function')
2326
- if (extension.pack && !extension.type)
2327
- throw new Error('Extension has no type (numeric code to identify the extension)')
2328
- extensionClasses.unshift(extension.Class);
2329
- extensions.unshift(extension);
2330
- }
2331
- addExtension$2(extension);
2332
- }
2333
- function prepareStructures$1(structures, packr) {
2334
- structures.isCompatible = (existingStructures) => {
2335
- let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
2336
- if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
2337
- packr._mergeStructures(existingStructures);
2338
- return compatible;
2339
- };
2340
- return structures
2341
- }
2342
- function setWriteStructSlots(writeSlots, makeStructures) {
2343
- writeStructSlots = writeSlots;
2344
- prepareStructures$1 = makeStructures;
2345
- }
2346
-
2347
- let defaultPackr = new Packr$1({ useRecords: false });
2348
- const pack$1 = defaultPackr.pack;
2349
- defaultPackr.pack;
2350
- const REUSE_BUFFER_MODE = 512;
2351
- const RESET_BUFFER_MODE = 1024;
2352
- const RESERVE_START_SPACE = 2048;
2353
-
2354
- const ASCII = 3; // the MIBenum from https://www.iana.org/assignments/character-sets/character-sets.xhtml (and other character encodings could be referenced by MIBenum)
2355
- const NUMBER = 0;
2356
- const UTF8 = 2;
2357
- const OBJECT_DATA = 1;
2358
- const DATE = 16;
2359
- const TYPE_NAMES = ['num', 'object', 'string', 'ascii'];
2360
- TYPE_NAMES[DATE] = 'date';
2361
- const float32Headers = [false, true, true, false, false, true, true, false];
2362
- let evalSupported;
2363
- try {
2364
- new Function('');
2365
- evalSupported = true;
2366
- } catch(error) {
2367
- // if eval variants are not supported, do not create inline object readers ever
2368
- }
2369
-
2370
- let updatedPosition;
2371
- const hasNodeBuffer = typeof Buffer !== 'undefined';
2372
- let textEncoder, currentSource;
2373
- try {
2374
- textEncoder = new TextEncoder();
2375
- } catch (error) {}
2376
- const encodeUtf8 = hasNodeBuffer ? function(target, string, position) {
2377
- return target.utf8Write(string, position, target.byteLength - position)
2378
- } : (textEncoder && textEncoder.encodeInto) ?
2379
- function(target, string, position) {
2380
- return textEncoder.encodeInto(string, target.subarray(position)).written
2381
- } : false;
2382
- setWriteStructSlots(writeStruct, prepareStructures);
2383
- function writeStruct(object, target, encodingStart, position, structures, makeRoom, pack, packr) {
2384
- let typedStructs = packr.typedStructs || (packr.typedStructs = []);
2385
- // note that we rely on pack.js to load stored structures before we get to this point
2386
- let targetView = target.dataView;
2387
- let refsStartPosition = (typedStructs.lastStringStart || 100) + position;
2388
- let safeEnd = target.length - 10;
2389
- let start = position;
2390
- if (position > safeEnd) {
2391
- target = makeRoom(position);
2392
- targetView = target.dataView;
2393
- position -= encodingStart;
2394
- start -= encodingStart;
2395
- refsStartPosition -= encodingStart;
2396
- encodingStart = 0;
2397
- safeEnd = target.length - 10;
2398
- }
2399
-
2400
- let refOffset, refPosition = refsStartPosition;
2401
-
2402
- let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null));
2403
- let nextId = typedStructs.nextId || typedStructs.length;
2404
- let headerSize =
2405
- nextId < 0xf ? 1 :
2406
- nextId < 0xf0 ? 2 :
2407
- nextId < 0xf000 ? 3 :
2408
- nextId < 0xf00000 ? 4 : 0;
2409
- if (headerSize === 0)
2410
- return 0;
2411
- position += headerSize;
2412
- let queuedReferences = [];
2413
- let usedAscii0;
2414
- let keyIndex = 0;
2415
- for (let key in object) {
2416
- let value = object[key];
2417
- let nextTransition = transition[key];
2418
- if (!nextTransition) {
2419
- transition[key] = nextTransition = {
2420
- key,
2421
- parent: transition,
2422
- enumerationOffset: 0,
2423
- ascii0: null,
2424
- ascii8: null,
2425
- num8: null,
2426
- string16: null,
2427
- object16: null,
2428
- num32: null,
2429
- float64: null,
2430
- date64: null
2431
- };
2432
- }
2433
- if (position > safeEnd) {
2434
- target = makeRoom(position);
2435
- targetView = target.dataView;
2436
- position -= encodingStart;
2437
- start -= encodingStart;
2438
- refsStartPosition -= encodingStart;
2439
- refPosition -= encodingStart;
2440
- encodingStart = 0;
2441
- safeEnd = target.length - 10;
2442
- }
2443
- switch (typeof value) {
2444
- case 'number':
2445
- let number = value;
2446
- // first check to see if we are using a lot of ids and should default to wide/common format
2447
- if (nextId < 200 || !nextTransition.num64) {
2448
- if (number >> 0 === number && number < 0x20000000 && number > -0x1f000000) {
2449
- if (number < 0xf6 && number >= 0 && (nextTransition.num8 && !(nextId > 200 && nextTransition.num32) || number < 0x20 && !nextTransition.num32)) {
2450
- transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1);
2451
- target[position++] = number;
2452
- } else {
2453
- transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
2454
- targetView.setUint32(position, number, true);
2455
- position += 4;
2456
- }
2457
- break;
2458
- } else if (number < 0x100000000 && number >= -0x80000000) {
2459
- targetView.setFloat32(position, number, true);
2460
- if (float32Headers[target[position + 3] >>> 5]) {
2461
- let xShifted;
2462
- // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
2463
- if (((xShifted = number * mult10[((target[position + 3] & 0x7f) << 1) | (target[position + 2] >> 7)]) >> 0) === xShifted) {
2464
- transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
2465
- position += 4;
2466
- break;
2467
- }
2468
- }
2469
- }
2470
- }
2471
- transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8);
2472
- targetView.setFloat64(position, number, true);
2473
- position += 8;
2474
- break;
2475
- case 'string':
2476
- let strLength = value.length;
2477
- refOffset = refPosition - refsStartPosition;
2478
- if ((strLength << 2) + refPosition > safeEnd) {
2479
- target = makeRoom((strLength << 2) + refPosition);
2480
- targetView = target.dataView;
2481
- position -= encodingStart;
2482
- start -= encodingStart;
2483
- refsStartPosition -= encodingStart;
2484
- refPosition -= encodingStart;
2485
- encodingStart = 0;
2486
- safeEnd = target.length - 10;
2487
- }
2488
- if (strLength > ((0xff00 + refOffset) >> 2)) {
2489
- queuedReferences.push(key, value, position - start);
2490
- break;
2491
- }
2492
- let isNotAscii;
2493
- let strStart = refPosition;
2494
- if (strLength < 0x40) {
2495
- let i, c1, c2;
2496
- for (i = 0; i < strLength; i++) {
2497
- c1 = value.charCodeAt(i);
2498
- if (c1 < 0x80) {
2499
- target[refPosition++] = c1;
2500
- } else if (c1 < 0x800) {
2501
- isNotAscii = true;
2502
- target[refPosition++] = c1 >> 6 | 0xc0;
2503
- target[refPosition++] = c1 & 0x3f | 0x80;
2504
- } else if (
2505
- (c1 & 0xfc00) === 0xd800 &&
2506
- ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
2507
- ) {
2508
- isNotAscii = true;
2509
- c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
2510
- i++;
2511
- target[refPosition++] = c1 >> 18 | 0xf0;
2512
- target[refPosition++] = c1 >> 12 & 0x3f | 0x80;
2513
- target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
2514
- target[refPosition++] = c1 & 0x3f | 0x80;
2515
- } else {
2516
- isNotAscii = true;
2517
- target[refPosition++] = c1 >> 12 | 0xe0;
2518
- target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
2519
- target[refPosition++] = c1 & 0x3f | 0x80;
2520
- }
2521
- }
2522
- } else {
2523
- refPosition += encodeUtf8(target, value, refPosition);
2524
- isNotAscii = refPosition - strStart > strLength;
2525
- }
2526
- if (refOffset < 0xa0 || (refOffset < 0xf6 && (nextTransition.ascii8 || nextTransition.string8))) {
2527
- // short strings
2528
- if (isNotAscii) {
2529
- if (!(transition = nextTransition.string8)) {
2530
- if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) {
2531
- // we can safely change ascii to utf8 in place since they are compatible
2532
- transition.__type = UTF8;
2533
- nextTransition.ascii8 = null;
2534
- nextTransition.string8 = transition;
2535
- pack(null, 0, true); // special call to notify that structures have been updated
2536
- } else {
2537
- transition = createTypeTransition(nextTransition, UTF8, 1);
2538
- }
2539
- }
2540
- } else if (refOffset === 0 && !usedAscii0) {
2541
- usedAscii0 = true;
2542
- transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0);
2543
- break; // don't increment position
2544
- }// else ascii:
2545
- else if (!(transition = nextTransition.ascii8) && !(typedStructs.length > 10 && (transition = nextTransition.string8)))
2546
- transition = createTypeTransition(nextTransition, ASCII, 1);
2547
- target[position++] = refOffset;
2548
- } else {
2549
- // TODO: Enable ascii16 at some point, but get the logic right
2550
- //if (isNotAscii)
2551
- transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2);
2552
- //else
2553
- //transition = nextTransition.ascii16 || createTypeTransition(nextTransition, ASCII, 2);
2554
- targetView.setUint16(position, refOffset, true);
2555
- position += 2;
2556
- }
2557
- break;
2558
- case 'object':
2559
- if (value) {
2560
- if (value.constructor === Date) {
2561
- transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8);
2562
- targetView.setFloat64(position, value.getTime(), true);
2563
- position += 8;
2564
- } else {
2565
- queuedReferences.push(key, value, keyIndex);
2566
- }
2567
- break;
2568
- } else { // null
2569
- nextTransition = anyType(nextTransition, position, targetView, -10); // match CBOR with this
2570
- if (nextTransition) {
2571
- transition = nextTransition;
2572
- position = updatedPosition;
2573
- } else queuedReferences.push(key, value, keyIndex);
2574
- }
2575
- break;
2576
- case 'boolean':
2577
- transition = nextTransition.num8 || nextTransition.ascii8 || createTypeTransition(nextTransition, NUMBER, 1);
2578
- target[position++] = value ? 0xf9 : 0xf8; // match CBOR with these
2579
- break;
2580
- case 'undefined':
2581
- nextTransition = anyType(nextTransition, position, targetView, -9); // match CBOR with this
2582
- if (nextTransition) {
2583
- transition = nextTransition;
2584
- position = updatedPosition;
2585
- } else queuedReferences.push(key, value, keyIndex);
2586
- break;
2587
- default:
2588
- queuedReferences.push(key, value, keyIndex);
2589
- }
2590
- keyIndex++;
2591
- }
2592
-
2593
- for (let i = 0, l = queuedReferences.length; i < l;) {
2594
- let key = queuedReferences[i++];
2595
- let value = queuedReferences[i++];
2596
- let propertyIndex = queuedReferences[i++];
2597
- let nextTransition = transition[key];
2598
- if (!nextTransition) {
2599
- transition[key] = nextTransition = {
2600
- key,
2601
- parent: transition,
2602
- enumerationOffset: propertyIndex - keyIndex,
2603
- ascii0: null,
2604
- ascii8: null,
2605
- num8: null,
2606
- string16: null,
2607
- object16: null,
2608
- num32: null,
2609
- float64: null
2610
- };
2611
- }
2612
- let newPosition;
2613
- if (value) {
2614
- /*if (typeof value === 'string') { // TODO: we could re-enable long strings
2615
- if (position + value.length * 3 > safeEnd) {
2616
- target = makeRoom(position + value.length * 3);
2617
- position -= start;
2618
- targetView = target.dataView;
2619
- start = 0;
2620
- }
2621
- newPosition = position + target.utf8Write(value, position, 0xffffffff);
2622
- } else { */
2623
- let size;
2624
- refOffset = refPosition - refsStartPosition;
2625
- if (refOffset < 0xff00) {
2626
- transition = nextTransition.object16;
2627
- if (transition)
2628
- size = 2;
2629
- else if ((transition = nextTransition.object32))
2630
- size = 4;
2631
- else {
2632
- transition = createTypeTransition(nextTransition, OBJECT_DATA, 2);
2633
- size = 2;
2634
- }
2635
- } else {
2636
- transition = nextTransition.object32 || createTypeTransition(nextTransition, OBJECT_DATA, 4);
2637
- size = 4;
2638
- }
2639
- newPosition = pack(value, refPosition);
2640
- //}
2641
- if (typeof newPosition === 'object') {
2642
- // re-allocated
2643
- refPosition = newPosition.position;
2644
- targetView = newPosition.targetView;
2645
- target = newPosition.target;
2646
- refsStartPosition -= encodingStart;
2647
- position -= encodingStart;
2648
- start -= encodingStart;
2649
- encodingStart = 0;
2650
- } else
2651
- refPosition = newPosition;
2652
- if (size === 2) {
2653
- targetView.setUint16(position, refOffset, true);
2654
- position += 2;
2655
- } else {
2656
- targetView.setUint32(position, refOffset, true);
2657
- position += 4;
2658
- }
2659
- } else { // null or undefined
2660
- transition = nextTransition.object16 || createTypeTransition(nextTransition, OBJECT_DATA, 2);
2661
- targetView.setInt16(position, value === null ? -10 : -9, true);
2662
- position += 2;
2663
- }
2664
- keyIndex++;
2665
- }
2666
-
2667
-
2668
- let recordId = transition[RECORD_SYMBOL];
2669
- if (recordId == null) {
2670
- recordId = packr.typedStructs.length;
2671
- let structure = [];
2672
- let nextTransition = transition;
2673
- let key, type;
2674
- while ((type = nextTransition.__type) !== undefined) {
2675
- let size = nextTransition.__size;
2676
- nextTransition = nextTransition.__parent;
2677
- key = nextTransition.key;
2678
- let property = [type, size, key];
2679
- if (nextTransition.enumerationOffset)
2680
- property.push(nextTransition.enumerationOffset);
2681
- structure.push(property);
2682
- nextTransition = nextTransition.parent;
2683
- }
2684
- structure.reverse();
2685
- transition[RECORD_SYMBOL] = recordId;
2686
- packr.typedStructs[recordId] = structure;
2687
- pack(null, 0, true); // special call to notify that structures have been updated
2688
- }
2689
-
2690
-
2691
- switch (headerSize) {
2692
- case 1:
2693
- if (recordId >= 0x10) return 0;
2694
- target[start] = recordId + 0x20;
2695
- break;
2696
- case 2:
2697
- if (recordId >= 0x100) return 0;
2698
- target[start] = 0x38;
2699
- target[start + 1] = recordId;
2700
- break;
2701
- case 3:
2702
- if (recordId >= 0x10000) return 0;
2703
- target[start] = 0x39;
2704
- targetView.setUint16(start + 1, recordId, true);
2705
- break;
2706
- case 4:
2707
- if (recordId >= 0x1000000) return 0;
2708
- targetView.setUint32(start, (recordId << 8) + 0x3a, true);
2709
- break;
2710
- }
2711
-
2712
- if (position < refsStartPosition) {
2713
- if (refsStartPosition === refPosition)
2714
- return position; // no refs
2715
- // adjust positioning
2716
- target.copyWithin(position, refsStartPosition, refPosition);
2717
- refPosition += position - refsStartPosition;
2718
- typedStructs.lastStringStart = position - start;
2719
- } else if (position > refsStartPosition) {
2720
- if (refsStartPosition === refPosition)
2721
- return position; // no refs
2722
- typedStructs.lastStringStart = position - start;
2723
- return writeStruct(object, target, encodingStart, start, structures, makeRoom, pack, packr);
2724
- }
2725
- return refPosition;
2726
- }
2727
- function anyType(transition, position, targetView, value) {
2728
- let nextTransition;
2729
- if ((nextTransition = transition.ascii8 || transition.num8)) {
2730
- targetView.setInt8(position, value, true);
2731
- updatedPosition = position + 1;
2732
- return nextTransition;
2733
- }
2734
- if ((nextTransition = transition.string16 || transition.object16)) {
2735
- targetView.setInt16(position, value, true);
2736
- updatedPosition = position + 2;
2737
- return nextTransition;
2738
- }
2739
- if (nextTransition = transition.num32) {
2740
- targetView.setUint32(position, 0xe0000100 + value, true);
2741
- updatedPosition = position + 4;
2742
- return nextTransition;
2743
- }
2744
- // transition.float64
2745
- if (nextTransition = transition.num64) {
2746
- targetView.setFloat64(position, NaN, true);
2747
- targetView.setInt8(position, value);
2748
- updatedPosition = position + 8;
2749
- return nextTransition;
2750
- }
2751
- updatedPosition = position;
2752
- // TODO: can we do an "any" type where we defer the decision?
2753
- return;
2754
- }
2755
- function createTypeTransition(transition, type, size) {
2756
- let typeName = TYPE_NAMES[type] + (size << 3);
2757
- let newTransition = transition[typeName] || (transition[typeName] = Object.create(null));
2758
- newTransition.__type = type;
2759
- newTransition.__size = size;
2760
- newTransition.__parent = transition;
2761
- return newTransition;
2762
- }
2763
- function onLoadedStructures(sharedData) {
2764
- if (!(sharedData instanceof Map))
2765
- return sharedData;
2766
- let typed = sharedData.get('typed') || [];
2767
- if (Object.isFrozen(typed))
2768
- typed = typed.map(structure => structure.slice(0));
2769
- let named = sharedData.get('named');
2770
- let transitions = Object.create(null);
2771
- for (let i = 0, l = typed.length; i < l; i++) {
2772
- let structure = typed[i];
2773
- let transition = transitions;
2774
- for (let [type, size, key] of structure) {
2775
- let nextTransition = transition[key];
2776
- if (!nextTransition) {
2777
- transition[key] = nextTransition = {
2778
- key,
2779
- parent: transition,
2780
- enumerationOffset: 0,
2781
- ascii0: null,
2782
- ascii8: null,
2783
- num8: null,
2784
- string16: null,
2785
- object16: null,
2786
- num32: null,
2787
- float64: null,
2788
- date64: null,
2789
- };
2790
- }
2791
- transition = createTypeTransition(nextTransition, type, size);
2792
- }
2793
- transition[RECORD_SYMBOL] = i;
2794
- }
2795
- typed.transitions = transitions;
2796
- this.typedStructs = typed;
2797
- this.lastTypedStructuresLength = typed.length;
2798
- return named;
2799
- }
2800
- var sourceSymbol = Symbol.for('source');
2801
- function readStruct(src, position, srcEnd, unpackr) {
2802
- let recordId = src[position++] - 0x20;
2803
- if (recordId >= 24) {
2804
- switch(recordId) {
2805
- case 24: recordId = src[position++]; break;
2806
- // little endian:
2807
- case 25: recordId = src[position++] + (src[position++] << 8); break;
2808
- case 26: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16); break;
2809
- case 27: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16) + (src[position++] << 24); break;
2810
- }
2811
- }
2812
- let structure = unpackr.typedStructs && unpackr.typedStructs[recordId];
2813
- if (!structure) {
2814
- // copy src buffer because getStructures will override it
2815
- src = Uint8Array.prototype.slice.call(src, position, srcEnd);
2816
- srcEnd -= position;
2817
- position = 0;
2818
- if (!unpackr.getStructures)
2819
- throw new Error(`Reference to shared structure ${recordId} without getStructures method`);
2820
- unpackr._mergeStructures(unpackr.getStructures());
2821
- if (!unpackr.typedStructs)
2822
- throw new Error('Could not find any shared typed structures');
2823
- unpackr.lastTypedStructuresLength = unpackr.typedStructs.length;
2824
- structure = unpackr.typedStructs[recordId];
2825
- if (!structure)
2826
- throw new Error('Could not find typed structure ' + recordId);
2827
- }
2828
- var construct = structure.construct;
2829
- var fullConstruct = structure.fullConstruct;
2830
- if (!construct) {
2831
- construct = structure.construct = function LazyObject() {
2832
- };
2833
- fullConstruct = structure.fullConstruct = function LoadedObject() {
2834
- };
2835
- fullConstruct.prototype = unpackr.structPrototype || {};
2836
- var prototype = construct.prototype = unpackr.structPrototype ? Object.create(unpackr.structPrototype) : {};
2837
- let properties = [];
2838
- let currentOffset = 0;
2839
- let lastRefProperty;
2840
- for (let i = 0, l = structure.length; i < l; i++) {
2841
- let definition = structure[i];
2842
- let [ type, size, key, enumerationOffset ] = definition;
2843
- if (key === '__proto__')
2844
- key = '__proto_';
2845
- let property = {
2846
- key,
2847
- offset: currentOffset,
2848
- };
2849
- if (enumerationOffset)
2850
- properties.splice(i + enumerationOffset, 0, property);
2851
- else
2852
- properties.push(property);
2853
- let getRef;
2854
- switch(size) { // TODO: Move into a separate function
2855
- case 0: getRef = () => 0; break;
2856
- case 1:
2857
- getRef = (source, position) => {
2858
- let ref = source.bytes[position + property.offset];
2859
- return ref >= 0xf6 ? toConstant(ref) : ref;
2860
- };
2861
- break;
2862
- case 2:
2863
- getRef = (source, position) => {
2864
- let src = source.bytes;
2865
- let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
2866
- let ref = dataView.getUint16(position + property.offset, true);
2867
- return ref >= 0xff00 ? toConstant(ref & 0xff) : ref;
2868
- };
2869
- break;
2870
- case 4:
2871
- getRef = (source, position) => {
2872
- let src = source.bytes;
2873
- let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
2874
- let ref = dataView.getUint32(position + property.offset, true);
2875
- return ref >= 0xffffff00 ? toConstant(ref & 0xff) : ref;
2876
- };
2877
- break;
2878
- }
2879
- property.getRef = getRef;
2880
- currentOffset += size;
2881
- let get;
2882
- switch(type) {
2883
- case ASCII:
2884
- if (lastRefProperty && !lastRefProperty.next)
2885
- lastRefProperty.next = property;
2886
- lastRefProperty = property;
2887
- property.multiGetCount = 0;
2888
- get = function(source) {
2889
- let src = source.bytes;
2890
- let position = source.position;
2891
- let refStart = currentOffset + position;
2892
- let ref = getRef(source, position);
2893
- if (typeof ref !== 'number') return ref;
2894
-
2895
- let end, next = property.next;
2896
- while(next) {
2897
- end = next.getRef(source, position);
2898
- if (typeof end === 'number')
2899
- break;
2900
- else
2901
- end = null;
2902
- next = next.next;
2903
- }
2904
- if (end == null)
2905
- end = source.bytesEnd - refStart;
2906
- if (source.srcString) {
2907
- return source.srcString.slice(ref, end);
2908
- }
2909
- /*if (property.multiGetCount > 0) {
2910
- let asciiEnd;
2911
- next = firstRefProperty;
2912
- let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
2913
- do {
2914
- asciiEnd = dataView.getUint16(source.position + next.offset, true);
2915
- if (asciiEnd < 0xff00)
2916
- break;
2917
- else
2918
- asciiEnd = null;
2919
- } while((next = next.next));
2920
- if (asciiEnd == null)
2921
- asciiEnd = source.bytesEnd - refStart
2922
- source.srcString = src.toString('latin1', refStart, refStart + asciiEnd);
2923
- return source.srcString.slice(ref, end);
2924
- }
2925
- if (source.prevStringGet) {
2926
- source.prevStringGet.multiGetCount += 2;
2927
- } else {
2928
- source.prevStringGet = property;
2929
- property.multiGetCount--;
2930
- }*/
2931
- return readString(src, ref + refStart, end - ref);
2932
- //return src.toString('latin1', ref + refStart, end + refStart);
2933
- };
2934
- break;
2935
- case UTF8: case OBJECT_DATA:
2936
- if (lastRefProperty && !lastRefProperty.next)
2937
- lastRefProperty.next = property;
2938
- lastRefProperty = property;
2939
- get = function(source) {
2940
- let position = source.position;
2941
- let refStart = currentOffset + position;
2942
- let ref = getRef(source, position);
2943
- if (typeof ref !== 'number') return ref;
2944
- let src = source.bytes;
2945
- let end, next = property.next;
2946
- while(next) {
2947
- end = next.getRef(source, position);
2948
- if (typeof end === 'number')
2949
- break;
2950
- else
2951
- end = null;
2952
- next = next.next;
2953
- }
2954
- if (end == null)
2955
- end = source.bytesEnd - refStart;
2956
- if (type === UTF8) {
2957
- return src.toString('utf8', ref + refStart, end + refStart);
2958
- } else {
2959
- currentSource = source;
2960
- try {
2961
- return unpackr.unpack(src, { start: ref + refStart, end: end + refStart });
2962
- } finally {
2963
- currentSource = null;
2964
- }
2965
- }
2966
- };
2967
- break;
2968
- case NUMBER:
2969
- switch(size) {
2970
- case 4:
2971
- get = function (source) {
2972
- let src = source.bytes;
2973
- let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
2974
- let position = source.position + property.offset;
2975
- let value = dataView.getInt32(position, true);
2976
- if (value < 0x20000000) {
2977
- if (value > -0x1f000000)
2978
- return value;
2979
- if (value > -0x20000000)
2980
- return toConstant(value & 0xff);
2981
- }
2982
- let fValue = dataView.getFloat32(position, true);
2983
- // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
2984
- let multiplier = mult10[((src[position + 3] & 0x7f) << 1) | (src[position + 2] >> 7)];
2985
- return ((multiplier * fValue + (fValue > 0 ? 0.5 : -0.5)) >> 0) / multiplier;
2986
- };
2987
- break;
2988
- case 8:
2989
- get = function (source) {
2990
- let src = source.bytes;
2991
- let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
2992
- let value = dataView.getFloat64(source.position + property.offset, true);
2993
- if (isNaN(value)) {
2994
- let byte = src[source.position + property.offset];
2995
- if (byte >= 0xf6)
2996
- return toConstant(byte);
2997
- }
2998
- return value;
2999
- };
3000
- break;
3001
- case 1:
3002
- get = function (source) {
3003
- let src = source.bytes;
3004
- let value = src[source.position + property.offset];
3005
- return value < 0xf6 ? value : toConstant(value);
3006
- };
3007
- break;
3008
- }
3009
- break;
3010
- case DATE:
3011
- get = function (source) {
3012
- let src = source.bytes;
3013
- let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
3014
- return new Date(dataView.getFloat64(source.position + property.offset, true));
3015
- };
3016
- break;
3017
-
3018
- }
3019
- property.get = get;
3020
- }
3021
- // TODO: load the srcString for faster string decoding on toJSON
3022
- if (evalSupported) {
3023
- let objectLiteralProperties = [];
3024
- let args = [];
3025
- let i = 0;
3026
- let hasInheritedProperties;
3027
- for (let property of properties) { // assign in enumeration order
3028
- if (unpackr.alwaysLazyProperty && unpackr.alwaysLazyProperty(property.key)) {
3029
- // these properties are not eagerly evaluated and this can be used for creating properties
3030
- // that are not serialized as JSON
3031
- hasInheritedProperties = true;
3032
- continue;
3033
- }
3034
- Object.defineProperty(prototype, property.key, { get: withSource(property.get), enumerable: true });
3035
- let valueFunction = 'v' + i++;
3036
- args.push(valueFunction);
3037
- objectLiteralProperties.push('o[' + JSON.stringify(property.key) + ']=' + valueFunction + '(s)');
3038
- }
3039
- if (hasInheritedProperties) {
3040
- objectLiteralProperties.push('__proto__:this');
3041
- }
3042
- let toObject = (new Function(...args, 'var c=this;return function(s){var o=new c();' + objectLiteralProperties.join(';') + ';return o;}')).apply(fullConstruct, properties.map(prop => prop.get));
3043
- Object.defineProperty(prototype, 'toJSON', {
3044
- value(omitUnderscoredProperties) {
3045
- return toObject.call(this, this[sourceSymbol]);
3046
- }
3047
- });
3048
- } else {
3049
- Object.defineProperty(prototype, 'toJSON', {
3050
- value(omitUnderscoredProperties) {
3051
- // return an enumerable object with own properties to JSON stringify
3052
- let resolved = {};
3053
- for (let i = 0, l = properties.length; i < l; i++) {
3054
- // TODO: check alwaysLazyProperty
3055
- let key = properties[i].key;
3056
-
3057
- resolved[key] = this[key];
3058
- }
3059
- return resolved;
3060
- },
3061
- // not enumerable or anything
3062
- });
3063
- }
3064
- }
3065
- var instance = new construct();
3066
- instance[sourceSymbol] = {
3067
- bytes: src,
3068
- position,
3069
- srcString: '',
3070
- bytesEnd: srcEnd
3071
- };
3072
- return instance;
3073
- }
3074
- function toConstant(code) {
3075
- switch(code) {
3076
- case 0xf6: return null;
3077
- case 0xf7: return undefined;
3078
- case 0xf8: return false;
3079
- case 0xf9: return true;
3080
- }
3081
- throw new Error('Unknown constant');
3082
- }
3083
- function withSource(get) {
3084
- return function() {
3085
- return get(this[sourceSymbol]);
3086
- }
3087
- }
3088
-
3089
- function saveState() {
3090
- if (currentSource) {
3091
- currentSource.bytes = Uint8Array.prototype.slice.call(currentSource.bytes, currentSource.position, currentSource.bytesEnd);
3092
- currentSource.position = 0;
3093
- currentSource.bytesEnd = currentSource.bytes.length;
3094
- }
3095
- }
3096
- function prepareStructures(structures, packr) {
3097
- if (packr.typedStructs) {
3098
- let structMap = new Map();
3099
- structMap.set('named', structures);
3100
- structMap.set('typed', packr.typedStructs);
3101
- structures = structMap;
3102
- }
3103
- let lastTypedStructuresLength = packr.lastTypedStructuresLength || 0;
3104
- structures.isCompatible = existing => {
3105
- let compatible = true;
3106
- if (existing instanceof Map) {
3107
- let named = existing.get('named') || [];
3108
- if (named.length !== (packr.lastNamedStructuresLength || 0))
3109
- compatible = false;
3110
- let typed = existing.get('typed') || [];
3111
- if (typed.length !== lastTypedStructuresLength)
3112
- compatible = false;
3113
- } else if (existing instanceof Array || Array.isArray(existing)) {
3114
- if (existing.length !== (packr.lastNamedStructuresLength || 0))
3115
- compatible = false;
3116
- }
3117
- if (!compatible)
3118
- packr._mergeStructures(existing);
3119
- return compatible;
3120
- };
3121
- packr.lastTypedStructuresLength = packr.typedStructs && packr.typedStructs.length;
3122
- return structures;
3123
- }
3124
-
3125
- setReadStruct(readStruct, onLoadedStructures, saveState);
3126
-
3127
- const nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';
3128
-
3129
- if (!nativeAccelerationDisabled) {
3130
- let extractor;
3131
- try {
3132
- if (typeof require == 'function')
3133
- extractor = require('msgpackr-extract');
3134
- else
3135
- extractor = module.createRequire((document.currentScript && document.currentScript.src || new URL('test.js', document.baseURI).href))('msgpackr-extract');
3136
- if (extractor)
3137
- setExtractor(extractor.extractStrings);
3138
- } catch (error) {
3139
- // native module is optional
3140
- }
3141
- }
3142
-
3143
- let allSampleData = [];
3144
- for (let i = 1; i < 6; i++) {
3145
- allSampleData.push(JSON.parse(fs.readFileSync(new URL(`./example${i > 1 ? i : ''}.json`, (document.currentScript && document.currentScript.src || new URL('test.js', document.baseURI).href)))));
3146
- }
3147
- allSampleData.push({
3148
- name: 'some other types',
3149
- date: new Date(),
3150
- empty: '',
3151
- });
3152
- const sampleData = allSampleData[3];
3153
- function tryRequire(module) {
3154
- try {
3155
- return require(module)
3156
- } catch(error) {
3157
- return {}
3158
- }
3159
- }
3160
-
3161
- let seed = 0;
3162
- function random() {
3163
- seed++;
3164
- let a = seed * 15485863;
3165
- return (a * a * a % 2038074743) / 2038074743;
3166
- }
3167
- //if (typeof chai === 'undefined') { chai = require('chai') }
3168
- var assert = chai.assert;
3169
- //if (typeof msgpackr === 'undefined') { msgpackr = require('..') }
3170
- var Packr = Packr$1;
3171
- var Unpackr = Unpackr$1;
3172
- var unpack = unpack$1;
3173
- var unpackMultiple = unpackMultiple$1;
3174
- var roundFloat32 = roundFloat32$1;
3175
- var pack = pack$1;
3176
- var DECIMAL_FIT = FLOAT32_OPTIONS.DECIMAL_FIT;
3177
-
3178
- var addExtension = addExtension$1;
3179
- var zlib = tryRequire('zlib');
3180
- zlib.deflateSync;
3181
- zlib.inflateSync;
3182
- zlib.brotliCompressSync;
3183
- zlib.brotliDecompressSync;
3184
- zlib.constants;
3185
-
3186
- var ITERATIONS = 4000;
3187
-
3188
- class ExtendArray extends Array {
3189
- }
3190
-
3191
- class ExtendArray2 extends Array {
3192
- }
3193
-
3194
- class ExtendArray3 extends Array {
3195
- }
3196
-
3197
-
3198
- class ExtendObject {
3199
- }
3200
-
3201
-
3202
- suite('msgpackr basic tests', function() {
3203
- test('pack/unpack data', function () {
3204
- var data = {
3205
- data: [
3206
- {a: 1, name: 'one', type: 'odd', isOdd: true},
3207
- {a: 2, name: 'two', type: 'even'},
3208
- {a: 3, name: 'three', type: 'odd', isOdd: true},
3209
- {a: 4, name: 'four', type: 'even'},
3210
- {a: 5, name: 'five', type: 'odd', isOdd: true},
3211
- {a: 6, name: 'six', type: 'even', isOdd: null}
3212
- ],
3213
- description: 'some names',
3214
- types: ['odd', 'even'],
3215
- convertEnumToNum: [
3216
- {prop: 'test'},
3217
- {prop: 'test'},
3218
- {prop: 'test'},
3219
- {prop: 1},
3220
- {prop: 2},
3221
- {prop: [undefined]},
3222
- {prop: null}
3223
- ]
3224
- };
3225
- let structures = [];
3226
- let packr = new Packr({structures});
3227
- var serialized = packr.pack(data);
3228
- serialized = packr.pack(data);
3229
- serialized = packr.pack(data);
3230
- var deserialized = packr.unpack(serialized);
3231
- assert.deepEqual(deserialized, data);
3232
- });
3233
-
3234
- test('mixed structures', function () {
3235
- let data1 = {a: 1, b: 2, c: 3};
3236
- let data2 = {a: 1, b: 2, d: 4};
3237
- let data3 = {a: 1, b: 2, e: 5};
3238
- let structures = [];
3239
- let packr = new Packr({structures});
3240
- var serialized = packr.pack(data1);
3241
- var deserialized = packr.unpack(serialized);
3242
- assert.deepEqual(deserialized, data1);
3243
- var serialized = packr.pack(data2);
3244
- var deserialized = packr.unpack(serialized);
3245
- assert.deepEqual(deserialized, data2);
3246
- var serialized = packr.pack(data3);
3247
- var deserialized = packr.unpack(serialized);
3248
- assert.deepEqual(deserialized, data3);
3249
- });
3250
-
3251
- test('mixed array', function () {
3252
- var data = [
3253
- 'one',
3254
- 'two',
3255
- 'one',
3256
- 10,
3257
- 11,
3258
- null,
3259
- true,
3260
- 'three',
3261
- 'three',
3262
- 'one', [
3263
- 3, -5, -50, -400, 1.3, -5.3, true
3264
- ]
3265
- ];
3266
- let structures = [];
3267
- let packr = new Packr({structures});
3268
- var serialized = packr.pack(data);
3269
- var deserialized = packr.unpack(serialized);
3270
- assert.deepEqual(deserialized, data);
3271
- });
3272
- test('255 chars', function () {
3273
- const data = 'RRZG9A6I7xupPeOZhxcOcioFsuhszGOdyDUcbRf4Zef2kdPIfC9RaLO4jTM5JhuZvTsF09fbRHMGtqk7YAgu3vespeTe9l61ziZ6VrMnYu2CamK96wCkmz0VUXyqaiUoTPgzk414LS9yYrd5uh7w18ksJF5SlC2e91rukWvNqAZJjYN3jpkqHNOFchCwFrhbxq2Lrv1kSJPYCx9blRg2hGmYqTbElLTZHv20iNqwZeQbRMgSBPT6vnbCBPnOh1W';
3274
- var serialized = pack(data);
3275
- var deserialized = unpack(serialized);
3276
- assert.equal(deserialized, data);
3277
- });
3278
- test('use ArrayBuffer', function () {
3279
- const data = {prop: 'a test'};
3280
- var serialized = pack(data);
3281
- let ab = new ArrayBuffer(serialized.length);
3282
- let u8 = new Uint8Array(ab);
3283
- u8.set(serialized);
3284
- var deserialized = unpack(ab);
3285
- assert.deepEqual(deserialized, data);
3286
- });
3287
- test('pack/unpack varying data with random access structures', function () {
3288
- let structures = [];
3289
- let packr = new Packr({
3290
- structures, useRecords: true, randomAccessStructure: true, freezeData: true, saveStructures(structures) {
3291
- }, getStructures() {
3292
- console.log('getStructures');
3293
- }
3294
- });
3295
- for (let i = 0; i < 2000; i++) {
3296
- let data = {};
3297
- let props = ['foo', 'bar', 'a', 'b', 'c', 'name', 'age', 'd'];
3298
-
3299
- function makeString() {
3300
- let str = '';
3301
- while (random() < 0.9) {
3302
- str += random() < 0.8 ? 'hello world' : String.fromCharCode(300);
3303
- }
3304
- return str;
3305
- }
3306
-
3307
- for (let i = 0; i < random() * 20; i++) {
3308
- data[props[Math.floor(random() * 8)]] =
3309
- random() < 0.3 ? Math.floor(random() * 400) / 2 :
3310
- random() < 0.3 ? makeString() : random() < 0.3 ? true : random() < 0.3 ? sampleData : null;
3311
- }
3312
- var serialized = packr.pack(data);
3313
- var deserialized = packr.unpack(serialized);
3314
- for (let key in deserialized) {
3315
- deserialized[key];
3316
- }
3317
- assert.deepEqual(deserialized, data);
3318
- }
3319
- });
3320
-
3321
- for (let sampleData of allSampleData) {
3322
- let snippet = JSON.stringify(sampleData).slice(0, 20) + '...';
3323
- test('pack/unpack sample data ' + snippet, function () {
3324
- var data = sampleData;
3325
- var serialized = pack(data);
3326
- var deserialized = unpack(serialized);
3327
- assert.deepEqual(deserialized, data);
3328
- var serialized = pack(data);
3329
- var deserialized = unpack(serialized);
3330
- assert.deepEqual(deserialized, data);
3331
- });
3332
- test('pack/unpack sample data with Uint8Array encoding' + snippet, function () {
3333
- var data = sampleData;
3334
- var serialized = pack(data);
3335
- serialized = new Uint8Array(serialized);
3336
- var deserialized = unpack(serialized);
3337
- assert.deepEqual(deserialized, data);
3338
- var serialized = pack(data);
3339
- var deserialized = unpack(serialized);
3340
- assert.deepEqual(deserialized, data);
3341
- });
3342
- test('pack/unpack sample data with random access structures ' + snippet, function () {
3343
- var data = sampleData;
3344
- let structures = [];
3345
- let packr = new Packr({
3346
- structures, useRecords: true, randomAccessStructure: true, freezeData: true, saveStructures(structures) {
3347
- }, getStructures() {
3348
- console.log('getStructures');
3349
- }
3350
- });
3351
- for (let i = 0; i < 20; i++) {
3352
- var serialized = packr.pack(data);
3353
- var deserialized = packr.unpack(serialized, {lazy: true});
3354
- var copied = {};
3355
- for (let key in deserialized) {
3356
- copied[key] = deserialized[key];
3357
- }
3358
- assert.deepEqual(copied, data);
3359
- }
3360
- });
3361
- test('pack/unpack sample data with bundled strings ' + snippet, function () {
3362
- var data = sampleData;
3363
- let packr = new Packr({ /*structures,*/ useRecords: false, bundleStrings: true});
3364
- var serialized = packr.pack(data);
3365
- var deserialized = packr.unpack(serialized);
3366
- assert.deepEqual(deserialized, data);
3367
- });
3368
- }
3369
-
3370
- test('pack/unpack sample data with useRecords function', function () {
3371
- var data = [
3372
- {id: 1, type: 1, labels: {a: 1, b: 2}},
3373
- {id: 2, type: 1, labels: {b: 1, c: 2}},
3374
- {id: 3, type: 1, labels: {d: 1, e: 2}}
3375
- ];
3376
-
3377
- var alternatives = [
3378
- {useRecords: false}, // 88 bytes
3379
- {useRecords: true}, // 58 bytes
3380
- {mapsAsObjects: true, useRecords: (v)=>!!v.id}, // 55 bytes
3381
- {mapsAsObjects: true, variableMapSize: true, useRecords: (v)=>!!v.id} // 49 bytes
3382
- ];
3383
-
3384
- for(let o of alternatives) {
3385
- let packr = new Packr(o);
3386
- var serialized = packr.pack(data);
3387
- var deserialized = packr.unpack(serialized);
3388
- assert.deepEqual(deserialized, data);
3389
- }
3390
- });
3391
-
3392
- test('mapAsEmptyObject combination', function () {
3393
- const msgpackr = new Packr({ useRecords: false, encodeUndefinedAsNil: true, variableMapSize: true, mapAsEmptyObject: true, setAsEmptyObject: true });
3394
-
3395
- const map = new Map();
3396
- map.set('a', 1);
3397
- map.set('b', 2);
3398
- const set = new Set();
3399
- set.add('a');
3400
- set.add('b');
3401
- const input = { map, set };
3402
-
3403
- const packed = msgpackr.pack(input);
3404
- const unpacked = msgpackr.unpack(packed);
3405
- assert.deepEqual(unpacked.map, {});
3406
- assert.deepEqual(unpacked.set, {});
3407
- });
3408
- test('pack/unpack numeric coercible keys', function () {
3409
- var data = { a: 1, 2: 'test', '-3.45': 'test2'};
3410
- let packr = new Packr({variableMapSize: true, coercibleKeyAsNumber: true, useRecords: false});
3411
- var serialized = packr.pack(data);
3412
- var deserialized = packr.unpack(serialized);
3413
- assert.deepEqual(deserialized, data);
3414
- });
3415
- test('pack/unpack empty data with bundled strings', function () {
3416
- var data = {};
3417
- let packr = new Packr({bundleStrings: true});
3418
- var serialized = packr.pack(data);
3419
- var deserialized = packr.unpack(serialized);
3420
- assert.deepEqual(deserialized, data);
3421
- });
3422
- test('pack/unpack large amount of chinese characters', function() {
3423
- const MSGPACK_OPTIONS = {bundleStrings: true};
3424
-
3425
- const item = {
3426
- message: '你好你好你好你好你好你好你好你好你好', // some Chinese characters
3427
- };
3428
-
3429
- testSize(100);
3430
- testSize(1000);
3431
- testSize(10000);
3432
- function testSize(size) {
3433
- const list = [];
3434
- for (let i = 0; i < size; i++) {
3435
- list.push({...item});
3436
- }
3437
-
3438
- const packer = new Packr(MSGPACK_OPTIONS);
3439
- const unpacker = new Unpackr(MSGPACK_OPTIONS);
3440
- const encoded = packer.pack(list);
3441
- const decoded = unpacker.unpack(encoded);
3442
- assert.deepEqual(list, decoded);
3443
- }
3444
- });
3445
- test('pack/unpack sequential data', function () {
3446
- var data = {foo: 1, bar: 2};
3447
- let packr = new Packr({sequential: true});
3448
- let unpackr = new Unpackr({sequential: true});
3449
- var serialized = packr.pack(data);
3450
- var deserialized = unpackr.unpack(serialized);
3451
- assert.deepEqual(deserialized, data);
3452
- var serialized = packr.pack(data);
3453
- var deserialized = unpackr.unpack(serialized);
3454
- assert.deepEqual(deserialized, data);
3455
- });
3456
- test('pack/unpack with bundled strings and sequential', function () {
3457
- const options = {
3458
- bundleStrings: true,
3459
- sequential: true,
3460
- };
3461
-
3462
- const packer = new Packr(options);
3463
- const unpacker = new Packr(options);
3464
-
3465
- const data = {data: 42}; // key length >= 4
3466
-
3467
- unpacker.unpackMultiple(Buffer.concat([
3468
- packer.pack(data),
3469
- packer.pack(data)
3470
- ]));
3471
- });
3472
- if (typeof Buffer != 'undefined')
3473
- test('replace data', function(){
3474
- var data1 = {
3475
- data: [
3476
- { a: 1, name: 'one', type: 'odd', isOdd: true, a: '13 characters' },
3477
- { a: 2, name: 'two', type: 'even', a: '11 characte' },
3478
- { a: 3, name: 'three', type: 'odd', isOdd: true, a: '12 character' },
3479
- { a: 4, name: 'four', type: 'even', a: '9 charact'},
3480
- { a: 5, name: 'five', type: 'odd', isOdd: true, a: '14 characters!' },
3481
- { a: 6, name: 'six', type: 'even', isOdd: null }
3482
- ],
3483
- };
3484
- var data2 = {
3485
- data: [
3486
- { foo: 7, name: 'one', type: 'odd', isOdd: true },
3487
- { foo: 8, name: 'two', type: 'even'},
3488
- { foo: 9, name: 'three', type: 'odd', isOdd: true },
3489
- { foo: 10, name: 'four', type: 'even'},
3490
- { foo: 11, name: 'five', type: 'odd', isOdd: true },
3491
- { foo: 12, name: 'six', type: 'even', isOdd: null }
3492
- ],
3493
- };
3494
- var serialized1 = pack(data1);
3495
- var serialized2 = pack(data2);
3496
- var b = Buffer.alloc(8000);
3497
- serialized1.copy(b);
3498
- var deserialized1 = unpack(b, serialized1.length);
3499
- serialized2.copy(b);
3500
- var deserialized2 = unpack(b, serialized2.length);
3501
- assert.deepEqual(deserialized1, data1);
3502
- assert.deepEqual(deserialized2, data2);
3503
- });
3504
-
3505
- test('compact 123', function() {
3506
- assert.equal(pack(123).length, 1);
3507
- });
3508
-
3509
- test('BigInt', function() {
3510
- let packr = new Packr({ useBigIntExtension: true });
3511
- let data = {
3512
- a: 3333333333333333333333333333n,
3513
- b: 1234567890123456789012345678901234567890n,
3514
- c: -3333333333333333333333333333n,
3515
- d: -352523523642364364364264264264264264262642642n,
3516
- e: 0xffffffffffffffffffffffffffn,
3517
- f: -0xffffffffffffffffffffffffffn,
3518
- g: (1234n << 123n) ^ (5678n << 56n) ^ 890n,
3519
- h: (-1234n << 123n) ^ (5678n << 56n) ^ 890n,
3520
- i: (1234n << 1234n) ^ (5678n << 567n) ^ 890n,
3521
- j: (-1234n << 1234n) ^ (5678n << 567n) ^ 890n,
3522
- k: 0xdeadn << 0xbeefn,
3523
- l: -0xdeadn << 0xbeefn,
3524
- m: 11n << 0x11111n ^ 111n,
3525
- n: -11n << 0x11111n ^ 111n,
3526
- o: 12345678901234567890n,
3527
- p: -12345678901234567890n,
3528
- exp: [],
3529
- expexp: [],
3530
- };
3531
-
3532
- for (let n = 1n; n.toString(16).length * 4 < 1500; n <<= 1n, n |= BigInt(Math.floor(Math.random() * 2))) {
3533
- data.exp.push(n, -n);
3534
- }
3535
-
3536
- for (let n = 7n; n.toString(16).length * 4 < 150000; n *= n) {
3537
- data.expexp.push(n, -n);
3538
- }
3539
-
3540
- let serialized = packr.pack(data);
3541
- let deserialized = packr.unpack(serialized);
3542
- assert.deepEqual(data, deserialized);
3543
- });
3544
-
3545
-
3546
- test('extended class pack/unpack', function(){
3547
- function Extended() {
3548
-
3549
- }
3550
- Extended.prototype.getDouble = function() {
3551
- return this.value * 2
3552
- };
3553
- var instance = new Extended();
3554
- instance.value = 4;
3555
- instance.string = 'decode this: ᾜ';
3556
- var data = {
3557
- prop1: 'has multi-byte: ᾜ',
3558
- extendedInstance: instance,
3559
- prop2: 'more string',
3560
- num: 3,
3561
- };
3562
- let packr = new Packr();
3563
- addExtension({
3564
- Class: Extended,
3565
- type: 11,
3566
- unpack: function(buffer) {
3567
- let e = new Extended();
3568
- let data = packr.unpack(buffer);
3569
- e.value = data[0];
3570
- e.string = data[1];
3571
- return e
3572
- },
3573
- pack: function(instance) {
3574
- return packr.pack([instance.value, instance.string])
3575
- }
3576
- });
3577
- var serialized = pack(data);
3578
- var deserialized = unpack(serialized);
3579
- assert.deepEqual(data, deserialized);
3580
- assert.equal(deserialized.extendedInstance.getDouble(), 8);
3581
- });
3582
-
3583
- test('extended Array class read/write', function(){
3584
- var instance = new ExtendArray();
3585
- instance.push(0);
3586
- instance.push(1);
3587
- instance.push(2);
3588
- var data = {
3589
- prop1: 'has multi-byte: ᾜ',
3590
- extendedInstance: instance,
3591
- prop2: 'more string',
3592
- num: 3,
3593
- };
3594
- new Packr();
3595
- addExtension({
3596
- Class: ExtendArray,
3597
- type: 12,
3598
- read: function(data) {
3599
- Object.setPrototypeOf(data, ExtendArray.prototype);
3600
- return data
3601
- },
3602
- write: function(instance) {
3603
- return [...instance]
3604
- }
3605
- });
3606
- var serialized = pack(data);
3607
- var deserialized = unpack(serialized);
3608
- assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), ExtendArray.prototype);
3609
- assert.deepEqual(data, deserialized);
3610
- });
3611
-
3612
- test('unregistered extended Array class read/write', function(){
3613
- var instance = new ExtendArray2();
3614
- instance.push(0);
3615
- instance.push(1);
3616
- instance.push(2);
3617
- var data = {
3618
- prop1: 'has multi-byte: ᾜ',
3619
- extendedInstance: instance,
3620
- prop2: 'more string',
3621
- num: 3,
3622
- };
3623
- new Packr();
3624
- var serialized = pack(data);
3625
- var deserialized = unpack(serialized);
3626
- assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), Array.prototype);
3627
- assert.deepEqual(data, deserialized);
3628
- });
3629
-
3630
-
3631
- test('unregistered extended Object class read/write', function(){
3632
- var instance = new ExtendObject();
3633
- instance.test1 = "string";
3634
- instance.test2 = 3421321;
3635
- var data = {
3636
- prop1: 'has multi-byte: ᾜ',
3637
- extendedInstance: instance,
3638
- prop2: 'more string',
3639
- num: 3,
3640
- };
3641
- new Packr();
3642
- var serialized = pack(data);
3643
- var deserialized = unpack(serialized);
3644
- assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), Object.prototype);
3645
- assert.deepEqual(data, deserialized);
3646
- });
3647
-
3648
- test('extended class pack/unpack custom size', function(){
3649
- function TestClass() {
3650
-
3651
- }
3652
- addExtension({
3653
- Class: TestClass,
3654
- type: 0x01,
3655
- pack() {
3656
- return typeof Buffer != 'undefined' ? Buffer.alloc(256) : new Uint8Array(256)
3657
- },
3658
- unpack(data) {
3659
- return data.length
3660
- }
3661
- });
3662
- let result = unpack(pack(new TestClass()));
3663
- assert.equal(result, 256);
3664
- });
3665
-
3666
- test('extended class read/write', function(){
3667
- function Extended() {
3668
-
3669
- }
3670
- Extended.prototype.getDouble = function() {
3671
- return this.value * 2
3672
- };
3673
- var instance = new Extended();
3674
- instance.value = 4;
3675
- instance.string = 'decode this: ᾜ';
3676
- var data = {
3677
- prop1: 'has multi-byte: ᾜ',
3678
- extendedInstance: instance,
3679
- prop2: 'more string',
3680
- num: 3,
3681
- };
3682
- new Packr();
3683
- addExtension({
3684
- Class: Extended,
3685
- type: 12,
3686
- read: function(data) {
3687
- let e = new Extended();
3688
- e.value = data[0];
3689
- e.string = data[1];
3690
- return e
3691
- },
3692
- write: function(instance) {
3693
- return [instance.value, instance.string]
3694
- }
3695
- });
3696
- var serialized = pack(data);
3697
- var deserialized = unpack(serialized);
3698
- assert.deepEqual(data, deserialized);
3699
- assert.equal(deserialized.extendedInstance.getDouble(), 8);
3700
- });
3701
- test('extended class return self', function(){
3702
- function Extended() {
3703
-
3704
- }
3705
- Extended.prototype.getDouble = function() {
3706
- return this.value * 2
3707
- };
3708
- var instance = new Extended();
3709
- instance.value = 4;
3710
- instance.string = 'decode this: ᾜ';
3711
- var data = {
3712
- prop1: 'has multi-byte: ᾜ',
3713
- extendedInstance: instance,
3714
- prop2: 'more string',
3715
- num: 3,
3716
- };
3717
- new Packr();
3718
- addExtension({
3719
- Class: Extended,
3720
- type: 13,
3721
- read: function(data) {
3722
- Object.setPrototypeOf(data, Extended.prototype);
3723
- return data
3724
- },
3725
- write: function(data) {
3726
- return data
3727
- }
3728
- });
3729
- var serialized = pack(data);
3730
- var deserialized = unpack(serialized);
3731
- assert.deepEqual(data, deserialized);
3732
- assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), Extended.prototype);
3733
- assert.equal(deserialized.extendedInstance.getDouble(), 8);
3734
- });
3735
- test('extended Array class return self', function(){
3736
- var instance = new ExtendArray3();
3737
- instance.push(0);
3738
- instance.push('has multi-byte: ᾜ');
3739
- var data = {
3740
- prop1: 'has multi-byte: ᾜ',
3741
- extendedInstance: instance,
3742
- prop2: 'more string',
3743
- num: 3,
3744
- };
3745
- new Packr();
3746
- addExtension({
3747
- Class: ExtendArray3,
3748
- type: 14,
3749
- read: function(data) {
3750
- Object.setPrototypeOf(data, ExtendArray3.prototype);
3751
- return data
3752
- },
3753
- write: function(data) {
3754
- return data
3755
- }
3756
- });
3757
- var serialized = pack(data);
3758
- var deserialized = unpack(serialized);
3759
- assert.deepEqual(data, deserialized);
3760
- assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), ExtendArray3.prototype);
3761
- assert.equal(deserialized.extendedInstance[0], 0);
3762
- });
3763
-
3764
- test('extended class pack/unpack proxied', function(){
3765
- function Extended() {
3766
-
3767
- }
3768
- Extended.prototype.__call__ = function(){
3769
- return this.value * 4
3770
- };
3771
- Extended.prototype.getDouble = function() {
3772
- return this.value * 2
3773
- };
3774
-
3775
- var instance = function() { instance.__call__();/* callable stuff */ };
3776
- Object.setPrototypeOf(instance,Extended.prototype);
3777
-
3778
- instance.value = 4;
3779
- var data = instance;
3780
-
3781
- let packr = new Packr();
3782
- addExtension({
3783
- Class: Extended,
3784
- type: 15,
3785
- unpack: function(buffer) {
3786
- var e = function() { e.__call__(); };
3787
- Object.setPrototypeOf(e,Extended.prototype);
3788
- e.value = packr.unpack(buffer);
3789
- return e
3790
- },
3791
- pack: function(instance) {
3792
- return packr.pack(instance.value)
3793
- }
3794
- });
3795
- var serialized = pack(data);
3796
- var deserialized = unpack(serialized);
3797
- assert.equal(deserialized.getDouble(), 8);
3798
- });
3799
-
3800
- test.skip('convert Date to string', function(){
3801
- var data = {
3802
- aDate: new Date(),
3803
- };
3804
- new Packr();
3805
- addExtension({
3806
- Class: Date,
3807
- write(date) {
3808
- return date.toString()
3809
- }
3810
- });
3811
- var serialized = pack(data);
3812
- var deserialized = unpack(serialized);
3813
- assert.equal(deserialized.aDate, data.aDate.toString());
3814
- });
3815
- test('standard pack fails on circular reference with shared structures', function () {
3816
- var data = {};
3817
- data.self = data;
3818
- let structures = [];
3819
- let packr = new Packr({
3820
- structures,
3821
- saveStructures(structures) {
3822
- }
3823
- });
3824
- assert.throws(function () {
3825
- packr.pack(data);
3826
- });
3827
- });
3828
-
3829
- test('proto handling', function() {
3830
- var objectWithProto = JSON.parse('{"__proto__":{"foo":3}}');
3831
- var decoded = unpack(pack(objectWithProto));
3832
- assert(!decoded.foo);
3833
- var objectsWithProto = [objectWithProto, objectWithProto, objectWithProto, objectWithProto, objectWithProto, objectWithProto];
3834
- let packr = new Packr();
3835
- var decoded = packr.unpack(packr.pack(objectsWithProto));
3836
- for (let object of decoded) {
3837
- assert(!decoded.foo);
3838
- }
3839
- });
3840
-
3841
- test.skip('text decoder', function() {
3842
- let td = new TextDecoder('ISO-8859-15');
3843
- let b = Buffer.alloc(3);
3844
- for (var i = 0; i < 256; i++) {
3845
- b[0] = i;
3846
- b[1] = 0;
3847
- b[2] = 0;
3848
- let s = td.decode(b);
3849
- if (!require('msgpackr-extract').isOneByte(s)) {
3850
- console.log(i.toString(16), s.length);
3851
- }
3852
- }
3853
- });
3854
-
3855
- test('moreTypes: Error with causes', function() {
3856
- const object = {
3857
- error: new Error('test'),
3858
- errorWithCause: new Error('test-1', { cause: new Error('test-2') }),
3859
- type: new TypeError(),
3860
- range: new RangeError('test', { cause: [1, 2] }),
3861
- };
3862
- const packr = new Packr({
3863
- moreTypes: true,
3864
- });
3865
-
3866
- const serialized = packr.pack(object);
3867
- const deserialized = packr.unpack(serialized);
3868
- assert.equal(deserialized.error.message, object.error.message);
3869
- assert.equal(deserialized.error.cause, object.error.cause);
3870
- assert.equal(deserialized.errorWithCause.message, object.errorWithCause.message);
3871
- assert.equal(deserialized.errorWithCause.cause.message, object.errorWithCause.cause.message);
3872
- assert.equal(deserialized.errorWithCause.cause.cause, object.errorWithCause.cause.cause);
3873
- assert.equal(deserialized.type.message, object.type.message);
3874
- assert.equal(deserialized.range.message, object.range.message);
3875
- assert.deepEqual(deserialized.range.cause, object.range.cause);
3876
- assert(deserialized.error instanceof Error);
3877
- assert(deserialized.type instanceof TypeError);
3878
- assert(deserialized.range instanceof RangeError);
3879
- });
3880
-
3881
- test('structured cloning: self reference', function() {
3882
- let object = {
3883
- test: 'string',
3884
- children: [
3885
- { name: 'child' }
3886
- ],
3887
- value: new ArrayBuffer(10)
3888
- };
3889
- let u8 = new Uint8Array(object.value);
3890
- u8[0] = 1;
3891
- u8[1] = 2;
3892
- object.self = object;
3893
- object.children[1] = object;
3894
- object.children[2] = object.children[0];
3895
- object.childrenAgain = object.children;
3896
- let packr = new Packr({
3897
- moreTypes: true,
3898
- structuredClone: true,
3899
- });
3900
- var serialized = packr.pack(object);
3901
- var deserialized = packr.unpack(serialized);
3902
- assert.equal(deserialized.self, deserialized);
3903
- assert.equal(deserialized.children[0].name, 'child');
3904
- assert.equal(deserialized.children[1], deserialized);
3905
- assert.equal(deserialized.children[0], deserialized.children[2]);
3906
- assert.equal(deserialized.children, deserialized.childrenAgain);
3907
- assert.equal(deserialized.value.constructor.name, 'ArrayBuffer');
3908
- u8 = new Uint8Array(deserialized.value);
3909
- assert.equal(u8[0], 1);
3910
- assert.equal(u8[1], 2);
3911
- });
3912
-
3913
- test('structured cloning: self reference with more types', function() {
3914
- let set = new Set();
3915
- set.add(['hello', 1, 2, { map: new Map([[set, set], ['a', 'b']]) }]);
3916
-
3917
- let packr = new Packr({
3918
- moreTypes: true,
3919
- structuredClone: true,
3920
- });
3921
- let serialized = packr.pack(set);
3922
- let deserialized = packr.unpack(serialized);
3923
- assert.equal(deserialized.constructor.name, 'Set');
3924
- let map = Array.from(deserialized)[0][3].map;
3925
- assert.equal(map.get(deserialized), deserialized);
3926
-
3927
- let sizeTestMap = new Map();
3928
- for (let i = 0; i < 50; i++) {
3929
- sizeTestMap.set(i || sizeTestMap, sizeTestMap);
3930
- let deserialized = packr.unpack(packr.pack(sizeTestMap));
3931
- assert.equal(deserialized.size, i + 1);
3932
- assert(deserialized.has(deserialized));
3933
- assert(deserialized.has(i || deserialized));
3934
- }
3935
-
3936
- let sizeTestSet = new Set();
3937
- for (let i = 0; i < 50; i++) {
3938
- sizeTestSet.add(i || sizeTestSet);
3939
- let deserialized = packr.unpack(packr.pack(sizeTestSet));
3940
- assert.equal(deserialized.size, i + 1);
3941
- assert(deserialized.has(deserialized));
3942
- assert(deserialized.has(i || deserialized));
3943
- }
3944
- });
3945
-
3946
- test('structured cloning: types', function() {
3947
- let b = typeof Buffer != 'undefined' ? Buffer.alloc(20) : new Uint8Array(20);
3948
- let fa = new Float32Array(b.buffer, 8, 2);
3949
- fa[0] = 2.25;
3950
- fa[1] = 6;
3951
- let object = {
3952
- error: new Error('test'),
3953
- set: new Set(['a', 'b']),
3954
- regexp: /test/gi,
3955
- float32Array: fa,
3956
- uint16Array: new Uint16Array([3, 4]),
3957
- arrayBuffer: new Uint8Array([0xde, 0xad]).buffer,
3958
- dataView: new DataView(new Uint8Array([0xbe, 0xef]).buffer),
3959
- };
3960
- let packr = new Packr({
3961
- moreTypes: true,
3962
- structuredClone: true,
3963
- });
3964
- var serialized = packr.pack(object);
3965
- var deserialized = packr.unpack(serialized);
3966
- assert.deepEqual(Array.from(deserialized.set), Array.from(object.set));
3967
- assert.equal(deserialized.error.message, object.error.message);
3968
- assert.equal(deserialized.regexp.test('TEST'), true);
3969
- assert.equal(deserialized.float32Array.constructor.name, 'Float32Array');
3970
- assert.equal(deserialized.float32Array[0], 2.25);
3971
- assert.equal(deserialized.float32Array[1], 6);
3972
- assert.equal(deserialized.uint16Array.constructor.name, 'Uint16Array');
3973
- assert.equal(deserialized.uint16Array[0], 3);
3974
- assert.equal(deserialized.uint16Array[1], 4);
3975
- assert.equal(deserialized.arrayBuffer.constructor.name, 'ArrayBuffer');
3976
- assert.equal(new DataView(deserialized.arrayBuffer).getUint16(), 0xdead);
3977
- assert.equal(deserialized.dataView.constructor.name, 'DataView');
3978
- assert.equal(deserialized.dataView.getUint16(), 0xbeef);
3979
- });
3980
- test('big bundledStrings', function() {
3981
- const MSGPACK_OPTIONS = {bundleStrings: true};
3982
- const packer = new Packr(MSGPACK_OPTIONS);
3983
- const unpacker = new Unpackr(MSGPACK_OPTIONS);
3984
-
3985
- const payload = {
3986
- output: [
3987
- {
3988
- url: 'https://www.example.com/',
3989
- },
3990
- ],
3991
- };
3992
-
3993
- for (let i = 0; i < 10000; i++) {
3994
- payload.output.push(payload.output[0]);
3995
- }
3996
- let deserialized = unpacker.unpack(packer.pack(payload));
3997
- assert.equal(deserialized.output[0].url, payload.output[0].url);
3998
- });
3999
- test('structured clone with bundled strings', function() {
4000
- const packer = new Packr({
4001
- structuredClone: true, // both options must be enabled
4002
- bundleStrings: true,
4003
- });
4004
-
4005
- const v = {};
4006
-
4007
- let shared = {
4008
- name1: v,
4009
- name2: v,
4010
- };
4011
-
4012
- let deserialized = packer.unpack(packer.pack(shared));
4013
- assert.equal(deserialized.name1, deserialized.name2);
4014
-
4015
- shared = {};
4016
- shared.aaaa = shared; // key length >= 4
4017
-
4018
- deserialized = packer.unpack(packer.pack(shared));
4019
- assert.equal(deserialized.aaaa, deserialized);
4020
- });
4021
-
4022
- test('object without prototype', function(){
4023
- var data = Object.create(null);
4024
- data.test = 3;
4025
- var serialized = pack(data);
4026
- var deserialized = unpack(serialized);
4027
- assert.deepEqual(deserialized, data);
4028
- });
4029
-
4030
- test('object with __proto__', function(){
4031
- const data = { foo: 'bar', __proto__: { isAdmin: true } };
4032
- var serialized = pack(data);
4033
- var deserialized = unpack(serialized);
4034
- assert.deepEqual(deserialized, { foo: 'bar' });
4035
- });
4036
-
4037
- test('separate instances', function() {
4038
- const packr = new Packr({
4039
- structures: [['m', 'e'], ['action', 'share']]
4040
- });
4041
- const packr2 = new Packr({
4042
- structures: [['m', 'e'], ['action', 'share']]
4043
- });
4044
- let packed = packr.pack([{m: 1, e: 2}, {action: 3, share: 4}]);
4045
- // also tried directly decoding this without the first Packr instance packed = new Uint8Array([0x92, 0x40, 0x01, 0x02, 0x41, 0x03, 0x04]);
4046
- console.log(packr2.unpack(packed));
4047
- });
4048
-
4049
- test('many shared structures', function() {
4050
- let data = [];
4051
- for (let i = 0; i < 200; i++) {
4052
- data.push({['a' + i]: i});
4053
- }
4054
- let structures = [];
4055
- let savedStructures;
4056
- let packr = new Packr({
4057
- structures,
4058
- saveStructures(structures) {
4059
- savedStructures = structures;
4060
- }
4061
- });
4062
- var serializedWith32 = packr.pack(data);
4063
- assert.equal(savedStructures.length, 32);
4064
- var deserialized = packr.unpack(serializedWith32);
4065
- assert.deepEqual(deserialized, data);
4066
- structures = structures.slice(0, 32);
4067
- packr = new Packr({
4068
- structures,
4069
- maxSharedStructures: 100,
4070
- saveStructures(structures) {
4071
- savedStructures = structures;
4072
- }
4073
- });
4074
- deserialized = packr.unpack(serializedWith32);
4075
- assert.deepEqual(deserialized, data);
4076
- structures = structures.slice(0, 32);
4077
- packr = new Packr({
4078
- structures,
4079
- maxSharedStructures: 100,
4080
- saveStructures(structures) {
4081
- savedStructures = structures;
4082
- }
4083
- });
4084
- let serialized = packr.pack(data);
4085
- assert.equal(savedStructures.length, 100);
4086
- deserialized = packr.unpack(serialized);
4087
- assert.deepEqual(deserialized, data);
4088
-
4089
- deserialized = packr.unpack(serializedWith32);
4090
- assert.deepEqual(deserialized, data);
4091
- assert.equal(savedStructures.length, 100);
4092
-
4093
- deserialized = packr.unpack(serialized);
4094
- assert.deepEqual(deserialized, data);
4095
- assert.equal(packr.structures.sharedLength, 100);
4096
- });
4097
- test('more shared structures', function() {
4098
- const structures = [];
4099
- for (let i = 0; i < 40; i++) {
4100
- structures.push(['a' + i]);
4101
- }
4102
- const structures2 = [...structures];
4103
- const packr = new Packr({
4104
- getStructures() {
4105
- return structures
4106
- },
4107
- saveStructures(structures) {
4108
- },
4109
- maxSharedStructures: 100
4110
- });
4111
- const packr2 = new Packr({
4112
- getStructures() {
4113
- return structures2
4114
- },
4115
- saveStructures(structures) {
4116
- },
4117
- maxSharedStructures: 100
4118
- });
4119
- const inputData = {a35: 35};
4120
- const buffer = packr.pack(inputData);
4121
- const outputData = packr2.decode(buffer);
4122
- assert.deepEqual(inputData, outputData);
4123
- });
4124
-
4125
- test('big buffer', function() {
4126
- var size = 100000000;
4127
- var data = new Uint8Array(size).fill(1);
4128
- var packed = pack(data);
4129
- var unpacked = unpack(packed);
4130
- assert.equal(unpacked.length, size);
4131
- });
4132
-
4133
- test('random strings', function(){
4134
- var data = [];
4135
- for (var i = 0; i < 2000; i++) {
4136
- var str = 'test';
4137
- while (Math.random() < 0.7 && str.length < 0x100000) {
4138
- str = str + String.fromCharCode(90/(Math.random() + 0.01)) + str;
4139
- }
4140
- data.push(str);
4141
- }
4142
- var serialized = pack(data);
4143
- var deserialized = unpack(serialized);
4144
- assert.deepEqual(deserialized, data);
4145
- });
4146
-
4147
- test('map/date', function(){
4148
- var map = new Map();
4149
- map.set(4, 'four');
4150
- map.set('three', 3);
4151
-
4152
-
4153
- var data = {
4154
- map: map,
4155
- date: new Date(1532219539733),
4156
- farFutureDate: new Date(3532219539133),
4157
- fartherFutureDate: new Date('2106-08-05T18:48:20.323Z'),
4158
- ancient: new Date(-3532219539133),
4159
- invalidDate: new Date('invalid')
4160
- };
4161
- let packr = new Packr();
4162
- var serialized = packr.pack(data);
4163
- var deserialized = packr.unpack(serialized);
4164
- assert.equal(deserialized.map.get(4), 'four');
4165
- assert.equal(deserialized.map.get('three'), 3);
4166
- assert.equal(deserialized.date.getTime(), 1532219539733);
4167
- assert.equal(deserialized.farFutureDate.getTime(), 3532219539133);
4168
- assert.equal(deserialized.fartherFutureDate.toISOString(), '2106-08-05T18:48:20.323Z');
4169
- assert.equal(deserialized.ancient.getTime(), -3532219539133);
4170
- assert.equal(deserialized.invalidDate.toString(), 'Invalid Date');
4171
- });
4172
- test('map/date with options', function(){
4173
- var map = new Map();
4174
- map.set(4, 'four');
4175
- map.set('three', 3);
4176
-
4177
-
4178
- var data = {
4179
- map: map,
4180
- date: new Date(1532219539011),
4181
- invalidDate: new Date('invalid')
4182
- };
4183
- let packr = new Packr({
4184
- mapsAsObjects: true,
4185
- useTimestamp32: true,
4186
- onInvalidDate: () => 'Custom invalid date'
4187
- });
4188
- var serialized = packr.pack(data);
4189
- var deserialized = packr.unpack(serialized);
4190
- assert.equal(deserialized.map[4], 'four');
4191
- assert.equal(deserialized.map.three, 3);
4192
- assert.equal(deserialized.date.getTime(), 1532219539000);
4193
- assert.equal(deserialized.invalidDate, 'Custom invalid date');
4194
- });
4195
- test('key caching', function() {
4196
- var data = {
4197
- foo: 2,
4198
- bar: 'test',
4199
- four: 4,
4200
- seven: 7,
4201
- foz: 3,
4202
- };
4203
- var serialized = pack(data);
4204
- var deserialized = unpack(serialized);
4205
- assert.deepEqual(deserialized, data);
4206
- // do multiple times to test caching
4207
- var serialized = pack(data);
4208
- var deserialized = unpack(serialized);
4209
- assert.deepEqual(deserialized, data);
4210
- var serialized = pack(data);
4211
- var deserialized = unpack(serialized);
4212
- assert.deepEqual(deserialized, data);
4213
- });
4214
- test('strings', function() {
4215
- var data = [''];
4216
- var serialized = pack(data);
4217
- var deserialized = unpack(serialized);
4218
- assert.deepEqual(deserialized, data);
4219
- // do multiple times
4220
- var serialized = pack(data);
4221
- var deserialized = unpack(serialized);
4222
- assert.deepEqual(deserialized, data);
4223
- data = 'decode this: ᾜ';
4224
- var serialized = pack(data);
4225
- var deserialized = unpack(serialized);
4226
- assert.deepEqual(deserialized, data);
4227
- data = 'decode this that is longer but without any non-latin characters';
4228
- var serialized = pack(data);
4229
- var deserialized = unpack(serialized);
4230
- assert.deepEqual(deserialized, data);
4231
- });
4232
- test('decimal float32', function() {
4233
- var data = {
4234
- a: 2.526,
4235
- b: 0.0035235,
4236
- c: 0.00000000000352501,
4237
- d: 3252.77,
4238
- };
4239
- let packr = new Packr({
4240
- useFloat32: DECIMAL_FIT
4241
- });
4242
- var serialized = packr.pack(data);
4243
- assert.equal(serialized.length, 32);
4244
- var deserialized = packr.unpack(serialized);
4245
- assert.deepEqual(deserialized, data);
4246
- });
4247
- test('int64/uint64 should be bigints by default', function() {
4248
- var data = {
4249
- a: 325283295382932843n
4250
- };
4251
-
4252
- let packr = new Packr();
4253
- var serialized = packr.pack(data);
4254
- var deserialized = packr.unpack(serialized);
4255
- assert.deepEqual(deserialized.a, 325283295382932843n);
4256
- });
4257
- test('bigint to float', function() {
4258
- var data = {
4259
- a: 325283295382932843n
4260
- };
4261
- let packr = new Packr({
4262
- int64AsType: 'number'
4263
- });
4264
- var serialized = packr.pack(data);
4265
- var deserialized = packr.unpack(serialized);
4266
- assert.deepEqual(deserialized.a, 325283295382932843);
4267
- });
4268
- test('int64AsNumber compatibility', function() {
4269
- // https://github.com/kriszyp/msgpackr/pull/85
4270
- var data = {
4271
- a: 325283295382932843n
4272
- };
4273
- let packr = new Packr({
4274
- int64AsNumber: true
4275
- });
4276
- var serialized = packr.pack(data);
4277
- var deserialized = packr.unpack(serialized);
4278
- assert.deepEqual(deserialized.a, 325283295382932843);
4279
- });
4280
- test('bigint to auto (float or bigint)', function() {
4281
- var data = {
4282
- a: -9007199254740993n,
4283
- b: -9007199254740992n,
4284
- c: 0n,
4285
- d: 9007199254740992n,
4286
- e: 9007199254740993n,
4287
- };
4288
- let packr = new Packr({
4289
- int64AsType: 'auto'
4290
- });
4291
- var serialized = packr.pack(data);
4292
- var deserialized = packr.unpack(serialized);
4293
- assert.deepEqual(deserialized.a, -9007199254740993n);
4294
- assert.deepEqual(deserialized.b, -9007199254740992);
4295
- assert.deepEqual(deserialized.c, 0);
4296
- assert.deepEqual(deserialized.d, 9007199254740992);
4297
- assert.deepEqual(deserialized.e, 9007199254740993n);
4298
- });
4299
- test('bigint to string', function() {
4300
- var data = {
4301
- a: 325283295382932843n,
4302
- };
4303
- let packr = new Packr({
4304
- int64AsType: 'string'
4305
- });
4306
- var serialized = packr.pack(data);
4307
- var deserialized = packr.unpack(serialized);
4308
- assert.deepEqual(deserialized.a, '325283295382932843');
4309
- });
4310
- test('fixint should be one byte', function(){
4311
- let encoded = pack(123);
4312
- assert.equal(encoded.length, 1);
4313
- });
4314
- test('numbers', function(){
4315
- var data = {
4316
- bigEncodable: 48978578104322,
4317
- dateEpoch: 1530886513200,
4318
- realBig: 3432235352353255323,
4319
- decimal: 32.55234,
4320
- negative: -34.11,
4321
- exponential: 0.234e123,
4322
- tiny: 3.233e-120,
4323
- zero: 0,
4324
- //negativeZero: -0,
4325
- Infinity: Infinity
4326
- };
4327
- var serialized = pack(data);
4328
- var deserialized = unpack(serialized);
4329
- assert.deepEqual(deserialized, data);
4330
- });
4331
- test('bigint', function(){
4332
- var data = {
4333
- bigintSmall: 352n,
4334
- bigintSmallNegative: -333335252n,
4335
- bigintBig: 2n**64n - 1n, // biggest possible
4336
- bigintBigNegative: -(2n**63n), // largest negative
4337
- mixedWithNormal: 44,
4338
- };
4339
- var serialized = pack(data);
4340
- var deserialized = unpack(serialized);
4341
- assert.deepEqual(deserialized, data);
4342
- var tooBigInt = {
4343
- tooBig: 2n**66n
4344
- };
4345
- assert.throws(function(){ serialized = pack(tooBigInt); });
4346
- let packr = new Packr({
4347
- largeBigIntToFloat: true
4348
- });
4349
- serialized = packr.pack(tooBigInt);
4350
- deserialized = unpack(serialized);
4351
- assert.isTrue(deserialized.tooBig > 2n**65n);
4352
-
4353
- packr = new Packr({
4354
- largeBigIntToString: true
4355
- });
4356
- serialized = packr.pack(tooBigInt);
4357
- deserialized = unpack(serialized);
4358
- assert.equal(deserialized.tooBig, (2n**66n).toString());
4359
- });
4360
-
4361
- test('roundFloat32', function() {
4362
- assert.equal(roundFloat32(0.00333000003), 0.00333);
4363
- assert.equal(roundFloat32(43.29999999993), 43.3);
4364
- });
4365
-
4366
- test('buffers', function(){
4367
- var data = {
4368
- buffer1: new Uint8Array([2,3,4]),
4369
- buffer2: new Uint8Array(pack(sampleData))
4370
- };
4371
- var serialized = pack(data);
4372
- var deserialized = unpack(serialized);
4373
- assert.deepEqual(deserialized, data);
4374
- });
4375
-
4376
- test('notepack test', function() {
4377
- const data = {
4378
- foo: 1,
4379
- bar: [1, 2, 3, 4, 'abc', 'def'],
4380
- foobar: {
4381
- foo: true,
4382
- bar: -2147483649,
4383
- foobar: {
4384
- foo: new Uint8Array([1, 2, 3, 4, 5]),
4385
- bar: 1.5,
4386
- foobar: [true, false, 'abcdefghijkmonpqrstuvwxyz']
4387
- }
4388
- }
4389
- };
4390
- var serialized = pack(data);
4391
- var deserialized = unpack(serialized);
4392
- var deserialized = unpack(serialized);
4393
- var deserialized = unpack(serialized);
4394
- assert.deepEqual(deserialized, data);
4395
- });
4396
-
4397
- test('arrays in map keys', function() {
4398
- const msgpackr = new Packr({ mapsAsObjects: true, allowArraysInMapKeys: true });
4399
-
4400
- const map = new Map();
4401
- map.set([1, 2, 3], 1);
4402
- map.set([1, 2, ['foo', 3.14]], 2);
4403
-
4404
- const packed = msgpackr.pack(map);
4405
- const unpacked = msgpackr.unpack(packed);
4406
- assert.deepEqual(unpacked, { '1,2,3': 1, '1,2,foo,3.14': 2 });
4407
- });
4408
-
4409
- test('utf16 causing expansion', function() {
4410
- this.timeout(10000);
4411
- let data = {fixstr: 'ᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝ', str8:'ᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝ'};
4412
- var serialized = pack(data);
4413
- var deserialized = unpack(serialized);
4414
- assert.deepEqual(deserialized, data);
4415
- });
4416
- test('unpackMultiple', () => {
4417
- let values = unpackMultiple(new Uint8Array([1, 2, 3, 4]));
4418
- assert.deepEqual(values, [1, 2, 3, 4]);
4419
- values = [];
4420
- unpackMultiple(new Uint8Array([1, 2, 3, 4]), value => values.push(value));
4421
- assert.deepEqual(values, [1, 2, 3, 4]);
4422
- });
4423
-
4424
- test('unpackMultiple with positions', () => {
4425
- let values = unpackMultiple(new Uint8Array([1, 2, 3, 4]));
4426
- assert.deepEqual(values, [1, 2, 3, 4]);
4427
- values = [];
4428
- unpackMultiple(new Uint8Array([1, 2, 3, 4]), (value,start,end) => values.push([value,start,end]));
4429
- assert.deepEqual(values, [[1,0,1], [2,1,2], [3,2,3], [4,3,4]]);
4430
- });
4431
-
4432
- test('pack toJSON returning this', () => {
4433
- class Serializable {
4434
- someData = [1, 2, 3, 4]
4435
- toJSON() {
4436
- return this
4437
- }
4438
- }
4439
- const serialized = pack(new Serializable);
4440
- const deserialized = unpack(serialized);
4441
- assert.deepStrictEqual(deserialized, { someData: [1, 2, 3, 4] });
4442
- });
4443
- test('skip values', function () {
4444
- var data = {
4445
- data: [
4446
- { a: 1, name: 'one', type: 'odd', isOdd: true },
4447
- { a: 2, name: 'two', type: 'even', isOdd: undefined },
4448
- { a: 3, name: 'three', type: 'odd', isOdd: true },
4449
- { a: 4, name: 'four', type: 'even', isOdd: null},
4450
- { a: 5, name: 'five', type: 'odd', isOdd: true },
4451
- { a: 6, name: 'six', type: 'even', isOdd: null }
4452
- ],
4453
- description: 'some names',
4454
- types: ['odd', 'even'],
4455
- convertEnumToNum: [
4456
- { prop: 'test' },
4457
- { prop: 'test' },
4458
- { prop: 'test' },
4459
- { prop: 1 },
4460
- { prop: 2 },
4461
- { prop: [undefined, null] },
4462
- { prop: null }
4463
- ]
4464
- };
4465
- var expected = {
4466
- data: [
4467
- { a: 1, name: 'one', type: 'odd', isOdd: true },
4468
- { a: 2, name: 'two', type: 'even' },
4469
- { a: 3, name: 'three', type: 'odd', isOdd: true },
4470
- { a: 4, name: 'four', type: 'even', },
4471
- { a: 5, name: 'five', type: 'odd', isOdd: true },
4472
- { a: 6, name: 'six', type: 'even' }
4473
- ],
4474
- description: 'some names',
4475
- types: ['odd', 'even'],
4476
- convertEnumToNum: [
4477
- { prop: 'test' },
4478
- { prop: 'test' },
4479
- { prop: 'test' },
4480
- { prop: 1 },
4481
- { prop: 2 },
4482
- { prop: [undefined, null] },
4483
- {}
4484
- ]
4485
- };
4486
- let packr = new Packr({ useRecords: false, skipValues: [undefined, null] });
4487
- var serialized = packr.pack(data);
4488
- var deserialized = packr.unpack(serialized);
4489
- assert.deepEqual(deserialized, expected);
4490
- });
4491
- });
4492
- suite('msgpackr performance tests', function(){
4493
- test('performance JSON.parse', function() {
4494
- var data = sampleData;
4495
- this.timeout(10000);
4496
- var serialized = JSON.stringify(data);
4497
- console.log('JSON size', serialized.length);
4498
- for (var i = 0; i < ITERATIONS; i++) {
4499
- JSON.parse(serialized);
4500
- }
4501
- });
4502
- test('performance JSON.stringify', function() {
4503
- var data = sampleData;
4504
- this.timeout(10000);
4505
- for (var i = 0; i < ITERATIONS; i++) {
4506
- JSON.stringify(data);
4507
- }
4508
- });
4509
- test('performance unpack', function() {
4510
- var data = sampleData;
4511
- this.timeout(10000);
4512
- let structures = [];
4513
- var serialized = pack(data);
4514
- console.log('MessagePack size', serialized.length);
4515
- let packr = new Packr({ structures, bundleStrings: false });
4516
- var serialized = packr.pack(data);
4517
- console.log('msgpackr w/ record ext size', serialized.length);
4518
- for (var i = 0; i < ITERATIONS; i++) {
4519
- packr.unpack(serialized);
4520
- }
4521
- });
4522
- test('performance pack', function() {
4523
- var data = sampleData;
4524
- this.timeout(10000);
4525
- let structures = [];
4526
- let packr = new Packr({ structures, bundleStrings: false });
4527
- let buffer = typeof Buffer != 'undefined' ? Buffer.alloc(0x10000) : new Uint8Array(0x10000);
4528
-
4529
- for (var i = 0; i < ITERATIONS; i++) {
4530
- //serialized = pack(data, { shared: sharedStructure })
4531
- packr.useBuffer(buffer);
4532
- packr.pack(data);
4533
- //var serializedGzip = deflateSync(serialized)
4534
- }
4535
- //console.log('serialized', serialized.length, global.propertyComparisons)
4536
- });
4537
- });
4538
-
4539
- })(chai, null, module, fs);
4540
- //# sourceMappingURL=test.js.map