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