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,2629 +0,0 @@
1
- 'use strict';
2
-
3
- var stream = require('stream');
4
- var module$1 = require('module');
5
-
6
- let decoder;
7
- try {
8
- decoder = new TextDecoder();
9
- } catch(error) {}
10
- let src;
11
- let srcEnd;
12
- let position$1 = 0;
13
- const EMPTY_ARRAY = [];
14
- const LEGACY_RECORD_INLINE_ID = 105;
15
- const RECORD_DEFINITIONS_ID = 0xdffe;
16
- const RECORD_INLINE_ID = 0xdfff; // temporary first-come first-serve tag // proposed tag: 0x7265 // 're'
17
- const BUNDLED_STRINGS_ID = 0xdff9;
18
- const PACKED_REFERENCE_TAG_ID = 6;
19
- const STOP_CODE = {};
20
- let maxArraySize = 112810000; // This is the maximum array size in V8. We would potentially detect and set it higher
21
- // for JSC, but this is pretty large and should be sufficient for most use cases
22
- let maxMapSize = 16810000; // JavaScript has a fixed maximum map size of about 16710000, but JS itself enforces this,
23
- // many keys in an object, so also probably a reasonable choice there.
24
- let strings = EMPTY_ARRAY;
25
- let stringPosition = 0;
26
- let currentDecoder = {};
27
- let currentStructures;
28
- let srcString;
29
- let srcStringStart = 0;
30
- let srcStringEnd = 0;
31
- let bundledStrings$1;
32
- let referenceMap;
33
- let currentExtensions = [];
34
- let currentExtensionRanges = [];
35
- let packedValues;
36
- let dataView;
37
- let restoreMapsAsObject;
38
- let defaultOptions = {
39
- useRecords: false,
40
- mapsAsObjects: true
41
- };
42
- let sequentialMode = false;
43
- let inlineObjectReadThreshold = 2;
44
- // no-eval build
45
- try {
46
- new Function('');
47
- } catch(error) {
48
- // if eval variants are not supported, do not create inline object readers ever
49
- inlineObjectReadThreshold = Infinity;
50
- }
51
-
52
-
53
-
54
- class Decoder {
55
- constructor(options) {
56
- if (options) {
57
- if ((options.keyMap || options._keyMap) && !options.useRecords) {
58
- options.useRecords = false;
59
- options.mapsAsObjects = true;
60
- }
61
- if (options.useRecords === false && options.mapsAsObjects === undefined)
62
- options.mapsAsObjects = true;
63
- if (options.getStructures)
64
- options.getShared = options.getStructures;
65
- if (options.getShared && !options.structures)
66
- (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
67
- if (options.keyMap) {
68
- this.mapKey = new Map();
69
- for (let [k,v] of Object.entries(options.keyMap)) this.mapKey.set(v,k);
70
- }
71
- }
72
- Object.assign(this, options);
73
- }
74
- /*
75
- decodeKey(key) {
76
- return this.keyMap
77
- ? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key
78
- : key
79
- }
80
- */
81
- decodeKey(key) {
82
- return this.keyMap ? this.mapKey.get(key) || key : key
83
- }
84
-
85
- encodeKey(key) {
86
- return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key
87
- }
88
-
89
- encodeKeys(rec) {
90
- if (!this._keyMap) return rec
91
- let map = new Map();
92
- for (let [k,v] of Object.entries(rec)) map.set((this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k), v);
93
- return map
94
- }
95
-
96
- decodeKeys(map) {
97
- if (!this._keyMap || map.constructor.name != 'Map') return map
98
- if (!this._mapKey) {
99
- this._mapKey = new Map();
100
- for (let [k,v] of Object.entries(this._keyMap)) this._mapKey.set(v,k);
101
- }
102
- let res = {};
103
- //map.forEach((v,k) => res[Object.keys(this._keyMap)[Object.values(this._keyMap).indexOf(k)] || k] = v)
104
- map.forEach((v,k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v);
105
- return res
106
- }
107
-
108
- mapDecode(source, end) {
109
-
110
- let res = this.decode(source);
111
- if (this._keyMap) {
112
- //Experiemntal support for Optimised KeyMap decoding
113
- switch (res.constructor.name) {
114
- case 'Array': return res.map(r => this.decodeKeys(r))
115
- //case 'Map': return this.decodeKeys(res)
116
- }
117
- }
118
- return res
119
- }
120
-
121
- decode(source, end) {
122
- if (src) {
123
- // re-entrant execution, save the state and restore it after we do this decode
124
- return saveState(() => {
125
- clearSource();
126
- return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end)
127
- })
128
- }
129
- srcEnd = end > -1 ? end : source.length;
130
- position$1 = 0;
131
- stringPosition = 0;
132
- srcStringEnd = 0;
133
- srcString = null;
134
- strings = EMPTY_ARRAY;
135
- bundledStrings$1 = null;
136
- src = source;
137
- // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
138
- // technique for getting data from a database where it can be copied into an existing buffer instead of creating
139
- // new ones
140
- try {
141
- dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
142
- } catch(error) {
143
- // if it doesn't have a buffer, maybe it is the wrong type of object
144
- src = null;
145
- if (source instanceof Uint8Array)
146
- throw error
147
- throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
148
- }
149
- if (this instanceof Decoder) {
150
- currentDecoder = this;
151
- packedValues = this.sharedValues &&
152
- (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) :
153
- this.sharedValues);
154
- if (this.structures) {
155
- currentStructures = this.structures;
156
- return checkedRead()
157
- } else if (!currentStructures || currentStructures.length > 0) {
158
- currentStructures = [];
159
- }
160
- } else {
161
- currentDecoder = defaultOptions;
162
- if (!currentStructures || currentStructures.length > 0)
163
- currentStructures = [];
164
- packedValues = null;
165
- }
166
- return checkedRead()
167
- }
168
- decodeMultiple(source, forEach) {
169
- let values, lastPosition = 0;
170
- try {
171
- let size = source.length;
172
- sequentialMode = true;
173
- let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size);
174
- if (forEach) {
175
- if (forEach(value) === false) {
176
- return
177
- }
178
- while(position$1 < size) {
179
- lastPosition = position$1;
180
- if (forEach(checkedRead()) === false) {
181
- return
182
- }
183
- }
184
- }
185
- else {
186
- values = [ value ];
187
- while(position$1 < size) {
188
- lastPosition = position$1;
189
- values.push(checkedRead());
190
- }
191
- return values
192
- }
193
- } catch(error) {
194
- error.lastPosition = lastPosition;
195
- error.values = values;
196
- throw error
197
- } finally {
198
- sequentialMode = false;
199
- clearSource();
200
- }
201
- }
202
- }
203
- function checkedRead() {
204
- try {
205
- let result = read();
206
- if (bundledStrings$1) {
207
- if (position$1 >= bundledStrings$1.postBundlePosition) {
208
- let error = new Error('Unexpected bundle position');
209
- error.incomplete = true;
210
- throw error
211
- }
212
- // bundled strings to skip past
213
- position$1 = bundledStrings$1.postBundlePosition;
214
- bundledStrings$1 = null;
215
- }
216
-
217
- if (position$1 == srcEnd) {
218
- // finished reading this source, cleanup references
219
- currentStructures = null;
220
- src = null;
221
- if (referenceMap)
222
- referenceMap = null;
223
- } else if (position$1 > srcEnd) {
224
- // over read
225
- let error = new Error('Unexpected end of CBOR data');
226
- error.incomplete = true;
227
- throw error
228
- } else if (!sequentialMode) {
229
- throw new Error('Data read, but end of buffer not reached')
230
- }
231
- // else more to read, but we are reading sequentially, so don't clear source yet
232
- return result
233
- } catch(error) {
234
- clearSource();
235
- if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) {
236
- error.incomplete = true;
237
- }
238
- throw error
239
- }
240
- }
241
-
242
- function read() {
243
- let token = src[position$1++];
244
- let majorType = token >> 5;
245
- token = token & 0x1f;
246
- if (token > 0x17) {
247
- switch (token) {
248
- case 0x18:
249
- token = src[position$1++];
250
- break
251
- case 0x19:
252
- if (majorType == 7) {
253
- return getFloat16()
254
- }
255
- token = dataView.getUint16(position$1);
256
- position$1 += 2;
257
- break
258
- case 0x1a:
259
- if (majorType == 7) {
260
- let value = dataView.getFloat32(position$1);
261
- if (currentDecoder.useFloat32 > 2) {
262
- // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
263
- let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
264
- position$1 += 4;
265
- return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
266
- }
267
- position$1 += 4;
268
- return value
269
- }
270
- token = dataView.getUint32(position$1);
271
- position$1 += 4;
272
- break
273
- case 0x1b:
274
- if (majorType == 7) {
275
- let value = dataView.getFloat64(position$1);
276
- position$1 += 8;
277
- return value
278
- }
279
- if (majorType > 1) {
280
- if (dataView.getUint32(position$1) > 0)
281
- throw new Error('JavaScript does not support arrays, maps, or strings with length over 4294967295')
282
- token = dataView.getUint32(position$1 + 4);
283
- } else if (currentDecoder.int64AsNumber) {
284
- token = dataView.getUint32(position$1) * 0x100000000;
285
- token += dataView.getUint32(position$1 + 4);
286
- } else
287
- token = dataView.getBigUint64(position$1);
288
- position$1 += 8;
289
- break
290
- case 0x1f:
291
- // indefinite length
292
- switch(majorType) {
293
- case 2: // byte string
294
- case 3: // text string
295
- throw new Error('Indefinite length not supported for byte or text strings')
296
- case 4: // array
297
- let array = [];
298
- let value, i = 0;
299
- while ((value = read()) != STOP_CODE) {
300
- if (i >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`)
301
- array[i++] = value;
302
- }
303
- return majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer.concat(array)
304
- case 5: // map
305
- let key;
306
- if (currentDecoder.mapsAsObjects) {
307
- let object = {};
308
- let i = 0;
309
- if (currentDecoder.keyMap) {
310
- while((key = read()) != STOP_CODE) {
311
- if (i++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`)
312
- object[safeKey(currentDecoder.decodeKey(key))] = read();
313
- }
314
- }
315
- else {
316
- while ((key = read()) != STOP_CODE) {
317
- if (i++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`)
318
- object[safeKey(key)] = read();
319
- }
320
- }
321
- return object
322
- } else {
323
- if (restoreMapsAsObject) {
324
- currentDecoder.mapsAsObjects = true;
325
- restoreMapsAsObject = false;
326
- }
327
- let map = new Map();
328
- if (currentDecoder.keyMap) {
329
- let i = 0;
330
- while((key = read()) != STOP_CODE) {
331
- if (i++ >= maxMapSize) {
332
- throw new Error(`Map size exceeds ${maxMapSize}`);
333
- }
334
- map.set(currentDecoder.decodeKey(key), read());
335
- }
336
- }
337
- else {
338
- let i = 0;
339
- while ((key = read()) != STOP_CODE) {
340
- if (i++ >= maxMapSize) {
341
- throw new Error(`Map size exceeds ${maxMapSize}`);
342
- }
343
- map.set(key, read());
344
- }
345
- }
346
- return map
347
- }
348
- case 7:
349
- return STOP_CODE
350
- default:
351
- throw new Error('Invalid major type for indefinite length ' + majorType)
352
- }
353
- default:
354
- throw new Error('Unknown token ' + token)
355
- }
356
- }
357
- switch (majorType) {
358
- case 0: // positive int
359
- return token
360
- case 1: // negative int
361
- return ~token
362
- case 2: // buffer
363
- return readBin(token)
364
- case 3: // string
365
- if (srcStringEnd >= position$1) {
366
- return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart)
367
- }
368
- if (srcStringEnd == 0 && srcEnd < 140 && token < 32) {
369
- // for small blocks, avoiding the overhead of the extract call is helpful
370
- let string = token < 16 ? shortStringInJS(token) : longStringInJS(token);
371
- if (string != null)
372
- return string
373
- }
374
- return readFixedString(token)
375
- case 4: // array
376
- if (token >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`)
377
- let array = new Array(token);
378
- //if (currentDecoder.keyMap) for (let i = 0; i < token; i++) array[i] = currentDecoder.decodeKey(read())
379
- //else
380
- for (let i = 0; i < token; i++) array[i] = read();
381
- return array
382
- case 5: // map
383
- if (token >= maxMapSize) throw new Error(`Map size exceeds ${maxArraySize}`)
384
- if (currentDecoder.mapsAsObjects) {
385
- let object = {};
386
- if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read();
387
- else for (let i = 0; i < token; i++) object[safeKey(read())] = read();
388
- return object
389
- } else {
390
- if (restoreMapsAsObject) {
391
- currentDecoder.mapsAsObjects = true;
392
- restoreMapsAsObject = false;
393
- }
394
- let map = new Map();
395
- if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()),read());
396
- else for (let i = 0; i < token; i++) map.set(read(), read());
397
- return map
398
- }
399
- case 6: // extension
400
- if (token >= BUNDLED_STRINGS_ID) {
401
- let structure = currentStructures[token & 0x1fff]; // check record structures first
402
- // At some point we may provide an option for dynamic tag assignment with a range like token >= 8 && (token < 16 || (token > 0x80 && token < 0xc0) || (token > 0x130 && token < 0x4000))
403
- if (structure) {
404
- if (!structure.read) structure.read = createStructureReader(structure);
405
- return structure.read()
406
- }
407
- if (token < 0x10000) {
408
- if (token == RECORD_INLINE_ID) { // we do a special check for this so that we can keep the
409
- // currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)
410
- let length = readJustLength();
411
- let id = read();
412
- let structure = read();
413
- recordDefinition(id, structure);
414
- let object = {};
415
- if (currentDecoder.keyMap) for (let i = 2; i < length; i++) {
416
- let key = currentDecoder.decodeKey(structure[i - 2]);
417
- object[safeKey(key)] = read();
418
- }
419
- else for (let i = 2; i < length; i++) {
420
- let key = structure[i - 2];
421
- object[safeKey(key)] = read();
422
- }
423
- return object
424
- }
425
- else if (token == RECORD_DEFINITIONS_ID) {
426
- let length = readJustLength();
427
- let id = read();
428
- for (let i = 2; i < length; i++) {
429
- recordDefinition(id++, read());
430
- }
431
- return read()
432
- } else if (token == BUNDLED_STRINGS_ID) {
433
- return readBundleExt()
434
- }
435
- if (currentDecoder.getShared) {
436
- loadShared();
437
- structure = currentStructures[token & 0x1fff];
438
- if (structure) {
439
- if (!structure.read)
440
- structure.read = createStructureReader(structure);
441
- return structure.read()
442
- }
443
- }
444
- }
445
- }
446
- let extension = currentExtensions[token];
447
- if (extension) {
448
- if (extension.handlesRead)
449
- return extension(read)
450
- else
451
- return extension(read())
452
- } else {
453
- let input = read();
454
- for (let i = 0; i < currentExtensionRanges.length; i++) {
455
- let value = currentExtensionRanges[i](token, input);
456
- if (value !== undefined)
457
- return value
458
- }
459
- return new Tag(input, token)
460
- }
461
- case 7: // fixed value
462
- switch (token) {
463
- case 0x14: return false
464
- case 0x15: return true
465
- case 0x16: return null
466
- case 0x17: return; // undefined
467
- case 0x1f:
468
- default:
469
- let packedValue = (packedValues || getPackedValues())[token];
470
- if (packedValue !== undefined)
471
- return packedValue
472
- throw new Error('Unknown token ' + token)
473
- }
474
- default: // negative int
475
- if (isNaN(token)) {
476
- let error = new Error('Unexpected end of CBOR data');
477
- error.incomplete = true;
478
- throw error
479
- }
480
- throw new Error('Unknown CBOR token ' + token)
481
- }
482
- }
483
- const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
484
- function createStructureReader(structure) {
485
- if (!structure) throw new Error('Structure is required in record definition');
486
- function readObject() {
487
- // get the array size from the header
488
- let length = src[position$1++];
489
- //let majorType = token >> 5
490
- length = length & 0x1f;
491
- if (length > 0x17) {
492
- switch (length) {
493
- case 0x18:
494
- length = src[position$1++];
495
- break
496
- case 0x19:
497
- length = dataView.getUint16(position$1);
498
- position$1 += 2;
499
- break
500
- case 0x1a:
501
- length = dataView.getUint32(position$1);
502
- position$1 += 4;
503
- break
504
- default:
505
- throw new Error('Expected array header, but got ' + src[position$1 - 1])
506
- }
507
- }
508
- // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
509
- let compiledReader = this.compiledReader; // first look to see if we have the fast compiled function
510
- while(compiledReader) {
511
- // we have a fast compiled object literal reader
512
- if (compiledReader.propertyCount === length)
513
- return compiledReader(read) // with the right length, so we use it
514
- compiledReader = compiledReader.next; // see if there is another reader with the right length
515
- }
516
- if (this.slowReads++ >= inlineObjectReadThreshold) { // create a fast compiled reader
517
- let array = this.length == length ? this : this.slice(0, length);
518
- compiledReader = currentDecoder.keyMap
519
- ? new Function('r', 'return {' + array.map(k => currentDecoder.decodeKey(k)).map(k => validName.test(k) ? safeKey(k) + ':r()' : ('[' + JSON.stringify(k) + ']:r()')).join(',') + '}')
520
- : new Function('r', 'return {' + array.map(key => validName.test(key) ? safeKey(key) + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}');
521
- if (this.compiledReader)
522
- compiledReader.next = this.compiledReader; // if there is an existing one, we store multiple readers as a linked list because it is usually pretty rare to have multiple readers (of different length) for the same structure
523
- compiledReader.propertyCount = length;
524
- this.compiledReader = compiledReader;
525
- return compiledReader(read)
526
- }
527
- let object = {};
528
- if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read();
529
- else for (let i = 0; i < length; i++) {
530
- object[safeKey(this[i])] = read();
531
- }
532
- return object
533
- }
534
- structure.slowReads = 0;
535
- return readObject
536
- }
537
-
538
- function safeKey(key) {
539
- // protect against prototype pollution
540
- if (typeof key === 'string') return key === '__proto__' ? '__proto_' : key
541
- if (typeof key === 'number' || typeof key === 'boolean' || typeof key === 'bigint') return key.toString();
542
- if (key == null) return key + '';
543
- // protect against expensive (DoS) string conversions
544
- throw new Error('Invalid property name type ' + typeof key);
545
- }
546
-
547
- let readFixedString = readStringJS;
548
-
549
- exports.isNativeAccelerationEnabled = false;
550
- function setExtractor(extractStrings) {
551
- exports.isNativeAccelerationEnabled = true;
552
- readFixedString = readString();
553
- function readString(headerLength) {
554
- return function readString(length) {
555
- let string = strings[stringPosition++];
556
- if (string == null) {
557
- if (bundledStrings$1)
558
- return readStringJS(length)
559
- let extraction = extractStrings(position$1, srcEnd, length, src);
560
- if (typeof extraction == 'string') {
561
- string = extraction;
562
- strings = EMPTY_ARRAY;
563
- } else {
564
- strings = extraction;
565
- stringPosition = 1;
566
- 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
567
- string = strings[0];
568
- if (string === undefined)
569
- throw new Error('Unexpected end of buffer')
570
- }
571
- }
572
- let srcStringLength = string.length;
573
- if (srcStringLength <= length) {
574
- position$1 += length;
575
- return string
576
- }
577
- srcString = string;
578
- srcStringStart = position$1;
579
- srcStringEnd = position$1 + srcStringLength;
580
- position$1 += length;
581
- return string.slice(0, length) // we know we just want the beginning
582
- }
583
- }
584
- }
585
- function readStringJS(length) {
586
- let result;
587
- if (length < 16) {
588
- if (result = shortStringInJS(length))
589
- return result
590
- }
591
- if (length > 64 && decoder)
592
- return decoder.decode(src.subarray(position$1, position$1 += length))
593
- const end = position$1 + length;
594
- const units = [];
595
- result = '';
596
- while (position$1 < end) {
597
- const byte1 = src[position$1++];
598
- if ((byte1 & 0x80) === 0) {
599
- // 1 byte
600
- units.push(byte1);
601
- } else if ((byte1 & 0xe0) === 0xc0) {
602
- // 2 bytes
603
- const byte2 = src[position$1++] & 0x3f;
604
- units.push(((byte1 & 0x1f) << 6) | byte2);
605
- } else if ((byte1 & 0xf0) === 0xe0) {
606
- // 3 bytes
607
- const byte2 = src[position$1++] & 0x3f;
608
- const byte3 = src[position$1++] & 0x3f;
609
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
610
- } else if ((byte1 & 0xf8) === 0xf0) {
611
- // 4 bytes
612
- const byte2 = src[position$1++] & 0x3f;
613
- const byte3 = src[position$1++] & 0x3f;
614
- const byte4 = src[position$1++] & 0x3f;
615
- let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
616
- if (unit > 0xffff) {
617
- unit -= 0x10000;
618
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
619
- unit = 0xdc00 | (unit & 0x3ff);
620
- }
621
- units.push(unit);
622
- } else {
623
- units.push(byte1);
624
- }
625
-
626
- if (units.length >= 0x1000) {
627
- result += fromCharCode.apply(String, units);
628
- units.length = 0;
629
- }
630
- }
631
-
632
- if (units.length > 0) {
633
- result += fromCharCode.apply(String, units);
634
- }
635
-
636
- return result
637
- }
638
- let fromCharCode = String.fromCharCode;
639
- function longStringInJS(length) {
640
- let start = position$1;
641
- let bytes = new Array(length);
642
- for (let i = 0; i < length; i++) {
643
- const byte = src[position$1++];
644
- if ((byte & 0x80) > 0) {
645
- position$1 = start;
646
- return
647
- }
648
- bytes[i] = byte;
649
- }
650
- return fromCharCode.apply(String, bytes)
651
- }
652
- function shortStringInJS(length) {
653
- if (length < 4) {
654
- if (length < 2) {
655
- if (length === 0)
656
- return ''
657
- else {
658
- let a = src[position$1++];
659
- if ((a & 0x80) > 1) {
660
- position$1 -= 1;
661
- return
662
- }
663
- return fromCharCode(a)
664
- }
665
- } else {
666
- let a = src[position$1++];
667
- let b = src[position$1++];
668
- if ((a & 0x80) > 0 || (b & 0x80) > 0) {
669
- position$1 -= 2;
670
- return
671
- }
672
- if (length < 3)
673
- return fromCharCode(a, b)
674
- let c = src[position$1++];
675
- if ((c & 0x80) > 0) {
676
- position$1 -= 3;
677
- return
678
- }
679
- return fromCharCode(a, b, c)
680
- }
681
- } else {
682
- let a = src[position$1++];
683
- let b = src[position$1++];
684
- let c = src[position$1++];
685
- let d = src[position$1++];
686
- if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
687
- position$1 -= 4;
688
- return
689
- }
690
- if (length < 6) {
691
- if (length === 4)
692
- return fromCharCode(a, b, c, d)
693
- else {
694
- let e = src[position$1++];
695
- if ((e & 0x80) > 0) {
696
- position$1 -= 5;
697
- return
698
- }
699
- return fromCharCode(a, b, c, d, e)
700
- }
701
- } else if (length < 8) {
702
- let e = src[position$1++];
703
- let f = src[position$1++];
704
- if ((e & 0x80) > 0 || (f & 0x80) > 0) {
705
- position$1 -= 6;
706
- return
707
- }
708
- if (length < 7)
709
- return fromCharCode(a, b, c, d, e, f)
710
- let g = src[position$1++];
711
- if ((g & 0x80) > 0) {
712
- position$1 -= 7;
713
- return
714
- }
715
- return fromCharCode(a, b, c, d, e, f, g)
716
- } else {
717
- let e = src[position$1++];
718
- let f = src[position$1++];
719
- let g = src[position$1++];
720
- let h = src[position$1++];
721
- if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
722
- position$1 -= 8;
723
- return
724
- }
725
- if (length < 10) {
726
- if (length === 8)
727
- return fromCharCode(a, b, c, d, e, f, g, h)
728
- else {
729
- let i = src[position$1++];
730
- if ((i & 0x80) > 0) {
731
- position$1 -= 9;
732
- return
733
- }
734
- return fromCharCode(a, b, c, d, e, f, g, h, i)
735
- }
736
- } else if (length < 12) {
737
- let i = src[position$1++];
738
- let j = src[position$1++];
739
- if ((i & 0x80) > 0 || (j & 0x80) > 0) {
740
- position$1 -= 10;
741
- return
742
- }
743
- if (length < 11)
744
- return fromCharCode(a, b, c, d, e, f, g, h, i, j)
745
- let k = src[position$1++];
746
- if ((k & 0x80) > 0) {
747
- position$1 -= 11;
748
- return
749
- }
750
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
751
- } else {
752
- let i = src[position$1++];
753
- let j = src[position$1++];
754
- let k = src[position$1++];
755
- let l = src[position$1++];
756
- if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
757
- position$1 -= 12;
758
- return
759
- }
760
- if (length < 14) {
761
- if (length === 12)
762
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
763
- else {
764
- let m = src[position$1++];
765
- if ((m & 0x80) > 0) {
766
- position$1 -= 13;
767
- return
768
- }
769
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
770
- }
771
- } else {
772
- let m = src[position$1++];
773
- let n = src[position$1++];
774
- if ((m & 0x80) > 0 || (n & 0x80) > 0) {
775
- position$1 -= 14;
776
- return
777
- }
778
- if (length < 15)
779
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
780
- let o = src[position$1++];
781
- if ((o & 0x80) > 0) {
782
- position$1 -= 15;
783
- return
784
- }
785
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
786
- }
787
- }
788
- }
789
- }
790
- }
791
-
792
- function readBin(length) {
793
- return currentDecoder.copyBuffers ?
794
- // specifically use the copying slice (not the node one)
795
- Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
796
- src.subarray(position$1, position$1 += length)
797
- }
798
- let f32Array = new Float32Array(1);
799
- let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
800
- function getFloat16() {
801
- let byte0 = src[position$1++];
802
- let byte1 = src[position$1++];
803
- let exponent = (byte0 & 0x7f) >> 2;
804
- if (exponent === 0x1f) { // specials
805
- if (byte1 || (byte0 & 3))
806
- return NaN;
807
- return (byte0 & 0x80) ? -Infinity : Infinity;
808
- }
809
- if (exponent === 0) { // sub-normals
810
- // significand with 10 fractional bits and divided by 2^14
811
- let abs = (((byte0 & 3) << 8) | byte1) / (1 << 24);
812
- return (byte0 & 0x80) ? -abs : abs
813
- }
814
-
815
- u8Array[3] = (byte0 & 0x80) | // sign bit
816
- ((exponent >> 1) + 56); // 4 of 5 of the exponent bits, re-offset-ed
817
- u8Array[2] = ((byte0 & 7) << 5) | // last exponent bit and first two mantissa bits
818
- (byte1 >> 3); // next 5 bits of mantissa
819
- u8Array[1] = byte1 << 5; // last three bits of mantissa
820
- u8Array[0] = 0;
821
- return f32Array[0];
822
- }
823
-
824
- new Array(4096);
825
-
826
- class Tag {
827
- constructor(value, tag) {
828
- this.value = value;
829
- this.tag = tag;
830
- }
831
- }
832
-
833
- currentExtensions[0] = (dateString) => {
834
- // string date extension
835
- return new Date(dateString)
836
- };
837
-
838
- currentExtensions[1] = (epochSec) => {
839
- // numeric date extension
840
- return new Date(Math.round(epochSec * 1000))
841
- };
842
-
843
- currentExtensions[2] = (buffer) => {
844
- // bigint extension
845
- let value = BigInt(0);
846
- for (let i = 0, l = buffer.byteLength; i < l; i++) {
847
- value = BigInt(buffer[i]) + (value << BigInt(8));
848
- }
849
- return value
850
- };
851
-
852
- currentExtensions[3] = (buffer) => {
853
- // negative bigint extension
854
- return BigInt(-1) - currentExtensions[2](buffer)
855
- };
856
- currentExtensions[4] = (fraction) => {
857
- // best to reparse to maintain accuracy
858
- return +(fraction[1] + 'e' + fraction[0])
859
- };
860
-
861
- currentExtensions[5] = (fraction) => {
862
- // probably not sufficiently accurate
863
- return fraction[1] * Math.exp(fraction[0] * Math.log(2))
864
- };
865
-
866
- // the registration of the record definition extension
867
- const recordDefinition = (id, structure) => {
868
- id = id - 0xe000;
869
- let existingStructure = currentStructures[id];
870
- if (existingStructure && existingStructure.isShared) {
871
- (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
872
- }
873
- currentStructures[id] = structure;
874
-
875
- structure.read = createStructureReader(structure);
876
- };
877
- currentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => {
878
- let length = data.length;
879
- let structure = data[1];
880
- recordDefinition(data[0], structure);
881
- let object = {};
882
- for (let i = 2; i < length; i++) {
883
- let key = structure[i - 2];
884
- object[safeKey(key)] = data[i];
885
- }
886
- return object
887
- };
888
- currentExtensions[14] = (value) => {
889
- if (bundledStrings$1)
890
- return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 += value)
891
- return new Tag(value, 14)
892
- };
893
- currentExtensions[15] = (value) => {
894
- if (bundledStrings$1)
895
- return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
896
- return new Tag(value, 15)
897
- };
898
- let glbl = { Error, RegExp };
899
- currentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object
900
- return (glbl[data[0]] || Error)(data[1], data[2])
901
- };
902
- const packedTable = (read) => {
903
- if (src[position$1++] != 0x84) {
904
- let error = new Error('Packed values structure must be followed by a 4 element array');
905
- if (src.length < position$1)
906
- error.incomplete = true;
907
- throw error
908
- }
909
- let newPackedValues = read(); // packed values
910
- if (!newPackedValues || !newPackedValues.length) {
911
- let error = new Error('Packed values structure must be followed by a 4 element array');
912
- error.incomplete = true;
913
- throw error
914
- }
915
- packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues;
916
- packedValues.prefixes = read();
917
- packedValues.suffixes = read();
918
- return read() // read the rump
919
- };
920
- packedTable.handlesRead = true;
921
- currentExtensions[51] = packedTable;
922
-
923
- currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { // packed reference
924
- if (!packedValues) {
925
- if (currentDecoder.getShared)
926
- loadShared();
927
- else
928
- return new Tag(data, PACKED_REFERENCE_TAG_ID)
929
- }
930
- if (typeof data == 'number')
931
- return packedValues[16 + (data >= 0 ? 2 * data : (-2 * data - 1))]
932
- let error = new Error('No support for non-integer packed references yet');
933
- if (data === undefined)
934
- error.incomplete = true;
935
- throw error
936
- };
937
-
938
- // The following code is an incomplete implementation of http://cbor.schmorp.de/stringref
939
- // the real thing would need to implemennt more logic to populate the stringRefs table and
940
- // maintain a stack of stringRef "namespaces".
941
- //
942
- // currentExtensions[25] = (id) => {
943
- // return stringRefs[id]
944
- // }
945
- // currentExtensions[256] = (read) => {
946
- // stringRefs = []
947
- // try {
948
- // return read()
949
- // } finally {
950
- // stringRefs = null
951
- // }
952
- // }
953
- // currentExtensions[256].handlesRead = true
954
-
955
- currentExtensions[28] = (read) => {
956
- // shareable http://cbor.schmorp.de/value-sharing (for structured clones)
957
- if (!referenceMap) {
958
- referenceMap = new Map();
959
- referenceMap.id = 0;
960
- }
961
- let id = referenceMap.id++;
962
- let startingPosition = position$1;
963
- let token = src[position$1];
964
- let target;
965
- // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
966
- // ahead past references to record structure definitions
967
- if ((token >> 5) == 4)
968
- target = [];
969
- else
970
- target = {};
971
-
972
- let refEntry = { target }; // a placeholder object
973
- referenceMap.set(id, refEntry);
974
- let targetProperties = read(); // read the next value as the target object to id
975
- if (refEntry.used) {// there is a cycle, so we have to assign properties to original target
976
- if (Object.getPrototypeOf(target) !== Object.getPrototypeOf(targetProperties)) {
977
- // this means that the returned target does not match the targetProperties, so we need rerun the read to
978
- // have the correctly create instance be assigned as a reference, then we do the copy the properties back to the
979
- // target
980
- // reset the position so that the read can be repeated
981
- position$1 = startingPosition;
982
- // the returned instance is our new target for references
983
- target = targetProperties;
984
- referenceMap.set(id, { target });
985
- targetProperties = read();
986
- }
987
- return Object.assign(target, targetProperties)
988
- }
989
- refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
990
- return targetProperties // no cycle, can just use the returned read object
991
- };
992
- currentExtensions[28].handlesRead = true;
993
-
994
- currentExtensions[29] = (id) => {
995
- // sharedref http://cbor.schmorp.de/value-sharing (for structured clones)
996
- let refEntry = referenceMap.get(id);
997
- refEntry.used = true;
998
- return refEntry.target
999
- };
1000
-
1001
- currentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
1002
- (currentExtensions[259] = (read) => {
1003
- // https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec
1004
- // for decoding as a standard Map
1005
- if (currentDecoder.mapsAsObjects) {
1006
- currentDecoder.mapsAsObjects = false;
1007
- restoreMapsAsObject = true;
1008
- }
1009
- return read()
1010
- }).handlesRead = true;
1011
- function combine(a, b) {
1012
- if (typeof a === 'string')
1013
- return a + b
1014
- if (a instanceof Array)
1015
- return a.concat(b)
1016
- return Object.assign({}, a, b)
1017
- }
1018
- function getPackedValues() {
1019
- if (!packedValues) {
1020
- if (currentDecoder.getShared)
1021
- loadShared();
1022
- else
1023
- throw new Error('No packed values available')
1024
- }
1025
- return packedValues
1026
- }
1027
- const SHARED_DATA_TAG_ID = 0x53687264; // ascii 'Shrd'
1028
- currentExtensionRanges.push((tag, input) => {
1029
- if (tag >= 225 && tag <= 255)
1030
- return combine(getPackedValues().prefixes[tag - 224], input)
1031
- if (tag >= 28704 && tag <= 32767)
1032
- return combine(getPackedValues().prefixes[tag - 28672], input)
1033
- if (tag >= 1879052288 && tag <= 2147483647)
1034
- return combine(getPackedValues().prefixes[tag - 1879048192], input)
1035
- if (tag >= 216 && tag <= 223)
1036
- return combine(input, getPackedValues().suffixes[tag - 216])
1037
- if (tag >= 27647 && tag <= 28671)
1038
- return combine(input, getPackedValues().suffixes[tag - 27639])
1039
- if (tag >= 1811940352 && tag <= 1879048191)
1040
- return combine(input, getPackedValues().suffixes[tag - 1811939328])
1041
- if (tag == SHARED_DATA_TAG_ID) {// we do a special check for this so that we can keep the currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)
1042
- return {
1043
- packedValues: packedValues,
1044
- structures: currentStructures.slice(0),
1045
- version: input,
1046
- }
1047
- }
1048
- if (tag == 55799) // self-descriptive CBOR tag, just return input value
1049
- return input
1050
- });
1051
-
1052
- const isLittleEndianMachine$1 = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
1053
- const typedArrays = [Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
1054
- typeof BigUint64Array == 'undefined' ? { name:'BigUint64Array' } : BigUint64Array, Int8Array, Int16Array, Int32Array,
1055
- typeof BigInt64Array == 'undefined' ? { name:'BigInt64Array' } : BigInt64Array, Float32Array, Float64Array];
1056
- const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86];
1057
- for (let i = 0; i < typedArrays.length; i++) {
1058
- registerTypedArray(typedArrays[i], typedArrayTags[i]);
1059
- }
1060
- function registerTypedArray(TypedArray, tag) {
1061
- let dvMethod = 'get' + TypedArray.name.slice(0, -5);
1062
- let bytesPerElement;
1063
- if (typeof TypedArray === 'function')
1064
- bytesPerElement = TypedArray.BYTES_PER_ELEMENT;
1065
- else
1066
- TypedArray = null;
1067
- for (let littleEndian = 0; littleEndian < 2; littleEndian++) {
1068
- if (!littleEndian && bytesPerElement == 1)
1069
- continue
1070
- let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : bytesPerElement == 8 ? 3 : 0;
1071
- currentExtensions[littleEndian ? tag : (tag - 4)] = (bytesPerElement == 1 || littleEndian == isLittleEndianMachine$1) ? (buffer) => {
1072
- if (!TypedArray)
1073
- throw new Error('Could not find typed array for code ' + tag)
1074
- if (!currentDecoder.copyBuffers) {
1075
- // try provide a direct view, but will only work if we are byte-aligned
1076
- if (bytesPerElement === 1 ||
1077
- bytesPerElement === 2 && !(buffer.byteOffset & 1) ||
1078
- bytesPerElement === 4 && !(buffer.byteOffset & 3) ||
1079
- bytesPerElement === 8 && !(buffer.byteOffset & 7))
1080
- return new TypedArray(buffer.buffer, buffer.byteOffset, buffer.byteLength >> sizeShift);
1081
- }
1082
- // we have to slice/copy here to get a new ArrayBuffer, if we are not word/byte aligned
1083
- return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer)
1084
- } : buffer => {
1085
- if (!TypedArray)
1086
- throw new Error('Could not find typed array for code ' + tag)
1087
- let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1088
- let elements = buffer.length >> sizeShift;
1089
- let ta = new TypedArray(elements);
1090
- let method = dv[dvMethod];
1091
- for (let i = 0; i < elements; i++) {
1092
- ta[i] = method.call(dv, i << sizeShift, littleEndian);
1093
- }
1094
- return ta
1095
- };
1096
- }
1097
- }
1098
-
1099
- function readBundleExt() {
1100
- let length = readJustLength();
1101
- let bundlePosition = position$1 + read();
1102
- for (let i = 2; i < length; i++) {
1103
- // skip past bundles that were already read
1104
- let bundleLength = readJustLength(); // this will increment position, so must add to position afterwards
1105
- position$1 += bundleLength;
1106
- }
1107
- let dataPosition = position$1;
1108
- position$1 = bundlePosition;
1109
- bundledStrings$1 = [readStringJS(readJustLength()), readStringJS(readJustLength())];
1110
- bundledStrings$1.position0 = 0;
1111
- bundledStrings$1.position1 = 0;
1112
- bundledStrings$1.postBundlePosition = position$1;
1113
- position$1 = dataPosition;
1114
- return read()
1115
- }
1116
-
1117
- function readJustLength() {
1118
- let token = src[position$1++] & 0x1f;
1119
- if (token > 0x17) {
1120
- switch (token) {
1121
- case 0x18:
1122
- token = src[position$1++];
1123
- break
1124
- case 0x19:
1125
- token = dataView.getUint16(position$1);
1126
- position$1 += 2;
1127
- break
1128
- case 0x1a:
1129
- token = dataView.getUint32(position$1);
1130
- position$1 += 4;
1131
- break
1132
- }
1133
- }
1134
- return token
1135
- }
1136
-
1137
- function loadShared() {
1138
- if (currentDecoder.getShared) {
1139
- let sharedData = saveState(() => {
1140
- // save the state in case getShared modifies our buffer
1141
- src = null;
1142
- return currentDecoder.getShared()
1143
- }) || {};
1144
- let updatedStructures = sharedData.structures || [];
1145
- currentDecoder.sharedVersion = sharedData.version;
1146
- packedValues = currentDecoder.sharedValues = sharedData.packedValues;
1147
- if (currentStructures === true)
1148
- currentDecoder.structures = currentStructures = updatedStructures;
1149
- else
1150
- currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures));
1151
- }
1152
- }
1153
-
1154
- function saveState(callback) {
1155
- let savedSrcEnd = srcEnd;
1156
- let savedPosition = position$1;
1157
- let savedStringPosition = stringPosition;
1158
- let savedSrcStringStart = srcStringStart;
1159
- let savedSrcStringEnd = srcStringEnd;
1160
- let savedSrcString = srcString;
1161
- let savedStrings = strings;
1162
- let savedReferenceMap = referenceMap;
1163
- let savedBundledStrings = bundledStrings$1;
1164
-
1165
- // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
1166
- let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
1167
- let savedStructures = currentStructures;
1168
- let savedDecoder = currentDecoder;
1169
- let savedSequentialMode = sequentialMode;
1170
- let value = callback();
1171
- srcEnd = savedSrcEnd;
1172
- position$1 = savedPosition;
1173
- stringPosition = savedStringPosition;
1174
- srcStringStart = savedSrcStringStart;
1175
- srcStringEnd = savedSrcStringEnd;
1176
- srcString = savedSrcString;
1177
- strings = savedStrings;
1178
- referenceMap = savedReferenceMap;
1179
- bundledStrings$1 = savedBundledStrings;
1180
- src = savedSrc;
1181
- sequentialMode = savedSequentialMode;
1182
- currentStructures = savedStructures;
1183
- currentDecoder = savedDecoder;
1184
- dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1185
- return value
1186
- }
1187
- function clearSource() {
1188
- src = null;
1189
- referenceMap = null;
1190
- currentStructures = null;
1191
- }
1192
-
1193
- function addExtension$1(extension) {
1194
- currentExtensions[extension.tag] = extension.decode;
1195
- }
1196
-
1197
- function setSizeLimits(limits) {
1198
- if (limits.maxMapSize) maxMapSize = limits.maxMapSize;
1199
- if (limits.maxArraySize) maxArraySize = limits.maxArraySize;
1200
- if (limits.maxObjectSize) limits.maxObjectSize;
1201
- }
1202
-
1203
- const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1204
- for (let i = 0; i < 256; i++) {
1205
- mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1206
- }
1207
- let defaultDecoder = new Decoder({ useRecords: false });
1208
- const decode = defaultDecoder.decode;
1209
- const decodeMultiple = defaultDecoder.decodeMultiple;
1210
- const FLOAT32_OPTIONS = {
1211
- NEVER: 0,
1212
- ALWAYS: 1,
1213
- DECIMAL_ROUND: 3,
1214
- DECIMAL_FIT: 4
1215
- };
1216
- function roundFloat32(float32Number) {
1217
- f32Array[0] = float32Number;
1218
- let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1219
- return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
1220
- }
1221
-
1222
- let textEncoder;
1223
- try {
1224
- textEncoder = new TextEncoder();
1225
- } catch (error) {}
1226
- let extensions, extensionClasses;
1227
- const Buffer$1 = typeof globalThis === 'object' && globalThis.Buffer;
1228
- const hasNodeBuffer = typeof Buffer$1 !== 'undefined';
1229
- const ByteArrayAllocate = hasNodeBuffer ? Buffer$1.allocUnsafeSlow : Uint8Array;
1230
- const ByteArray = hasNodeBuffer ? Buffer$1 : Uint8Array;
1231
- const MAX_STRUCTURES = 0x100;
1232
- const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1233
- let throwOnIterable;
1234
- let target;
1235
- let targetView;
1236
- let position = 0;
1237
- let safeEnd;
1238
- let bundledStrings = null;
1239
- const MAX_BUNDLE_SIZE = 0xf000;
1240
- const hasNonLatin = /[\u0080-\uFFFF]/;
1241
- const RECORD_SYMBOL = Symbol('record-id');
1242
- class Encoder extends Decoder {
1243
- constructor(options) {
1244
- super(options);
1245
- this.offset = 0;
1246
- let start;
1247
- let sharedStructures;
1248
- let hasSharedUpdate;
1249
- let structures;
1250
- let referenceMap;
1251
- options = options || {};
1252
- let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position, maxBytes) {
1253
- return target.utf8Write(string, position, maxBytes)
1254
- } : (textEncoder && textEncoder.encodeInto) ?
1255
- function(string, position) {
1256
- return textEncoder.encodeInto(string, target.subarray(position)).written
1257
- } : false;
1258
-
1259
- let encoder = this;
1260
- let hasSharedStructures = options.structures || options.saveStructures;
1261
- let maxSharedStructures = options.maxSharedStructures;
1262
- if (maxSharedStructures == null)
1263
- maxSharedStructures = hasSharedStructures ? 128 : 0;
1264
- if (maxSharedStructures > 8190)
1265
- throw new Error('Maximum maxSharedStructure is 8190')
1266
- let isSequential = options.sequential;
1267
- if (isSequential) {
1268
- maxSharedStructures = 0;
1269
- }
1270
- if (!this.structures)
1271
- this.structures = [];
1272
- if (this.saveStructures)
1273
- this.saveShared = this.saveStructures;
1274
- let samplingPackedValues, packedObjectMap, sharedValues = options.sharedValues;
1275
- let sharedPackedObjectMap;
1276
- if (sharedValues) {
1277
- sharedPackedObjectMap = Object.create(null);
1278
- for (let i = 0, l = sharedValues.length; i < l; i++) {
1279
- sharedPackedObjectMap[sharedValues[i]] = i;
1280
- }
1281
- }
1282
- let recordIdsToRemove = [];
1283
- let transitionsCount = 0;
1284
- let serializationsSinceTransitionRebuild = 0;
1285
-
1286
- this.mapEncode = function(value, encodeOptions) {
1287
- // Experimental support for premapping keys using _keyMap instad of keyMap - not optiimised yet)
1288
- if (this._keyMap && !this._mapped) {
1289
- //console.log('encoding ', value)
1290
- switch (value.constructor.name) {
1291
- case 'Array':
1292
- value = value.map(r => this.encodeKeys(r));
1293
- break
1294
- //case 'Map':
1295
- // value = this.encodeKeys(value)
1296
- // break
1297
- }
1298
- //this._mapped = true
1299
- }
1300
- return this.encode(value, encodeOptions)
1301
- };
1302
-
1303
- this.encode = function(value, encodeOptions) {
1304
- if (!target) {
1305
- target = new ByteArrayAllocate(8192);
1306
- targetView = new DataView(target.buffer, 0, 8192);
1307
- position = 0;
1308
- }
1309
- safeEnd = target.length - 10;
1310
- if (safeEnd - position < 0x800) {
1311
- // don't start too close to the end,
1312
- target = new ByteArrayAllocate(target.length);
1313
- targetView = new DataView(target.buffer, 0, target.length);
1314
- safeEnd = target.length - 10;
1315
- position = 0;
1316
- } else if (encodeOptions === REUSE_BUFFER_MODE)
1317
- position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1318
- start = position;
1319
- if (encoder.useSelfDescribedHeader) {
1320
- targetView.setUint32(position, 0xd9d9f700); // tag two byte, then self-descriptive tag
1321
- position += 3;
1322
- }
1323
- referenceMap = encoder.structuredClone ? new Map() : null;
1324
- if (encoder.bundleStrings && typeof value !== 'string') {
1325
- bundledStrings = [];
1326
- bundledStrings.size = Infinity; // force a new bundle start on first string
1327
- } else
1328
- bundledStrings = null;
1329
-
1330
- sharedStructures = encoder.structures;
1331
- if (sharedStructures) {
1332
- if (sharedStructures.uninitialized) {
1333
- let sharedData = encoder.getShared() || {};
1334
- encoder.structures = sharedStructures = sharedData.structures || [];
1335
- encoder.sharedVersion = sharedData.version;
1336
- let sharedValues = encoder.sharedValues = sharedData.packedValues;
1337
- if (sharedValues) {
1338
- sharedPackedObjectMap = {};
1339
- for (let i = 0, l = sharedValues.length; i < l; i++)
1340
- sharedPackedObjectMap[sharedValues[i]] = i;
1341
- }
1342
- }
1343
- let sharedStructuresLength = sharedStructures.length;
1344
- if (sharedStructuresLength > maxSharedStructures && !isSequential)
1345
- sharedStructuresLength = maxSharedStructures;
1346
- if (!sharedStructures.transitions) {
1347
- // rebuild our structure transitions
1348
- sharedStructures.transitions = Object.create(null);
1349
- for (let i = 0; i < sharedStructuresLength; i++) {
1350
- let keys = sharedStructures[i];
1351
- //console.log('shared struct keys:', keys)
1352
- if (!keys)
1353
- continue
1354
- let nextTransition, transition = sharedStructures.transitions;
1355
- for (let j = 0, l = keys.length; j < l; j++) {
1356
- if (transition[RECORD_SYMBOL] === undefined)
1357
- transition[RECORD_SYMBOL] = i;
1358
- let key = keys[j];
1359
- nextTransition = transition[key];
1360
- if (!nextTransition) {
1361
- nextTransition = transition[key] = Object.create(null);
1362
- }
1363
- transition = nextTransition;
1364
- }
1365
- transition[RECORD_SYMBOL] = i | 0x100000;
1366
- }
1367
- }
1368
- if (!isSequential)
1369
- sharedStructures.nextId = sharedStructuresLength;
1370
- }
1371
- if (hasSharedUpdate)
1372
- hasSharedUpdate = false;
1373
- structures = sharedStructures || [];
1374
- packedObjectMap = sharedPackedObjectMap;
1375
- if (options.pack) {
1376
- let packedValues = new Map();
1377
- packedValues.values = [];
1378
- packedValues.encoder = encoder;
1379
- packedValues.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap ? 16 : Infinity);
1380
- packedValues.objectMap = sharedPackedObjectMap || false;
1381
- packedValues.samplingPackedValues = samplingPackedValues;
1382
- findRepetitiveStrings(value, packedValues);
1383
- if (packedValues.values.length > 0) {
1384
- target[position++] = 0xd8; // one-byte tag
1385
- target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1386
- writeArrayHeader(4);
1387
- let valuesArray = packedValues.values;
1388
- encode(valuesArray);
1389
- writeArrayHeader(0); // prefixes
1390
- writeArrayHeader(0); // suffixes
1391
- packedObjectMap = Object.create(sharedPackedObjectMap || null);
1392
- for (let i = 0, l = valuesArray.length; i < l; i++) {
1393
- packedObjectMap[valuesArray[i]] = i;
1394
- }
1395
- }
1396
- }
1397
- throwOnIterable = encodeOptions & THROW_ON_ITERABLE;
1398
- try {
1399
- if (throwOnIterable)
1400
- return;
1401
- encode(value);
1402
- if (bundledStrings) {
1403
- writeBundles(start, encode);
1404
- }
1405
- encoder.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1406
- if (referenceMap && referenceMap.idsToInsert) {
1407
- position += referenceMap.idsToInsert.length * 2;
1408
- if (position > safeEnd)
1409
- makeRoom(position);
1410
- encoder.offset = position;
1411
- let serialized = insertIds(target.subarray(start, position), referenceMap.idsToInsert);
1412
- referenceMap = null;
1413
- return serialized
1414
- }
1415
- if (encodeOptions & REUSE_BUFFER_MODE) {
1416
- target.start = start;
1417
- target.end = position;
1418
- return target
1419
- }
1420
- return target.subarray(start, position) // position can change if we call encode again in saveShared, so we get the buffer now
1421
- } finally {
1422
- if (sharedStructures) {
1423
- if (serializationsSinceTransitionRebuild < 10)
1424
- serializationsSinceTransitionRebuild++;
1425
- if (sharedStructures.length > maxSharedStructures)
1426
- sharedStructures.length = maxSharedStructures;
1427
- if (transitionsCount > 10000) {
1428
- // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1429
- sharedStructures.transitions = null;
1430
- serializationsSinceTransitionRebuild = 0;
1431
- transitionsCount = 0;
1432
- if (recordIdsToRemove.length > 0)
1433
- recordIdsToRemove = [];
1434
- } else if (recordIdsToRemove.length > 0 && !isSequential) {
1435
- for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1436
- recordIdsToRemove[i][RECORD_SYMBOL] = undefined;
1437
- }
1438
- recordIdsToRemove = [];
1439
- //sharedStructures.nextId = maxSharedStructures
1440
- }
1441
- }
1442
- if (hasSharedUpdate && encoder.saveShared) {
1443
- if (encoder.structures.length > maxSharedStructures) {
1444
- encoder.structures = encoder.structures.slice(0, maxSharedStructures);
1445
- }
1446
- // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1447
- let returnBuffer = target.subarray(start, position);
1448
- if (encoder.updateSharedData() === false)
1449
- return encoder.encode(value) // re-encode if it fails
1450
- return returnBuffer
1451
- }
1452
- if (encodeOptions & RESET_BUFFER_MODE)
1453
- position = start;
1454
- }
1455
- };
1456
- this.findCommonStringsToPack = () => {
1457
- samplingPackedValues = new Map();
1458
- if (!sharedPackedObjectMap)
1459
- sharedPackedObjectMap = Object.create(null);
1460
- return (options) => {
1461
- let threshold = options && options.threshold || 4;
1462
- let position = this.pack ? options.maxPrivatePackedValues || 16 : 0;
1463
- if (!sharedValues)
1464
- sharedValues = this.sharedValues = [];
1465
- for (let [ key, status ] of samplingPackedValues) {
1466
- if (status.count > threshold) {
1467
- sharedPackedObjectMap[key] = position++;
1468
- sharedValues.push(key);
1469
- hasSharedUpdate = true;
1470
- }
1471
- }
1472
- while (this.saveShared && this.updateSharedData() === false) {}
1473
- samplingPackedValues = null;
1474
- }
1475
- };
1476
- const encode = (value) => {
1477
- if (position > safeEnd)
1478
- target = makeRoom(position);
1479
-
1480
- var type = typeof value;
1481
- var length;
1482
- if (type === 'string') {
1483
- if (packedObjectMap) {
1484
- let packedPosition = packedObjectMap[value];
1485
- if (packedPosition >= 0) {
1486
- if (packedPosition < 16)
1487
- target[position++] = packedPosition + 0xe0; // simple values, defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1488
- else {
1489
- target[position++] = 0xc6; // tag 6 defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1490
- if (packedPosition & 1)
1491
- encode((15 - packedPosition) >> 1);
1492
- else
1493
- encode((packedPosition - 16) >> 1);
1494
- }
1495
- return
1496
- /* } else if (packedStatus.serializationId != serializationId) {
1497
- packedStatus.serializationId = serializationId
1498
- packedStatus.count = 1
1499
- if (options.sharedPack) {
1500
- let sharedCount = packedStatus.sharedCount = (packedStatus.sharedCount || 0) + 1
1501
- if (shareCount > (options.sharedPack.threshold || 5)) {
1502
- let sharedPosition = packedStatus.position = packedStatus.nextSharedPosition
1503
- hasSharedUpdate = true
1504
- if (sharedPosition < 16)
1505
- target[position++] = sharedPosition + 0xc0
1506
-
1507
- }
1508
- }
1509
- } // else any in-doc incrementation?*/
1510
- } else if (samplingPackedValues && !options.pack) {
1511
- let status = samplingPackedValues.get(value);
1512
- if (status)
1513
- status.count++;
1514
- else
1515
- samplingPackedValues.set(value, {
1516
- count: 1,
1517
- });
1518
- }
1519
- }
1520
- let strLength = value.length;
1521
- if (bundledStrings && strLength >= 4 && strLength < 0x400) {
1522
- if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
1523
- let extStart;
1524
- let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
1525
- if (position + maxBytes > safeEnd)
1526
- target = makeRoom(position + maxBytes);
1527
- target[position++] = 0xd9; // tag 16-bit
1528
- target[position++] = 0xdf; // tag 0xdff9
1529
- target[position++] = 0xf9;
1530
- // TODO: If we only have one bundle with any string data, only write one string bundle
1531
- target[position++] = bundledStrings.position ? 0x84 : 0x82; // array of 4 or 2 elements depending on if we write bundles
1532
- target[position++] = 0x1a; // 32-bit unsigned int
1533
- extStart = position - start;
1534
- position += 4; // reserve for writing bundle reference
1535
- if (bundledStrings.position) {
1536
- writeBundles(start, encode); // write the last bundles
1537
- }
1538
- bundledStrings = ['', '']; // create new ones
1539
- bundledStrings.size = 0;
1540
- bundledStrings.position = extStart;
1541
- }
1542
- let twoByte = hasNonLatin.test(value);
1543
- bundledStrings[twoByte ? 0 : 1] += value;
1544
- target[position++] = twoByte ? 0xce : 0xcf;
1545
- encode(strLength);
1546
- return
1547
- }
1548
- let headerSize;
1549
- // first we estimate the header size, so we can write to the correct location
1550
- if (strLength < 0x20) {
1551
- headerSize = 1;
1552
- } else if (strLength < 0x100) {
1553
- headerSize = 2;
1554
- } else if (strLength < 0x10000) {
1555
- headerSize = 3;
1556
- } else {
1557
- headerSize = 5;
1558
- }
1559
- let maxBytes = strLength * 3;
1560
- if (position + maxBytes > safeEnd)
1561
- target = makeRoom(position + maxBytes);
1562
-
1563
- if (strLength < 0x40 || !encodeUtf8) {
1564
- let i, c1, c2, strPosition = position + headerSize;
1565
- for (i = 0; i < strLength; i++) {
1566
- c1 = value.charCodeAt(i);
1567
- if (c1 < 0x80) {
1568
- target[strPosition++] = c1;
1569
- } else if (c1 < 0x800) {
1570
- target[strPosition++] = c1 >> 6 | 0xc0;
1571
- target[strPosition++] = c1 & 0x3f | 0x80;
1572
- } else if (
1573
- (c1 & 0xfc00) === 0xd800 &&
1574
- ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1575
- ) {
1576
- c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1577
- i++;
1578
- target[strPosition++] = c1 >> 18 | 0xf0;
1579
- target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1580
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1581
- target[strPosition++] = c1 & 0x3f | 0x80;
1582
- } else {
1583
- target[strPosition++] = c1 >> 12 | 0xe0;
1584
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1585
- target[strPosition++] = c1 & 0x3f | 0x80;
1586
- }
1587
- }
1588
- length = strPosition - position - headerSize;
1589
- } else {
1590
- length = encodeUtf8(value, position + headerSize, maxBytes);
1591
- }
1592
-
1593
- if (length < 0x18) {
1594
- target[position++] = 0x60 | length;
1595
- } else if (length < 0x100) {
1596
- if (headerSize < 2) {
1597
- target.copyWithin(position + 2, position + 1, position + 1 + length);
1598
- }
1599
- target[position++] = 0x78;
1600
- target[position++] = length;
1601
- } else if (length < 0x10000) {
1602
- if (headerSize < 3) {
1603
- target.copyWithin(position + 3, position + 2, position + 2 + length);
1604
- }
1605
- target[position++] = 0x79;
1606
- target[position++] = length >> 8;
1607
- target[position++] = length & 0xff;
1608
- } else {
1609
- if (headerSize < 5) {
1610
- target.copyWithin(position + 5, position + 3, position + 3 + length);
1611
- }
1612
- target[position++] = 0x7a;
1613
- targetView.setUint32(position, length);
1614
- position += 4;
1615
- }
1616
- position += length;
1617
- } else if (type === 'number') {
1618
- if (!this.alwaysUseFloat && value >>> 0 === value) {// positive integer, 32-bit or less
1619
- // positive uint
1620
- if (value < 0x18) {
1621
- target[position++] = value;
1622
- } else if (value < 0x100) {
1623
- target[position++] = 0x18;
1624
- target[position++] = value;
1625
- } else if (value < 0x10000) {
1626
- target[position++] = 0x19;
1627
- target[position++] = value >> 8;
1628
- target[position++] = value & 0xff;
1629
- } else {
1630
- target[position++] = 0x1a;
1631
- targetView.setUint32(position, value);
1632
- position += 4;
1633
- }
1634
- } else if (!this.alwaysUseFloat && value >> 0 === value) { // negative integer
1635
- if (value >= -0x18) {
1636
- target[position++] = 0x1f - value;
1637
- } else if (value >= -0x100) {
1638
- target[position++] = 0x38;
1639
- target[position++] = ~value;
1640
- } else if (value >= -0x10000) {
1641
- target[position++] = 0x39;
1642
- targetView.setUint16(position, ~value);
1643
- position += 2;
1644
- } else {
1645
- target[position++] = 0x3a;
1646
- targetView.setUint32(position, ~value);
1647
- position += 4;
1648
- }
1649
- } else {
1650
- let useFloat32;
1651
- if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1652
- target[position++] = 0xfa;
1653
- targetView.setFloat32(position, value);
1654
- let xShifted;
1655
- if (useFloat32 < 4 ||
1656
- // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1657
- ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
1658
- position += 4;
1659
- return
1660
- } else
1661
- position--; // move back into position for writing a double
1662
- }
1663
- target[position++] = 0xfb;
1664
- targetView.setFloat64(position, value);
1665
- position += 8;
1666
- }
1667
- } else if (type === 'object') {
1668
- if (!value)
1669
- target[position++] = 0xf6;
1670
- else {
1671
- if (referenceMap) {
1672
- let referee = referenceMap.get(value);
1673
- if (referee) {
1674
- target[position++] = 0xd8;
1675
- target[position++] = 29; // http://cbor.schmorp.de/value-sharing
1676
- target[position++] = 0x19; // 16-bit uint
1677
- if (!referee.references) {
1678
- let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1679
- referee.references = [];
1680
- idsToInsert.push(referee);
1681
- }
1682
- referee.references.push(position - start);
1683
- position += 2; // TODO: also support 32-bit
1684
- return
1685
- } else
1686
- referenceMap.set(value, { offset: position - start });
1687
- }
1688
- let constructor = value.constructor;
1689
- if (constructor === Object) {
1690
- writeObject(value);
1691
- } else if (constructor === Array) {
1692
- length = value.length;
1693
- if (length < 0x18) {
1694
- target[position++] = 0x80 | length;
1695
- } else {
1696
- writeArrayHeader(length);
1697
- }
1698
- for (let i = 0; i < length; i++) {
1699
- encode(value[i]);
1700
- }
1701
- } else if (constructor === Map) {
1702
- if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) {
1703
- // use Tag 259 (https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec--explicit-maps.md) for maps if the user wants it that way
1704
- target[position++] = 0xd9;
1705
- target[position++] = 1;
1706
- target[position++] = 3;
1707
- }
1708
- length = value.size;
1709
- if (length < 0x18) {
1710
- target[position++] = 0xa0 | length;
1711
- } else if (length < 0x100) {
1712
- target[position++] = 0xb8;
1713
- target[position++] = length;
1714
- } else if (length < 0x10000) {
1715
- target[position++] = 0xb9;
1716
- target[position++] = length >> 8;
1717
- target[position++] = length & 0xff;
1718
- } else {
1719
- target[position++] = 0xba;
1720
- targetView.setUint32(position, length);
1721
- position += 4;
1722
- }
1723
- if (encoder.keyMap) {
1724
- for (let [ key, entryValue ] of value) {
1725
- encode(encoder.encodeKey(key));
1726
- encode(entryValue);
1727
- }
1728
- } else {
1729
- for (let [ key, entryValue ] of value) {
1730
- encode(key);
1731
- encode(entryValue);
1732
- }
1733
- }
1734
- } else {
1735
- for (let i = 0, l = extensions.length; i < l; i++) {
1736
- let extensionClass = extensionClasses[i];
1737
- if (value instanceof extensionClass) {
1738
- let extension = extensions[i];
1739
- let tag = extension.tag;
1740
- if (tag == undefined)
1741
- tag = extension.getTag && extension.getTag.call(this, value);
1742
- if (tag < 0x18) {
1743
- target[position++] = 0xc0 | tag;
1744
- } else if (tag < 0x100) {
1745
- target[position++] = 0xd8;
1746
- target[position++] = tag;
1747
- } else if (tag < 0x10000) {
1748
- target[position++] = 0xd9;
1749
- target[position++] = tag >> 8;
1750
- target[position++] = tag & 0xff;
1751
- } else if (tag > -1) {
1752
- target[position++] = 0xda;
1753
- targetView.setUint32(position, tag);
1754
- position += 4;
1755
- } // else undefined, don't write tag
1756
- extension.encode.call(this, value, encode, makeRoom);
1757
- return
1758
- }
1759
- }
1760
- if (value[Symbol.iterator]) {
1761
- if (throwOnIterable) {
1762
- let error = new Error('Iterable should be serialized as iterator');
1763
- error.iteratorNotHandled = true;
1764
- throw error;
1765
- }
1766
- target[position++] = 0x9f; // indefinite length array
1767
- for (let entry of value) {
1768
- encode(entry);
1769
- }
1770
- target[position++] = 0xff; // stop-code
1771
- return
1772
- }
1773
- if (value[Symbol.asyncIterator] || isBlob(value)) {
1774
- let error = new Error('Iterable/blob should be serialized as iterator');
1775
- error.iteratorNotHandled = true;
1776
- throw error;
1777
- }
1778
- if (this.useToJSON && value.toJSON) {
1779
- const json = value.toJSON();
1780
- // if for some reason value.toJSON returns itself it'll loop forever
1781
- if (json !== value)
1782
- return encode(json)
1783
- }
1784
-
1785
- // no extension found, write as a plain object
1786
- writeObject(value);
1787
- }
1788
- }
1789
- } else if (type === 'boolean') {
1790
- target[position++] = value ? 0xf5 : 0xf4;
1791
- } else if (type === 'bigint') {
1792
- if (value < (BigInt(1)<<BigInt(64)) && value >= 0) {
1793
- // use an unsigned int as long as it fits
1794
- target[position++] = 0x1b;
1795
- targetView.setBigUint64(position, value);
1796
- } else if (value > -(BigInt(1)<<BigInt(64)) && value < 0) {
1797
- // if we can fit an unsigned int, use that
1798
- target[position++] = 0x3b;
1799
- targetView.setBigUint64(position, -value - BigInt(1));
1800
- } else {
1801
- // overflow
1802
- if (this.largeBigIntToFloat) {
1803
- target[position++] = 0xfb;
1804
- targetView.setFloat64(position, Number(value));
1805
- } else {
1806
- if (value >= BigInt(0))
1807
- target[position++] = 0xc2; // tag 2
1808
- else {
1809
- target[position++] = 0xc3; // tag 2
1810
- value = BigInt(-1) - value;
1811
- }
1812
- let bytes = [];
1813
- while (value) {
1814
- bytes.push(Number(value & BigInt(0xff)));
1815
- value >>= BigInt(8);
1816
- }
1817
- writeBuffer(new Uint8Array(bytes.reverse()), makeRoom);
1818
- return;
1819
- }
1820
- }
1821
- position += 8;
1822
- } else if (type === 'undefined') {
1823
- target[position++] = 0xf7;
1824
- } else {
1825
- throw new Error('Unknown type: ' + type)
1826
- }
1827
- };
1828
-
1829
- const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1830
- // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1831
- let keys = Object.keys(object);
1832
- let vals = Object.values(object);
1833
- let length = keys.length;
1834
- if (length < 0x18) {
1835
- target[position++] = 0xa0 | length;
1836
- } else if (length < 0x100) {
1837
- target[position++] = 0xb8;
1838
- target[position++] = length;
1839
- } else if (length < 0x10000) {
1840
- target[position++] = 0xb9;
1841
- target[position++] = length >> 8;
1842
- target[position++] = length & 0xff;
1843
- } else {
1844
- target[position++] = 0xba;
1845
- targetView.setUint32(position, length);
1846
- position += 4;
1847
- }
1848
- if (encoder.keyMap) {
1849
- for (let i = 0; i < length; i++) {
1850
- encode(encoder.encodeKey(keys[i]));
1851
- encode(vals[i]);
1852
- }
1853
- } else {
1854
- for (let i = 0; i < length; i++) {
1855
- encode(keys[i]);
1856
- encode(vals[i]);
1857
- }
1858
- }
1859
- } :
1860
- (object) => {
1861
- target[position++] = 0xb9; // always use map 16, so we can preallocate and set the length afterwards
1862
- let objectOffset = position - start;
1863
- position += 2;
1864
- let size = 0;
1865
- if (encoder.keyMap) {
1866
- for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
1867
- encode(encoder.encodeKey(key));
1868
- encode(object[key]);
1869
- size++;
1870
- }
1871
- } else {
1872
- for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
1873
- encode(key);
1874
- encode(object[key]);
1875
- size++;
1876
- }
1877
- }
1878
- target[objectOffset++ + start] = size >> 8;
1879
- target[objectOffset + start] = size & 0xff;
1880
- } :
1881
- (object, skipValues) => {
1882
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1883
- let newTransitions = 0;
1884
- let length = 0;
1885
- let parentRecordId;
1886
- let keys;
1887
- if (this.keyMap) {
1888
- keys = Object.keys(object).map(k => this.encodeKey(k));
1889
- length = keys.length;
1890
- for (let i = 0; i < length; i++) {
1891
- let key = keys[i];
1892
- nextTransition = transition[key];
1893
- if (!nextTransition) {
1894
- nextTransition = transition[key] = Object.create(null);
1895
- newTransitions++;
1896
- }
1897
- transition = nextTransition;
1898
- }
1899
- } else {
1900
- for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
1901
- nextTransition = transition[key];
1902
- if (!nextTransition) {
1903
- if (transition[RECORD_SYMBOL] & 0x100000) {// this indicates it is a brancheable/extendable terminal node, so we will use this record id and extend it
1904
- parentRecordId = transition[RECORD_SYMBOL] & 0xffff;
1905
- }
1906
- nextTransition = transition[key] = Object.create(null);
1907
- newTransitions++;
1908
- }
1909
- transition = nextTransition;
1910
- length++;
1911
- }
1912
- }
1913
- let recordId = transition[RECORD_SYMBOL];
1914
- if (recordId !== undefined) {
1915
- recordId &= 0xffff;
1916
- target[position++] = 0xd9;
1917
- target[position++] = (recordId >> 8) | 0xe0;
1918
- target[position++] = recordId & 0xff;
1919
- } else {
1920
- if (!keys)
1921
- keys = transition.__keys__ || (transition.__keys__ = Object.keys(object));
1922
- if (parentRecordId === undefined) {
1923
- recordId = structures.nextId++;
1924
- if (!recordId) {
1925
- recordId = 0;
1926
- structures.nextId = 1;
1927
- }
1928
- if (recordId >= MAX_STRUCTURES) {// cycle back around
1929
- structures.nextId = (recordId = maxSharedStructures) + 1;
1930
- }
1931
- } else {
1932
- recordId = parentRecordId;
1933
- }
1934
- structures[recordId] = keys;
1935
- if (recordId < maxSharedStructures) {
1936
- target[position++] = 0xd9;
1937
- target[position++] = (recordId >> 8) | 0xe0;
1938
- target[position++] = recordId & 0xff;
1939
- transition = structures.transitions;
1940
- for (let i = 0; i < length; i++) {
1941
- if (transition[RECORD_SYMBOL] === undefined || (transition[RECORD_SYMBOL] & 0x100000))
1942
- transition[RECORD_SYMBOL] = recordId;
1943
- transition = transition[keys[i]];
1944
- }
1945
- transition[RECORD_SYMBOL] = recordId | 0x100000; // indicates it is a extendable terminal
1946
- hasSharedUpdate = true;
1947
- } else {
1948
- transition[RECORD_SYMBOL] = recordId;
1949
- targetView.setUint32(position, 0xd9dfff00); // tag two byte, then record definition id
1950
- position += 3;
1951
- if (newTransitions)
1952
- transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1953
- // record the removal of the id, we can maintain our shared structure
1954
- if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures)
1955
- recordIdsToRemove.shift()[RECORD_SYMBOL] = undefined; // we are cycling back through, and have to remove old ones
1956
- recordIdsToRemove.push(transition);
1957
- writeArrayHeader(length + 2);
1958
- encode(0xe000 + recordId);
1959
- encode(keys);
1960
- if (skipValues) return; // special exit for iterator
1961
- for (let key in object)
1962
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key))
1963
- encode(object[key]);
1964
- return
1965
- }
1966
- }
1967
- if (length < 0x18) { // write the array header
1968
- target[position++] = 0x80 | length;
1969
- } else {
1970
- writeArrayHeader(length);
1971
- }
1972
- if (skipValues) return; // special exit for iterator
1973
- for (let key in object)
1974
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key))
1975
- encode(object[key]);
1976
- };
1977
- const makeRoom = (end) => {
1978
- let newSize;
1979
- if (end > 0x1000000) {
1980
- // special handling for really large buffers
1981
- if ((end - start) > MAX_BUFFER_SIZE)
1982
- throw new Error('Encoded buffer would be larger than maximum buffer size')
1983
- newSize = Math.min(MAX_BUFFER_SIZE,
1984
- Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1985
- } else // faster handling for smaller buffers
1986
- newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1987
- let newBuffer = new ByteArrayAllocate(newSize);
1988
- targetView = new DataView(newBuffer.buffer, 0, newSize);
1989
- if (target.copy)
1990
- target.copy(newBuffer, 0, start, end);
1991
- else
1992
- newBuffer.set(target.slice(start, end));
1993
- position -= start;
1994
- start = 0;
1995
- safeEnd = newBuffer.length - 10;
1996
- return target = newBuffer
1997
- };
1998
- let chunkThreshold = 100;
1999
- let continuedChunkThreshold = 1000;
2000
- this.encodeAsIterable = function(value, options) {
2001
- return startEncoding(value, options, encodeObjectAsIterable);
2002
- };
2003
- this.encodeAsAsyncIterable = function(value, options) {
2004
- return startEncoding(value, options, encodeObjectAsAsyncIterable);
2005
- };
2006
-
2007
- function* encodeObjectAsIterable(object, iterateProperties, finalIterable) {
2008
- let constructor = object.constructor;
2009
- if (constructor === Object) {
2010
- let useRecords = encoder.useRecords !== false;
2011
- if (useRecords)
2012
- writeObject(object, true); // write the record identifier
2013
- else
2014
- writeEntityLength(Object.keys(object).length, 0xa0);
2015
- for (let key in object) {
2016
- let value = object[key];
2017
- if (!useRecords) encode(key);
2018
- if (value && typeof value === 'object') {
2019
- if (iterateProperties[key])
2020
- yield* encodeObjectAsIterable(value, iterateProperties[key]);
2021
- else
2022
- yield* tryEncode(value, iterateProperties, key);
2023
- } else encode(value);
2024
- }
2025
- } else if (constructor === Array) {
2026
- let length = object.length;
2027
- writeArrayHeader(length);
2028
- for (let i = 0; i < length; i++) {
2029
- let value = object[i];
2030
- if (value && (typeof value === 'object' || position - start > chunkThreshold)) {
2031
- if (iterateProperties.element)
2032
- yield* encodeObjectAsIterable(value, iterateProperties.element);
2033
- else
2034
- yield* tryEncode(value, iterateProperties, 'element');
2035
- } else encode(value);
2036
- }
2037
- } else if (object[Symbol.iterator] && !object.buffer) { // iterator, but exclude typed arrays
2038
- target[position++] = 0x9f; // start indefinite array
2039
- for (let value of object) {
2040
- if (value && (typeof value === 'object' || position - start > chunkThreshold)) {
2041
- if (iterateProperties.element)
2042
- yield* encodeObjectAsIterable(value, iterateProperties.element);
2043
- else
2044
- yield* tryEncode(value, iterateProperties, 'element');
2045
- } else encode(value);
2046
- }
2047
- target[position++] = 0xff; // stop byte
2048
- } else if (isBlob(object)){
2049
- writeEntityLength(object.size, 0x40); // encode as binary data
2050
- yield target.subarray(start, position);
2051
- yield object; // directly return blobs, they have to be encoded asynchronously
2052
- restartEncoding();
2053
- } else if (object[Symbol.asyncIterator]) {
2054
- target[position++] = 0x9f; // start indefinite array
2055
- yield target.subarray(start, position);
2056
- yield object; // directly return async iterators, they have to be encoded asynchronously
2057
- restartEncoding();
2058
- target[position++] = 0xff; // stop byte
2059
- } else {
2060
- encode(object);
2061
- }
2062
- if (finalIterable && position > start) yield target.subarray(start, position);
2063
- else if (position - start > chunkThreshold) {
2064
- yield target.subarray(start, position);
2065
- restartEncoding();
2066
- }
2067
- }
2068
- function* tryEncode(value, iterateProperties, key) {
2069
- let restart = position - start;
2070
- try {
2071
- encode(value);
2072
- if (position - start > chunkThreshold) {
2073
- yield target.subarray(start, position);
2074
- restartEncoding();
2075
- }
2076
- } catch (error) {
2077
- if (error.iteratorNotHandled) {
2078
- iterateProperties[key] = {};
2079
- position = start + restart; // restart our position so we don't have partial data from last encode
2080
- yield* encodeObjectAsIterable.call(this, value, iterateProperties[key]);
2081
- } else throw error;
2082
- }
2083
- }
2084
- function restartEncoding() {
2085
- chunkThreshold = continuedChunkThreshold;
2086
- encoder.encode(null, THROW_ON_ITERABLE); // restart encoding
2087
- }
2088
- function startEncoding(value, options, encodeIterable) {
2089
- if (options && options.chunkThreshold) // explicitly specified chunk sizes
2090
- chunkThreshold = continuedChunkThreshold = options.chunkThreshold;
2091
- else // we start with a smaller threshold to get initial bytes sent quickly
2092
- chunkThreshold = 100;
2093
- if (value && typeof value === 'object') {
2094
- encoder.encode(null, THROW_ON_ITERABLE); // start encoding
2095
- return encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true);
2096
- }
2097
- return [encoder.encode(value)];
2098
- }
2099
-
2100
- async function* encodeObjectAsAsyncIterable(value, iterateProperties) {
2101
- for (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) {
2102
- let constructor = encodedValue.constructor;
2103
- if (constructor === ByteArray || constructor === Uint8Array)
2104
- yield encodedValue;
2105
- else if (isBlob(encodedValue)) {
2106
- let reader = encodedValue.stream().getReader();
2107
- let next;
2108
- while (!(next = await reader.read()).done) {
2109
- yield next.value;
2110
- }
2111
- } else if (encodedValue[Symbol.asyncIterator]) {
2112
- for await (let asyncValue of encodedValue) {
2113
- restartEncoding();
2114
- if (asyncValue)
2115
- yield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {}));
2116
- else yield encoder.encode(asyncValue);
2117
- }
2118
- } else {
2119
- yield encodedValue;
2120
- }
2121
- }
2122
- }
2123
- }
2124
- useBuffer(buffer) {
2125
- // this means we are finished using our own buffer and we can write over it safely
2126
- target = buffer;
2127
- targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
2128
- position = 0;
2129
- }
2130
- clearSharedData() {
2131
- if (this.structures)
2132
- this.structures = [];
2133
- if (this.sharedValues)
2134
- this.sharedValues = undefined;
2135
- }
2136
- updateSharedData() {
2137
- let lastVersion = this.sharedVersion || 0;
2138
- this.sharedVersion = lastVersion + 1;
2139
- let structuresCopy = this.structures.slice(0);
2140
- let sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion);
2141
- let saveResults = this.saveShared(sharedData,
2142
- existingShared => (existingShared && existingShared.version || 0) == lastVersion);
2143
- if (saveResults === false) {
2144
- // get updated structures and try again if the update failed
2145
- sharedData = this.getShared() || {};
2146
- this.structures = sharedData.structures || [];
2147
- this.sharedValues = sharedData.packedValues;
2148
- this.sharedVersion = sharedData.version;
2149
- this.structures.nextId = this.structures.length;
2150
- } else {
2151
- // restore structures
2152
- structuresCopy.forEach((structure, i) => this.structures[i] = structure);
2153
- }
2154
- // saveShared may fail to write and reload, or may have reloaded to check compatibility and overwrite saved data, either way load the correct shared data
2155
- return saveResults
2156
- }
2157
- }
2158
- function writeEntityLength(length, majorValue) {
2159
- if (length < 0x18)
2160
- target[position++] = majorValue | length;
2161
- else if (length < 0x100) {
2162
- target[position++] = majorValue | 0x18;
2163
- target[position++] = length;
2164
- } else if (length < 0x10000) {
2165
- target[position++] = majorValue | 0x19;
2166
- target[position++] = length >> 8;
2167
- target[position++] = length & 0xff;
2168
- } else {
2169
- target[position++] = majorValue | 0x1a;
2170
- targetView.setUint32(position, length);
2171
- position += 4;
2172
- }
2173
-
2174
- }
2175
- class SharedData {
2176
- constructor(structures, values, version) {
2177
- this.structures = structures;
2178
- this.packedValues = values;
2179
- this.version = version;
2180
- }
2181
- }
2182
-
2183
- function writeArrayHeader(length) {
2184
- if (length < 0x18)
2185
- target[position++] = 0x80 | length;
2186
- else if (length < 0x100) {
2187
- target[position++] = 0x98;
2188
- target[position++] = length;
2189
- } else if (length < 0x10000) {
2190
- target[position++] = 0x99;
2191
- target[position++] = length >> 8;
2192
- target[position++] = length & 0xff;
2193
- } else {
2194
- target[position++] = 0x9a;
2195
- targetView.setUint32(position, length);
2196
- position += 4;
2197
- }
2198
- }
2199
-
2200
- const BlobConstructor = typeof Blob === 'undefined' ? function(){} : Blob;
2201
- function isBlob(object) {
2202
- if (object instanceof BlobConstructor)
2203
- return true;
2204
- let tag = object[Symbol.toStringTag];
2205
- return tag === 'Blob' || tag === 'File';
2206
- }
2207
- function findRepetitiveStrings(value, packedValues) {
2208
- switch(typeof value) {
2209
- case 'string':
2210
- if (value.length > 3) {
2211
- if (packedValues.objectMap[value] > -1 || packedValues.values.length >= packedValues.maxValues)
2212
- return
2213
- let packedStatus = packedValues.get(value);
2214
- if (packedStatus) {
2215
- if (++packedStatus.count == 2) {
2216
- packedValues.values.push(value);
2217
- }
2218
- } else {
2219
- packedValues.set(value, {
2220
- count: 1,
2221
- });
2222
- if (packedValues.samplingPackedValues) {
2223
- let status = packedValues.samplingPackedValues.get(value);
2224
- if (status)
2225
- status.count++;
2226
- else
2227
- packedValues.samplingPackedValues.set(value, {
2228
- count: 1,
2229
- });
2230
- }
2231
- }
2232
- }
2233
- break
2234
- case 'object':
2235
- if (value) {
2236
- if (value instanceof Array) {
2237
- for (let i = 0, l = value.length; i < l; i++) {
2238
- findRepetitiveStrings(value[i], packedValues);
2239
- }
2240
-
2241
- } else {
2242
- let includeKeys = !packedValues.encoder.useRecords;
2243
- for (var key in value) {
2244
- if (value.hasOwnProperty(key)) {
2245
- if (includeKeys)
2246
- findRepetitiveStrings(key, packedValues);
2247
- findRepetitiveStrings(value[key], packedValues);
2248
- }
2249
- }
2250
- }
2251
- }
2252
- break
2253
- case 'function': console.log(value);
2254
- }
2255
- }
2256
- const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
2257
- extensionClasses = [ Date, Set, Error, RegExp, Tag, ArrayBuffer,
2258
- Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
2259
- typeof BigUint64Array == 'undefined' ? function() {} : BigUint64Array, Int8Array, Int16Array, Int32Array,
2260
- typeof BigInt64Array == 'undefined' ? function() {} : BigInt64Array,
2261
- Float32Array, Float64Array, SharedData ];
2262
-
2263
- //Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/
2264
- extensions = [{ // Date
2265
- tag: 1,
2266
- encode(date, encode) {
2267
- let seconds = date.getTime() / 1000;
2268
- if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
2269
- // Timestamp 32
2270
- target[position++] = 0x1a;
2271
- targetView.setUint32(position, seconds);
2272
- position += 4;
2273
- } else {
2274
- // Timestamp float64
2275
- target[position++] = 0xfb;
2276
- targetView.setFloat64(position, seconds);
2277
- position += 8;
2278
- }
2279
- }
2280
- }, { // Set
2281
- tag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
2282
- encode(set, encode) {
2283
- let array = Array.from(set);
2284
- encode(array);
2285
- }
2286
- }, { // Error
2287
- tag: 27, // http://cbor.schmorp.de/generic-object
2288
- encode(error, encode) {
2289
- encode([ error.name, error.message ]);
2290
- }
2291
- }, { // RegExp
2292
- tag: 27, // http://cbor.schmorp.de/generic-object
2293
- encode(regex, encode) {
2294
- encode([ 'RegExp', regex.source, regex.flags ]);
2295
- }
2296
- }, { // Tag
2297
- getTag(tag) {
2298
- return tag.tag
2299
- },
2300
- encode(tag, encode) {
2301
- encode(tag.value);
2302
- }
2303
- }, { // ArrayBuffer
2304
- encode(arrayBuffer, encode, makeRoom) {
2305
- writeBuffer(arrayBuffer, makeRoom);
2306
- }
2307
- }, { // Uint8Array
2308
- getTag(typedArray) {
2309
- if (typedArray.constructor === Uint8Array) {
2310
- if (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false)
2311
- return 64;
2312
- } // else no tag
2313
- },
2314
- encode(typedArray, encode, makeRoom) {
2315
- writeBuffer(typedArray, makeRoom);
2316
- }
2317
- },
2318
- typedArrayEncoder(68, 1),
2319
- typedArrayEncoder(69, 2),
2320
- typedArrayEncoder(70, 4),
2321
- typedArrayEncoder(71, 8),
2322
- typedArrayEncoder(72, 1),
2323
- typedArrayEncoder(77, 2),
2324
- typedArrayEncoder(78, 4),
2325
- typedArrayEncoder(79, 8),
2326
- typedArrayEncoder(85, 4),
2327
- typedArrayEncoder(86, 8),
2328
- {
2329
- encode(sharedData, encode) { // write SharedData
2330
- let packedValues = sharedData.packedValues || [];
2331
- let sharedStructures = sharedData.structures || [];
2332
- if (packedValues.values.length > 0) {
2333
- target[position++] = 0xd8; // one-byte tag
2334
- target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
2335
- writeArrayHeader(4);
2336
- let valuesArray = packedValues.values;
2337
- encode(valuesArray);
2338
- writeArrayHeader(0); // prefixes
2339
- writeArrayHeader(0); // suffixes
2340
- packedObjectMap = Object.create(sharedPackedObjectMap || null);
2341
- for (let i = 0, l = valuesArray.length; i < l; i++) {
2342
- packedObjectMap[valuesArray[i]] = i;
2343
- }
2344
- }
2345
- if (sharedStructures) {
2346
- targetView.setUint32(position, 0xd9dffe00);
2347
- position += 3;
2348
- let definitions = sharedStructures.slice(0);
2349
- definitions.unshift(0xe000);
2350
- definitions.push(new Tag(sharedData.version, 0x53687264));
2351
- encode(definitions);
2352
- } else
2353
- encode(new Tag(sharedData.version, 0x53687264));
2354
- }
2355
- }];
2356
- function typedArrayEncoder(tag, size) {
2357
- if (!isLittleEndianMachine && size > 1)
2358
- tag -= 4; // the big endian equivalents are 4 less
2359
- return {
2360
- tag: tag,
2361
- encode: function writeExtBuffer(typedArray, encode) {
2362
- let length = typedArray.byteLength;
2363
- let offset = typedArray.byteOffset || 0;
2364
- let buffer = typedArray.buffer || typedArray;
2365
- encode(hasNodeBuffer ? Buffer$1.from(buffer, offset, length) :
2366
- new Uint8Array(buffer, offset, length));
2367
- }
2368
- }
2369
- }
2370
- function writeBuffer(buffer, makeRoom) {
2371
- let length = buffer.byteLength;
2372
- if (length < 0x18) {
2373
- target[position++] = 0x40 + length;
2374
- } else if (length < 0x100) {
2375
- target[position++] = 0x58;
2376
- target[position++] = length;
2377
- } else if (length < 0x10000) {
2378
- target[position++] = 0x59;
2379
- target[position++] = length >> 8;
2380
- target[position++] = length & 0xff;
2381
- } else {
2382
- target[position++] = 0x5a;
2383
- targetView.setUint32(position, length);
2384
- position += 4;
2385
- }
2386
- if (position + length >= target.length) {
2387
- makeRoom(position + length);
2388
- }
2389
- // if it is already a typed array (has an ArrayBuffer), use that, but if it is an ArrayBuffer itself,
2390
- // must wrap it to set it.
2391
- target.set(buffer.buffer ? buffer : new Uint8Array(buffer), position);
2392
- position += length;
2393
- }
2394
-
2395
- function insertIds(serialized, idsToInsert) {
2396
- // insert the ids that need to be referenced for structured clones
2397
- let nextId;
2398
- let distanceToMove = idsToInsert.length * 2;
2399
- let lastEnd = serialized.length - distanceToMove;
2400
- idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
2401
- for (let id = 0; id < idsToInsert.length; id++) {
2402
- let referee = idsToInsert[id];
2403
- referee.id = id;
2404
- for (let position of referee.references) {
2405
- serialized[position++] = id >> 8;
2406
- serialized[position] = id & 0xff;
2407
- }
2408
- }
2409
- while (nextId = idsToInsert.pop()) {
2410
- let offset = nextId.offset;
2411
- serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
2412
- distanceToMove -= 2;
2413
- let position = offset + distanceToMove;
2414
- serialized[position++] = 0xd8;
2415
- serialized[position++] = 28; // http://cbor.schmorp.de/value-sharing
2416
- lastEnd = offset;
2417
- }
2418
- return serialized
2419
- }
2420
- function writeBundles(start, encode) {
2421
- targetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1); // the offset to bundle
2422
- let writeStrings = bundledStrings;
2423
- bundledStrings = null;
2424
- encode(writeStrings[0]);
2425
- encode(writeStrings[1]);
2426
- }
2427
-
2428
- function addExtension(extension) {
2429
- if (extension.Class) {
2430
- if (!extension.encode)
2431
- throw new Error('Extension has no encode function')
2432
- extensionClasses.unshift(extension.Class);
2433
- extensions.unshift(extension);
2434
- }
2435
- addExtension$1(extension);
2436
- }
2437
- let defaultEncoder = new Encoder({ useRecords: false });
2438
- const encode = defaultEncoder.encode;
2439
- const encodeAsIterable = defaultEncoder.encodeAsIterable;
2440
- const encodeAsAsyncIterable = defaultEncoder.encodeAsAsyncIterable;
2441
- const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
2442
- const REUSE_BUFFER_MODE = 512;
2443
- const RESET_BUFFER_MODE = 1024;
2444
- const THROW_ON_ITERABLE = 2048;
2445
-
2446
- class EncoderStream extends stream.Transform {
2447
- constructor(options) {
2448
- if (!options)
2449
- options = {};
2450
- options.writableObjectMode = true;
2451
- super(options);
2452
- options.sequential = true;
2453
- this.encoder = options.encoder || new Encoder(options);
2454
- }
2455
- async _transform(value, encoding, callback) {
2456
- try {
2457
- for await (let chunk of this.encoder.encodeAsAsyncIterable(value)) {
2458
- this.push(chunk);
2459
- }
2460
- callback();
2461
- } catch(error) { callback (error); }
2462
- }
2463
- }
2464
-
2465
- class DecoderStream extends stream.Transform {
2466
- constructor(options) {
2467
- if (!options)
2468
- options = {};
2469
- options.objectMode = true;
2470
- super(options);
2471
- options.structures = [];
2472
- this.decoder = options.decoder || new Decoder(options);
2473
- }
2474
- _transform(chunk, encoding, callback) {
2475
- if (this.incompleteBuffer) {
2476
- chunk = Buffer.concat([this.incompleteBuffer, chunk]);
2477
- this.incompleteBuffer = null;
2478
- }
2479
- let values;
2480
- try {
2481
- values = this.decoder.decodeMultiple(chunk);
2482
- } catch(error) {
2483
- if (error.incomplete) {
2484
- this.incompleteBuffer = chunk.slice(error.lastPosition);
2485
- values = error.values;
2486
- } else {
2487
- return callback(error)
2488
- }
2489
- } finally {
2490
- for (let value of values || []) {
2491
- if (value === null)
2492
- value = this.getNullValue();
2493
- this.push(value);
2494
- }
2495
- }
2496
- callback();
2497
- }
2498
- getNullValue() {
2499
- return Symbol.for(null)
2500
- }
2501
- }
2502
-
2503
- /**
2504
- * Given an Iterable first argument, returns an Iterable where each value is encoded as a Buffer
2505
- * If the argument is only Async Iterable, the return value will be an Async Iterable.
2506
- * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
2507
- * @param {options} [options] - cbor-x Encoder options
2508
- * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
2509
- */
2510
- function encodeIter (objectIterator, options = {}) {
2511
- if (!objectIterator || typeof objectIterator !== 'object') {
2512
- throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
2513
- } else if (typeof objectIterator[Symbol.iterator] === 'function') {
2514
- return encodeIterSync(objectIterator, options)
2515
- } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
2516
- return encodeIterAsync(objectIterator, options)
2517
- } else {
2518
- throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
2519
- }
2520
- }
2521
-
2522
- function * encodeIterSync (objectIterator, options) {
2523
- const encoder = new Encoder(options);
2524
- for (const value of objectIterator) {
2525
- yield encoder.encode(value);
2526
- }
2527
- }
2528
-
2529
- async function * encodeIterAsync (objectIterator, options) {
2530
- const encoder = new Encoder(options);
2531
- for await (const value of objectIterator) {
2532
- yield encoder.encode(value);
2533
- }
2534
- }
2535
-
2536
- /**
2537
- * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
2538
- * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
2539
- * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
2540
- * @param {object} [options] - Decoder options
2541
- * @returns {IterableIterator|Promise.<AsyncIterableIterator}
2542
- */
2543
- function decodeIter (bufferIterator, options = {}) {
2544
- if (!bufferIterator || typeof bufferIterator !== 'object') {
2545
- throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
2546
- }
2547
-
2548
- const decoder = new Decoder(options);
2549
- let incomplete;
2550
- const parser = (chunk) => {
2551
- let yields;
2552
- // if there's incomplete data from previous chunk, concatinate and try again
2553
- if (incomplete) {
2554
- chunk = Buffer.concat([incomplete, chunk]);
2555
- incomplete = undefined;
2556
- }
2557
-
2558
- try {
2559
- yields = decoder.decodeMultiple(chunk);
2560
- } catch (err) {
2561
- if (err.incomplete) {
2562
- incomplete = chunk.slice(err.lastPosition);
2563
- yields = err.values;
2564
- } else {
2565
- throw err
2566
- }
2567
- }
2568
- return yields
2569
- };
2570
-
2571
- if (typeof bufferIterator[Symbol.iterator] === 'function') {
2572
- return (function * iter () {
2573
- for (const value of bufferIterator) {
2574
- yield * parser(value);
2575
- }
2576
- })()
2577
- } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
2578
- return (async function * iter () {
2579
- for await (const value of bufferIterator) {
2580
- yield * parser(value);
2581
- }
2582
- })()
2583
- }
2584
- }
2585
-
2586
- const useRecords = false;
2587
- const mapsAsObjects = true;
2588
-
2589
- const nativeAccelerationDisabled = process.env.CBOR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';
2590
-
2591
- if (!nativeAccelerationDisabled) {
2592
- let extractor;
2593
- try {
2594
- if (typeof require == 'function')
2595
- extractor = require('cbor-extract');
2596
- else
2597
- extractor = module$1.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('node.cjs', document.baseURI).href)))('cbor-extract');
2598
- if (extractor)
2599
- setExtractor(extractor.extractStrings);
2600
- } catch (error) {
2601
- // native module is optional
2602
- }
2603
- }
2604
-
2605
- exports.ALWAYS = ALWAYS;
2606
- exports.DECIMAL_FIT = DECIMAL_FIT;
2607
- exports.DECIMAL_ROUND = DECIMAL_ROUND;
2608
- exports.Decoder = Decoder;
2609
- exports.DecoderStream = DecoderStream;
2610
- exports.Encoder = Encoder;
2611
- exports.EncoderStream = EncoderStream;
2612
- exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
2613
- exports.NEVER = NEVER;
2614
- exports.REUSE_BUFFER_MODE = REUSE_BUFFER_MODE;
2615
- exports.Tag = Tag;
2616
- exports.addExtension = addExtension;
2617
- exports.clearSource = clearSource;
2618
- exports.decode = decode;
2619
- exports.decodeIter = decodeIter;
2620
- exports.decodeMultiple = decodeMultiple;
2621
- exports.encode = encode;
2622
- exports.encodeAsAsyncIterable = encodeAsAsyncIterable;
2623
- exports.encodeAsIterable = encodeAsIterable;
2624
- exports.encodeIter = encodeIter;
2625
- exports.mapsAsObjects = mapsAsObjects;
2626
- exports.roundFloat32 = roundFloat32;
2627
- exports.setSizeLimits = setSizeLimits;
2628
- exports.useRecords = useRecords;
2629
- //# sourceMappingURL=node.cjs.map