@carbon/ai-chat 0.1.6 → 0.1.7-test-no-cjs

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 (144) hide show
  1. package/dist/es/{cds-aichat-internal.js → AppContainer.js} +50756 -18310
  2. package/dist/es/Carousel.js +14 -8
  3. package/dist/es/GenesysMessengerServiceDesk.js +17 -11
  4. package/dist/es/HumanAgentServiceImpl.js +17 -12
  5. package/dist/es/NiceDFOServiceDesk.js +17 -12
  6. package/dist/es/PDFViewerContainer.js +15 -108
  7. package/dist/es/ReactPlayer.js +2 -2
  8. package/dist/es/SFServiceDesk.js +18 -11
  9. package/dist/es/ServiceDeskImpl.js +2 -2
  10. package/dist/es/Table.js +429 -315
  11. package/dist/es/ZendeskServiceDesk.js +17 -11
  12. package/dist/es/_node-resolve_empty.js +2 -2
  13. package/dist/es/aiChatEntry.js +137 -120
  14. package/dist/es/ar-dz.js +3 -4
  15. package/dist/es/ar-kw.js +3 -4
  16. package/dist/es/ar-ly.js +3 -4
  17. package/dist/es/ar-ma.js +3 -4
  18. package/dist/es/ar-sa.js +3 -4
  19. package/dist/es/ar-tn.js +3 -4
  20. package/dist/es/ar.js +3 -4
  21. package/dist/es/ar2.js +2 -2
  22. package/dist/es/cds-aichat-container.js +104 -18
  23. package/dist/es/cds-aichat-custom-element.js +31 -21
  24. package/dist/es/cs.js +3 -4
  25. package/dist/es/cs2.js +2 -2
  26. package/dist/es/de-at.js +3 -4
  27. package/dist/es/de-ch.js +3 -4
  28. package/dist/es/de.js +3 -4
  29. package/dist/es/de2.js +2 -2
  30. package/dist/es/en-au.js +3 -4
  31. package/dist/es/en-ca.js +3 -4
  32. package/dist/es/en-gb.js +3 -4
  33. package/dist/es/en-ie.js +3 -4
  34. package/dist/es/en-il.js +3 -4
  35. package/dist/es/en-nz.js +3 -4
  36. package/dist/es/es-do.js +3 -4
  37. package/dist/es/es-us.js +3 -4
  38. package/dist/es/es.js +3 -4
  39. package/dist/es/es2.js +2 -2
  40. package/dist/es/export.js +3 -3
  41. package/dist/es/export.legacy.js +3 -3
  42. package/dist/es/fontUtils.js +2 -2
  43. package/dist/es/fr-ca.js +3 -4
  44. package/dist/es/fr-ch.js +3 -4
  45. package/dist/es/fr.js +3 -4
  46. package/dist/es/fr2.js +2 -2
  47. package/dist/es/it-ch.js +3 -4
  48. package/dist/es/it.js +3 -4
  49. package/dist/es/it2.js +2 -2
  50. package/dist/es/ja.js +3 -4
  51. package/dist/es/ja2.js +2 -2
  52. package/dist/es/ko.js +3 -4
  53. package/dist/es/ko2.js +2 -2
  54. package/dist/es/mockServiceDesk.js +17 -11
  55. package/dist/es/nl.js +3 -4
  56. package/dist/es/nl2.js +2 -2
  57. package/dist/es/pt-br.js +3 -4
  58. package/dist/es/pt-br2.js +2 -2
  59. package/dist/es/pt.js +3 -4
  60. package/dist/es/render.js +25 -12
  61. package/dist/es/zh-cn.js +3 -4
  62. package/dist/es/zh-tw.js +3 -4
  63. package/dist/es/zh-tw2.js +2 -2
  64. package/dist/es/zh.js +2 -2
  65. package/dist/types/aiChatEntry.d.ts +599 -11
  66. package/package.json +29 -21
  67. package/dist/cjs/Carousel.js +0 -5711
  68. package/dist/cjs/Chat.js +0 -8838
  69. package/dist/cjs/GenesysMessengerServiceDesk.js +0 -598
  70. package/dist/cjs/HumanAgentServiceImpl.js +0 -1145
  71. package/dist/cjs/NiceDFOServiceDesk.js +0 -2116
  72. package/dist/cjs/PDFViewerContainer.js +0 -83227
  73. package/dist/cjs/ReactPlayer.js +0 -57
  74. package/dist/cjs/SFServiceDesk.js +0 -1031
  75. package/dist/cjs/ServiceDeskImpl.js +0 -74
  76. package/dist/cjs/Table.js +0 -3146
  77. package/dist/cjs/ZendeskServiceDesk.js +0 -670
  78. package/dist/cjs/_node-resolve_empty.js +0 -27
  79. package/dist/cjs/agentActions.js +0 -214
  80. package/dist/cjs/aiChatEntry.js +0 -354
  81. package/dist/cjs/anonymousUserIDStorage.js +0 -254
  82. package/dist/cjs/ar-dz.js +0 -57
  83. package/dist/cjs/ar-kw.js +0 -57
  84. package/dist/cjs/ar-ly.js +0 -57
  85. package/dist/cjs/ar-ma.js +0 -57
  86. package/dist/cjs/ar-sa.js +0 -57
  87. package/dist/cjs/ar-tn.js +0 -57
  88. package/dist/cjs/ar.js +0 -57
  89. package/dist/cjs/ar2.js +0 -763
  90. package/dist/cjs/cds-aichat-container.js +0 -143
  91. package/dist/cjs/cds-aichat-custom-element.js +0 -200
  92. package/dist/cjs/cds-aichat-internal.js +0 -39150
  93. package/dist/cjs/cs.js +0 -57
  94. package/dist/cjs/cs2.js +0 -763
  95. package/dist/cjs/de-at.js +0 -57
  96. package/dist/cjs/de-ch.js +0 -57
  97. package/dist/cjs/de.js +0 -57
  98. package/dist/cjs/de2.js +0 -763
  99. package/dist/cjs/en-au.js +0 -57
  100. package/dist/cjs/en-ca.js +0 -57
  101. package/dist/cjs/en-gb.js +0 -57
  102. package/dist/cjs/en-ie.js +0 -57
  103. package/dist/cjs/en-il.js +0 -57
  104. package/dist/cjs/en-nz.js +0 -57
  105. package/dist/cjs/es-do.js +0 -57
  106. package/dist/cjs/es-us.js +0 -57
  107. package/dist/cjs/es.js +0 -57
  108. package/dist/cjs/es2.js +0 -763
  109. package/dist/cjs/export.js +0 -27
  110. package/dist/cjs/export.legacy.js +0 -27
  111. package/dist/cjs/fontUtils.js +0 -1038
  112. package/dist/cjs/fr-ca.js +0 -57
  113. package/dist/cjs/fr-ch.js +0 -57
  114. package/dist/cjs/fr.js +0 -57
  115. package/dist/cjs/fr2.js +0 -763
  116. package/dist/cjs/highlight_js.js +0 -15325
  117. package/dist/cjs/it-ch.js +0 -57
  118. package/dist/cjs/it.js +0 -57
  119. package/dist/cjs/it2.js +0 -763
  120. package/dist/cjs/ja.js +0 -57
  121. package/dist/cjs/ja2.js +0 -763
  122. package/dist/cjs/jstz.min.js +0 -43
  123. package/dist/cjs/ko.js +0 -57
  124. package/dist/cjs/ko2.js +0 -763
  125. package/dist/cjs/markdown.js +0 -8505
  126. package/dist/cjs/markdown_attrs.js +0 -805
  127. package/dist/cjs/mockServiceDesk.js +0 -887
  128. package/dist/cjs/nl.js +0 -57
  129. package/dist/cjs/nl2.js +0 -763
  130. package/dist/cjs/pt-br.js +0 -57
  131. package/dist/cjs/pt-br2.js +0 -763
  132. package/dist/cjs/pt.js +0 -57
  133. package/dist/cjs/render.js +0 -94
  134. package/dist/cjs/zh-cn.js +0 -57
  135. package/dist/cjs/zh-tw.js +0 -57
  136. package/dist/cjs/zh-tw2.js +0 -763
  137. package/dist/cjs/zh.js +0 -763
  138. package/dist/es/Chat.js +0 -8836
  139. package/dist/es/agentActions.js +0 -186
  140. package/dist/es/anonymousUserIDStorage.js +0 -249
  141. package/dist/es/highlight_js.js +0 -15320
  142. package/dist/es/jstz.min.js +0 -41
  143. package/dist/es/markdown.js +0 -8501
  144. package/dist/es/markdown_attrs.js +0 -803
package/dist/cjs/Table.js DELETED
@@ -1,3146 +0,0 @@
1
- /*
2
-
3
-
4
- (C) Copyright IBM Corp. 2017, 2025. All Rights Reserved.
5
-
6
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7
- in compliance with the License. You may obtain a copy of the License at
8
-
9
- http://www.apache.org/licenses/LICENSE-2.0
10
-
11
- Unless required by applicable law or agreed to in writing, software distributed under the License
12
- is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13
- or implied. See the License for the specific language governing permissions and limitations under
14
- the License.
15
-
16
- @carbon/ai-chat 0.1.6
17
-
18
- Built: Feb 3 2025 9:58 am -05:00
19
-
20
-
21
-
22
- */
23
- 'use strict';
24
-
25
- var cdsAichatInternal = require('./cds-aichat-internal.js');
26
- var React = require('react');
27
- var lit = require('lit');
28
- var decorators_js = require('lit/decorators.js');
29
- require('@carbon/web-components/es/components/data-table/index.js');
30
- require('@carbon/web-components/es/components/checkbox/index.js');
31
- require('@carbon/web-components/es/components/button/index.js');
32
- var unsafeSvg_js = require('lit/directives/unsafe-svg.js');
33
- var repeat_js = require('lit-html/directives/repeat.js');
34
- require('@carbon/web-components/es/components/pagination/index.js');
35
- require('@carbon/web-components/es/components/select/index.js');
36
- require('@carbon/web-components/es/components/data-table/table-skeleton.js');
37
- require('react-dom');
38
- require('./highlight_js.js');
39
- require('@carbon/react');
40
- require('react-intl');
41
- require('react-redux');
42
- require('./markdown.js');
43
- require('./markdown_attrs.js');
44
- require('@carbon/web-components/es/components/overflow-menu/index.js');
45
- require('lit/directives/unsafe-html.js');
46
- require('@carbon/web-components/es/components/slug/index.js');
47
- require('@carbon/web-components/es/components/popover/defs.js');
48
- require('@carbon/web-components/es/components/slug/defs.js');
49
- require('@carbon/web-components/es/components/slug/slug-action-button.js');
50
- require('@carbon/web-components/es/components/slug/slug.js');
51
- require('@carbon/web-components/es/components/textarea/index.js');
52
- require('@carbon/web-components/es/components/icon-button/index.js');
53
- require('@carbon/web-components/es/components/tag/index.js');
54
- require('@carbon/web-components/es/components/chat-button/index.js');
55
- require('@carbon/web-components/es/components/button/button.js');
56
- require('@carbon/web-components/es/components/layer/index.js');
57
-
58
- /**
59
- * Copyright IBM Corp. 2016, 2023
60
- *
61
- * This source code is licensed under the Apache-2.0 license found in the
62
- * LICENSE file in the root directory of this source tree.
63
- *
64
- * Code generated by @carbon/icon-build-helpers. DO NOT EDIT.
65
- */
66
- var _16 = {
67
- "elem": "svg",
68
- "attrs": {
69
- "xmlns": "http://www.w3.org/2000/svg",
70
- "viewBox": "0 0 16 16",
71
- "fill": "currentColor",
72
- "width": 16,
73
- "height": 16
74
- },
75
- "content": [{
76
- "elem": "path",
77
- "attrs": {
78
- "d": "M13 7L12.3 6.3 8.5 10.1 8.5 1 7.5 1 7.5 10.1 3.7 6.3 3 7 8 12zM13 12v2H3v-2H2v2l0 0c0 .6.4 1 1 1h10c.6 0 1-.4 1-1l0 0v-2H13z"
79
- }
80
- }],
81
- "name": "download",
82
- "size": 16
83
- };
84
-
85
- var global$1 = (typeof global !== "undefined" ? global :
86
- typeof self !== "undefined" ? self :
87
- typeof window !== "undefined" ? window : {});
88
-
89
- var lookup = [];
90
- var revLookup = [];
91
- var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
92
- var inited = false;
93
- function init () {
94
- inited = true;
95
- var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
96
- for (var i = 0, len = code.length; i < len; ++i) {
97
- lookup[i] = code[i];
98
- revLookup[code.charCodeAt(i)] = i;
99
- }
100
-
101
- revLookup['-'.charCodeAt(0)] = 62;
102
- revLookup['_'.charCodeAt(0)] = 63;
103
- }
104
-
105
- function toByteArray (b64) {
106
- if (!inited) {
107
- init();
108
- }
109
- var i, j, l, tmp, placeHolders, arr;
110
- var len = b64.length;
111
-
112
- if (len % 4 > 0) {
113
- throw new Error('Invalid string. Length must be a multiple of 4')
114
- }
115
-
116
- // the number of equal signs (place holders)
117
- // if there are two placeholders, than the two characters before it
118
- // represent one byte
119
- // if there is only one, then the three characters before it represent 2 bytes
120
- // this is just a cheap hack to not do indexOf twice
121
- placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
122
-
123
- // base64 is 4/3 + up to two characters of the original data
124
- arr = new Arr(len * 3 / 4 - placeHolders);
125
-
126
- // if there are placeholders, only get up to the last complete 4 chars
127
- l = placeHolders > 0 ? len - 4 : len;
128
-
129
- var L = 0;
130
-
131
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
132
- tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
133
- arr[L++] = (tmp >> 16) & 0xFF;
134
- arr[L++] = (tmp >> 8) & 0xFF;
135
- arr[L++] = tmp & 0xFF;
136
- }
137
-
138
- if (placeHolders === 2) {
139
- tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
140
- arr[L++] = tmp & 0xFF;
141
- } else if (placeHolders === 1) {
142
- tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
143
- arr[L++] = (tmp >> 8) & 0xFF;
144
- arr[L++] = tmp & 0xFF;
145
- }
146
-
147
- return arr
148
- }
149
-
150
- function tripletToBase64 (num) {
151
- return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
152
- }
153
-
154
- function encodeChunk (uint8, start, end) {
155
- var tmp;
156
- var output = [];
157
- for (var i = start; i < end; i += 3) {
158
- tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
159
- output.push(tripletToBase64(tmp));
160
- }
161
- return output.join('')
162
- }
163
-
164
- function fromByteArray (uint8) {
165
- if (!inited) {
166
- init();
167
- }
168
- var tmp;
169
- var len = uint8.length;
170
- var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
171
- var output = '';
172
- var parts = [];
173
- var maxChunkLength = 16383; // must be multiple of 3
174
-
175
- // go through the array every three bytes, we'll deal with trailing stuff later
176
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
177
- parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
178
- }
179
-
180
- // pad the end with zeros, but make sure to not forget the extra bytes
181
- if (extraBytes === 1) {
182
- tmp = uint8[len - 1];
183
- output += lookup[tmp >> 2];
184
- output += lookup[(tmp << 4) & 0x3F];
185
- output += '==';
186
- } else if (extraBytes === 2) {
187
- tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
188
- output += lookup[tmp >> 10];
189
- output += lookup[(tmp >> 4) & 0x3F];
190
- output += lookup[(tmp << 2) & 0x3F];
191
- output += '=';
192
- }
193
-
194
- parts.push(output);
195
-
196
- return parts.join('')
197
- }
198
-
199
- function read (buffer, offset, isLE, mLen, nBytes) {
200
- var e, m;
201
- var eLen = nBytes * 8 - mLen - 1;
202
- var eMax = (1 << eLen) - 1;
203
- var eBias = eMax >> 1;
204
- var nBits = -7;
205
- var i = isLE ? (nBytes - 1) : 0;
206
- var d = isLE ? -1 : 1;
207
- var s = buffer[offset + i];
208
-
209
- i += d;
210
-
211
- e = s & ((1 << (-nBits)) - 1);
212
- s >>= (-nBits);
213
- nBits += eLen;
214
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
215
-
216
- m = e & ((1 << (-nBits)) - 1);
217
- e >>= (-nBits);
218
- nBits += mLen;
219
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
220
-
221
- if (e === 0) {
222
- e = 1 - eBias;
223
- } else if (e === eMax) {
224
- return m ? NaN : ((s ? -1 : 1) * Infinity)
225
- } else {
226
- m = m + Math.pow(2, mLen);
227
- e = e - eBias;
228
- }
229
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
230
- }
231
-
232
- function write (buffer, value, offset, isLE, mLen, nBytes) {
233
- var e, m, c;
234
- var eLen = nBytes * 8 - mLen - 1;
235
- var eMax = (1 << eLen) - 1;
236
- var eBias = eMax >> 1;
237
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
238
- var i = isLE ? 0 : (nBytes - 1);
239
- var d = isLE ? 1 : -1;
240
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
241
-
242
- value = Math.abs(value);
243
-
244
- if (isNaN(value) || value === Infinity) {
245
- m = isNaN(value) ? 1 : 0;
246
- e = eMax;
247
- } else {
248
- e = Math.floor(Math.log(value) / Math.LN2);
249
- if (value * (c = Math.pow(2, -e)) < 1) {
250
- e--;
251
- c *= 2;
252
- }
253
- if (e + eBias >= 1) {
254
- value += rt / c;
255
- } else {
256
- value += rt * Math.pow(2, 1 - eBias);
257
- }
258
- if (value * c >= 2) {
259
- e++;
260
- c /= 2;
261
- }
262
-
263
- if (e + eBias >= eMax) {
264
- m = 0;
265
- e = eMax;
266
- } else if (e + eBias >= 1) {
267
- m = (value * c - 1) * Math.pow(2, mLen);
268
- e = e + eBias;
269
- } else {
270
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
271
- e = 0;
272
- }
273
- }
274
-
275
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
276
-
277
- e = (e << mLen) | m;
278
- eLen += mLen;
279
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
280
-
281
- buffer[offset + i - d] |= s * 128;
282
- }
283
-
284
- var toString = {}.toString;
285
-
286
- var isArray = Array.isArray || function (arr) {
287
- return toString.call(arr) == '[object Array]';
288
- };
289
-
290
- var INSPECT_MAX_BYTES = 50;
291
-
292
- /**
293
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
294
- * === true Use Uint8Array implementation (fastest)
295
- * === false Use Object implementation (most compatible, even IE6)
296
- *
297
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
298
- * Opera 11.6+, iOS 4.2+.
299
- *
300
- * Due to various browser bugs, sometimes the Object implementation will be used even
301
- * when the browser supports typed arrays.
302
- *
303
- * Note:
304
- *
305
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
306
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
307
- *
308
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
309
- *
310
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
311
- * incorrect length in some situations.
312
-
313
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
314
- * get the Object implementation, which is slower but behaves correctly.
315
- */
316
- Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
317
- ? global$1.TYPED_ARRAY_SUPPORT
318
- : true;
319
-
320
- /*
321
- * Export kMaxLength after typed array support is determined.
322
- */
323
- kMaxLength();
324
-
325
- function kMaxLength () {
326
- return Buffer.TYPED_ARRAY_SUPPORT
327
- ? 0x7fffffff
328
- : 0x3fffffff
329
- }
330
-
331
- function createBuffer (that, length) {
332
- if (kMaxLength() < length) {
333
- throw new RangeError('Invalid typed array length')
334
- }
335
- if (Buffer.TYPED_ARRAY_SUPPORT) {
336
- // Return an augmented `Uint8Array` instance, for best performance
337
- that = new Uint8Array(length);
338
- that.__proto__ = Buffer.prototype;
339
- } else {
340
- // Fallback: Return an object instance of the Buffer class
341
- if (that === null) {
342
- that = new Buffer(length);
343
- }
344
- that.length = length;
345
- }
346
-
347
- return that
348
- }
349
-
350
- /**
351
- * The Buffer constructor returns instances of `Uint8Array` that have their
352
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
353
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
354
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
355
- * returns a single octet.
356
- *
357
- * The `Uint8Array` prototype remains unmodified.
358
- */
359
-
360
- function Buffer (arg, encodingOrOffset, length) {
361
- if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
362
- return new Buffer(arg, encodingOrOffset, length)
363
- }
364
-
365
- // Common case.
366
- if (typeof arg === 'number') {
367
- if (typeof encodingOrOffset === 'string') {
368
- throw new Error(
369
- 'If encoding is specified then the first argument must be a string'
370
- )
371
- }
372
- return allocUnsafe(this, arg)
373
- }
374
- return from(this, arg, encodingOrOffset, length)
375
- }
376
-
377
- Buffer.poolSize = 8192; // not used by this implementation
378
-
379
- // TODO: Legacy, not needed anymore. Remove in next major version.
380
- Buffer._augment = function (arr) {
381
- arr.__proto__ = Buffer.prototype;
382
- return arr
383
- };
384
-
385
- function from (that, value, encodingOrOffset, length) {
386
- if (typeof value === 'number') {
387
- throw new TypeError('"value" argument must not be a number')
388
- }
389
-
390
- if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
391
- return fromArrayBuffer(that, value, encodingOrOffset, length)
392
- }
393
-
394
- if (typeof value === 'string') {
395
- return fromString(that, value, encodingOrOffset)
396
- }
397
-
398
- return fromObject(that, value)
399
- }
400
-
401
- /**
402
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
403
- * if value is a number.
404
- * Buffer.from(str[, encoding])
405
- * Buffer.from(array)
406
- * Buffer.from(buffer)
407
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
408
- **/
409
- Buffer.from = function (value, encodingOrOffset, length) {
410
- return from(null, value, encodingOrOffset, length)
411
- };
412
-
413
- if (Buffer.TYPED_ARRAY_SUPPORT) {
414
- Buffer.prototype.__proto__ = Uint8Array.prototype;
415
- Buffer.__proto__ = Uint8Array;
416
- if (typeof Symbol !== 'undefined' && Symbol.species &&
417
- Buffer[Symbol.species] === Buffer) ;
418
- }
419
-
420
- function assertSize (size) {
421
- if (typeof size !== 'number') {
422
- throw new TypeError('"size" argument must be a number')
423
- } else if (size < 0) {
424
- throw new RangeError('"size" argument must not be negative')
425
- }
426
- }
427
-
428
- function alloc (that, size, fill, encoding) {
429
- assertSize(size);
430
- if (size <= 0) {
431
- return createBuffer(that, size)
432
- }
433
- if (fill !== undefined) {
434
- // Only pay attention to encoding if it's a string. This
435
- // prevents accidentally sending in a number that would
436
- // be interpretted as a start offset.
437
- return typeof encoding === 'string'
438
- ? createBuffer(that, size).fill(fill, encoding)
439
- : createBuffer(that, size).fill(fill)
440
- }
441
- return createBuffer(that, size)
442
- }
443
-
444
- /**
445
- * Creates a new filled Buffer instance.
446
- * alloc(size[, fill[, encoding]])
447
- **/
448
- Buffer.alloc = function (size, fill, encoding) {
449
- return alloc(null, size, fill, encoding)
450
- };
451
-
452
- function allocUnsafe (that, size) {
453
- assertSize(size);
454
- that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
455
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
456
- for (var i = 0; i < size; ++i) {
457
- that[i] = 0;
458
- }
459
- }
460
- return that
461
- }
462
-
463
- /**
464
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
465
- * */
466
- Buffer.allocUnsafe = function (size) {
467
- return allocUnsafe(null, size)
468
- };
469
- /**
470
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
471
- */
472
- Buffer.allocUnsafeSlow = function (size) {
473
- return allocUnsafe(null, size)
474
- };
475
-
476
- function fromString (that, string, encoding) {
477
- if (typeof encoding !== 'string' || encoding === '') {
478
- encoding = 'utf8';
479
- }
480
-
481
- if (!Buffer.isEncoding(encoding)) {
482
- throw new TypeError('"encoding" must be a valid string encoding')
483
- }
484
-
485
- var length = byteLength(string, encoding) | 0;
486
- that = createBuffer(that, length);
487
-
488
- var actual = that.write(string, encoding);
489
-
490
- if (actual !== length) {
491
- // Writing a hex string, for example, that contains invalid characters will
492
- // cause everything after the first invalid character to be ignored. (e.g.
493
- // 'abxxcd' will be treated as 'ab')
494
- that = that.slice(0, actual);
495
- }
496
-
497
- return that
498
- }
499
-
500
- function fromArrayLike (that, array) {
501
- var length = array.length < 0 ? 0 : checked(array.length) | 0;
502
- that = createBuffer(that, length);
503
- for (var i = 0; i < length; i += 1) {
504
- that[i] = array[i] & 255;
505
- }
506
- return that
507
- }
508
-
509
- function fromArrayBuffer (that, array, byteOffset, length) {
510
- array.byteLength; // this throws if `array` is not a valid ArrayBuffer
511
-
512
- if (byteOffset < 0 || array.byteLength < byteOffset) {
513
- throw new RangeError('\'offset\' is out of bounds')
514
- }
515
-
516
- if (array.byteLength < byteOffset + (length || 0)) {
517
- throw new RangeError('\'length\' is out of bounds')
518
- }
519
-
520
- if (byteOffset === undefined && length === undefined) {
521
- array = new Uint8Array(array);
522
- } else if (length === undefined) {
523
- array = new Uint8Array(array, byteOffset);
524
- } else {
525
- array = new Uint8Array(array, byteOffset, length);
526
- }
527
-
528
- if (Buffer.TYPED_ARRAY_SUPPORT) {
529
- // Return an augmented `Uint8Array` instance, for best performance
530
- that = array;
531
- that.__proto__ = Buffer.prototype;
532
- } else {
533
- // Fallback: Return an object instance of the Buffer class
534
- that = fromArrayLike(that, array);
535
- }
536
- return that
537
- }
538
-
539
- function fromObject (that, obj) {
540
- if (internalIsBuffer(obj)) {
541
- var len = checked(obj.length) | 0;
542
- that = createBuffer(that, len);
543
-
544
- if (that.length === 0) {
545
- return that
546
- }
547
-
548
- obj.copy(that, 0, 0, len);
549
- return that
550
- }
551
-
552
- if (obj) {
553
- if ((typeof ArrayBuffer !== 'undefined' &&
554
- obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
555
- if (typeof obj.length !== 'number' || isnan(obj.length)) {
556
- return createBuffer(that, 0)
557
- }
558
- return fromArrayLike(that, obj)
559
- }
560
-
561
- if (obj.type === 'Buffer' && isArray(obj.data)) {
562
- return fromArrayLike(that, obj.data)
563
- }
564
- }
565
-
566
- throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
567
- }
568
-
569
- function checked (length) {
570
- // Note: cannot use `length < kMaxLength()` here because that fails when
571
- // length is NaN (which is otherwise coerced to zero.)
572
- if (length >= kMaxLength()) {
573
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
574
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
575
- }
576
- return length | 0
577
- }
578
- Buffer.isBuffer = isBuffer;
579
- function internalIsBuffer (b) {
580
- return !!(b != null && b._isBuffer)
581
- }
582
-
583
- Buffer.compare = function compare (a, b) {
584
- if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
585
- throw new TypeError('Arguments must be Buffers')
586
- }
587
-
588
- if (a === b) return 0
589
-
590
- var x = a.length;
591
- var y = b.length;
592
-
593
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
594
- if (a[i] !== b[i]) {
595
- x = a[i];
596
- y = b[i];
597
- break
598
- }
599
- }
600
-
601
- if (x < y) return -1
602
- if (y < x) return 1
603
- return 0
604
- };
605
-
606
- Buffer.isEncoding = function isEncoding (encoding) {
607
- switch (String(encoding).toLowerCase()) {
608
- case 'hex':
609
- case 'utf8':
610
- case 'utf-8':
611
- case 'ascii':
612
- case 'latin1':
613
- case 'binary':
614
- case 'base64':
615
- case 'ucs2':
616
- case 'ucs-2':
617
- case 'utf16le':
618
- case 'utf-16le':
619
- return true
620
- default:
621
- return false
622
- }
623
- };
624
-
625
- Buffer.concat = function concat (list, length) {
626
- if (!isArray(list)) {
627
- throw new TypeError('"list" argument must be an Array of Buffers')
628
- }
629
-
630
- if (list.length === 0) {
631
- return Buffer.alloc(0)
632
- }
633
-
634
- var i;
635
- if (length === undefined) {
636
- length = 0;
637
- for (i = 0; i < list.length; ++i) {
638
- length += list[i].length;
639
- }
640
- }
641
-
642
- var buffer = Buffer.allocUnsafe(length);
643
- var pos = 0;
644
- for (i = 0; i < list.length; ++i) {
645
- var buf = list[i];
646
- if (!internalIsBuffer(buf)) {
647
- throw new TypeError('"list" argument must be an Array of Buffers')
648
- }
649
- buf.copy(buffer, pos);
650
- pos += buf.length;
651
- }
652
- return buffer
653
- };
654
-
655
- function byteLength (string, encoding) {
656
- if (internalIsBuffer(string)) {
657
- return string.length
658
- }
659
- if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
660
- (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
661
- return string.byteLength
662
- }
663
- if (typeof string !== 'string') {
664
- string = '' + string;
665
- }
666
-
667
- var len = string.length;
668
- if (len === 0) return 0
669
-
670
- // Use a for loop to avoid recursion
671
- var loweredCase = false;
672
- for (;;) {
673
- switch (encoding) {
674
- case 'ascii':
675
- case 'latin1':
676
- case 'binary':
677
- return len
678
- case 'utf8':
679
- case 'utf-8':
680
- case undefined:
681
- return utf8ToBytes(string).length
682
- case 'ucs2':
683
- case 'ucs-2':
684
- case 'utf16le':
685
- case 'utf-16le':
686
- return len * 2
687
- case 'hex':
688
- return len >>> 1
689
- case 'base64':
690
- return base64ToBytes(string).length
691
- default:
692
- if (loweredCase) return utf8ToBytes(string).length // assume utf8
693
- encoding = ('' + encoding).toLowerCase();
694
- loweredCase = true;
695
- }
696
- }
697
- }
698
- Buffer.byteLength = byteLength;
699
-
700
- function slowToString (encoding, start, end) {
701
- var loweredCase = false;
702
-
703
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
704
- // property of a typed array.
705
-
706
- // This behaves neither like String nor Uint8Array in that we set start/end
707
- // to their upper/lower bounds if the value passed is out of range.
708
- // undefined is handled specially as per ECMA-262 6th Edition,
709
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
710
- if (start === undefined || start < 0) {
711
- start = 0;
712
- }
713
- // Return early if start > this.length. Done here to prevent potential uint32
714
- // coercion fail below.
715
- if (start > this.length) {
716
- return ''
717
- }
718
-
719
- if (end === undefined || end > this.length) {
720
- end = this.length;
721
- }
722
-
723
- if (end <= 0) {
724
- return ''
725
- }
726
-
727
- // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
728
- end >>>= 0;
729
- start >>>= 0;
730
-
731
- if (end <= start) {
732
- return ''
733
- }
734
-
735
- if (!encoding) encoding = 'utf8';
736
-
737
- while (true) {
738
- switch (encoding) {
739
- case 'hex':
740
- return hexSlice(this, start, end)
741
-
742
- case 'utf8':
743
- case 'utf-8':
744
- return utf8Slice(this, start, end)
745
-
746
- case 'ascii':
747
- return asciiSlice(this, start, end)
748
-
749
- case 'latin1':
750
- case 'binary':
751
- return latin1Slice(this, start, end)
752
-
753
- case 'base64':
754
- return base64Slice(this, start, end)
755
-
756
- case 'ucs2':
757
- case 'ucs-2':
758
- case 'utf16le':
759
- case 'utf-16le':
760
- return utf16leSlice(this, start, end)
761
-
762
- default:
763
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
764
- encoding = (encoding + '').toLowerCase();
765
- loweredCase = true;
766
- }
767
- }
768
- }
769
-
770
- // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
771
- // Buffer instances.
772
- Buffer.prototype._isBuffer = true;
773
-
774
- function swap (b, n, m) {
775
- var i = b[n];
776
- b[n] = b[m];
777
- b[m] = i;
778
- }
779
-
780
- Buffer.prototype.swap16 = function swap16 () {
781
- var len = this.length;
782
- if (len % 2 !== 0) {
783
- throw new RangeError('Buffer size must be a multiple of 16-bits')
784
- }
785
- for (var i = 0; i < len; i += 2) {
786
- swap(this, i, i + 1);
787
- }
788
- return this
789
- };
790
-
791
- Buffer.prototype.swap32 = function swap32 () {
792
- var len = this.length;
793
- if (len % 4 !== 0) {
794
- throw new RangeError('Buffer size must be a multiple of 32-bits')
795
- }
796
- for (var i = 0; i < len; i += 4) {
797
- swap(this, i, i + 3);
798
- swap(this, i + 1, i + 2);
799
- }
800
- return this
801
- };
802
-
803
- Buffer.prototype.swap64 = function swap64 () {
804
- var len = this.length;
805
- if (len % 8 !== 0) {
806
- throw new RangeError('Buffer size must be a multiple of 64-bits')
807
- }
808
- for (var i = 0; i < len; i += 8) {
809
- swap(this, i, i + 7);
810
- swap(this, i + 1, i + 6);
811
- swap(this, i + 2, i + 5);
812
- swap(this, i + 3, i + 4);
813
- }
814
- return this
815
- };
816
-
817
- Buffer.prototype.toString = function toString () {
818
- var length = this.length | 0;
819
- if (length === 0) return ''
820
- if (arguments.length === 0) return utf8Slice(this, 0, length)
821
- return slowToString.apply(this, arguments)
822
- };
823
-
824
- Buffer.prototype.equals = function equals (b) {
825
- if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
826
- if (this === b) return true
827
- return Buffer.compare(this, b) === 0
828
- };
829
-
830
- Buffer.prototype.inspect = function inspect () {
831
- var str = '';
832
- var max = INSPECT_MAX_BYTES;
833
- if (this.length > 0) {
834
- str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
835
- if (this.length > max) str += ' ... ';
836
- }
837
- return '<Buffer ' + str + '>'
838
- };
839
-
840
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
841
- if (!internalIsBuffer(target)) {
842
- throw new TypeError('Argument must be a Buffer')
843
- }
844
-
845
- if (start === undefined) {
846
- start = 0;
847
- }
848
- if (end === undefined) {
849
- end = target ? target.length : 0;
850
- }
851
- if (thisStart === undefined) {
852
- thisStart = 0;
853
- }
854
- if (thisEnd === undefined) {
855
- thisEnd = this.length;
856
- }
857
-
858
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
859
- throw new RangeError('out of range index')
860
- }
861
-
862
- if (thisStart >= thisEnd && start >= end) {
863
- return 0
864
- }
865
- if (thisStart >= thisEnd) {
866
- return -1
867
- }
868
- if (start >= end) {
869
- return 1
870
- }
871
-
872
- start >>>= 0;
873
- end >>>= 0;
874
- thisStart >>>= 0;
875
- thisEnd >>>= 0;
876
-
877
- if (this === target) return 0
878
-
879
- var x = thisEnd - thisStart;
880
- var y = end - start;
881
- var len = Math.min(x, y);
882
-
883
- var thisCopy = this.slice(thisStart, thisEnd);
884
- var targetCopy = target.slice(start, end);
885
-
886
- for (var i = 0; i < len; ++i) {
887
- if (thisCopy[i] !== targetCopy[i]) {
888
- x = thisCopy[i];
889
- y = targetCopy[i];
890
- break
891
- }
892
- }
893
-
894
- if (x < y) return -1
895
- if (y < x) return 1
896
- return 0
897
- };
898
-
899
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
900
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
901
- //
902
- // Arguments:
903
- // - buffer - a Buffer to search
904
- // - val - a string, Buffer, or number
905
- // - byteOffset - an index into `buffer`; will be clamped to an int32
906
- // - encoding - an optional encoding, relevant is val is a string
907
- // - dir - true for indexOf, false for lastIndexOf
908
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
909
- // Empty buffer means no match
910
- if (buffer.length === 0) return -1
911
-
912
- // Normalize byteOffset
913
- if (typeof byteOffset === 'string') {
914
- encoding = byteOffset;
915
- byteOffset = 0;
916
- } else if (byteOffset > 0x7fffffff) {
917
- byteOffset = 0x7fffffff;
918
- } else if (byteOffset < -0x80000000) {
919
- byteOffset = -0x80000000;
920
- }
921
- byteOffset = +byteOffset; // Coerce to Number.
922
- if (isNaN(byteOffset)) {
923
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
924
- byteOffset = dir ? 0 : (buffer.length - 1);
925
- }
926
-
927
- // Normalize byteOffset: negative offsets start from the end of the buffer
928
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
929
- if (byteOffset >= buffer.length) {
930
- if (dir) return -1
931
- else byteOffset = buffer.length - 1;
932
- } else if (byteOffset < 0) {
933
- if (dir) byteOffset = 0;
934
- else return -1
935
- }
936
-
937
- // Normalize val
938
- if (typeof val === 'string') {
939
- val = Buffer.from(val, encoding);
940
- }
941
-
942
- // Finally, search either indexOf (if dir is true) or lastIndexOf
943
- if (internalIsBuffer(val)) {
944
- // Special case: looking for empty string/buffer always fails
945
- if (val.length === 0) {
946
- return -1
947
- }
948
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
949
- } else if (typeof val === 'number') {
950
- val = val & 0xFF; // Search for a byte value [0-255]
951
- if (Buffer.TYPED_ARRAY_SUPPORT &&
952
- typeof Uint8Array.prototype.indexOf === 'function') {
953
- if (dir) {
954
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
955
- } else {
956
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
957
- }
958
- }
959
- return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
960
- }
961
-
962
- throw new TypeError('val must be string, number or Buffer')
963
- }
964
-
965
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
966
- var indexSize = 1;
967
- var arrLength = arr.length;
968
- var valLength = val.length;
969
-
970
- if (encoding !== undefined) {
971
- encoding = String(encoding).toLowerCase();
972
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
973
- encoding === 'utf16le' || encoding === 'utf-16le') {
974
- if (arr.length < 2 || val.length < 2) {
975
- return -1
976
- }
977
- indexSize = 2;
978
- arrLength /= 2;
979
- valLength /= 2;
980
- byteOffset /= 2;
981
- }
982
- }
983
-
984
- function read (buf, i) {
985
- if (indexSize === 1) {
986
- return buf[i]
987
- } else {
988
- return buf.readUInt16BE(i * indexSize)
989
- }
990
- }
991
-
992
- var i;
993
- if (dir) {
994
- var foundIndex = -1;
995
- for (i = byteOffset; i < arrLength; i++) {
996
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
997
- if (foundIndex === -1) foundIndex = i;
998
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
999
- } else {
1000
- if (foundIndex !== -1) i -= i - foundIndex;
1001
- foundIndex = -1;
1002
- }
1003
- }
1004
- } else {
1005
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
1006
- for (i = byteOffset; i >= 0; i--) {
1007
- var found = true;
1008
- for (var j = 0; j < valLength; j++) {
1009
- if (read(arr, i + j) !== read(val, j)) {
1010
- found = false;
1011
- break
1012
- }
1013
- }
1014
- if (found) return i
1015
- }
1016
- }
1017
-
1018
- return -1
1019
- }
1020
-
1021
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1022
- return this.indexOf(val, byteOffset, encoding) !== -1
1023
- };
1024
-
1025
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1026
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1027
- };
1028
-
1029
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1030
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1031
- };
1032
-
1033
- function hexWrite (buf, string, offset, length) {
1034
- offset = Number(offset) || 0;
1035
- var remaining = buf.length - offset;
1036
- if (!length) {
1037
- length = remaining;
1038
- } else {
1039
- length = Number(length);
1040
- if (length > remaining) {
1041
- length = remaining;
1042
- }
1043
- }
1044
-
1045
- // must be an even number of digits
1046
- var strLen = string.length;
1047
- if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1048
-
1049
- if (length > strLen / 2) {
1050
- length = strLen / 2;
1051
- }
1052
- for (var i = 0; i < length; ++i) {
1053
- var parsed = parseInt(string.substr(i * 2, 2), 16);
1054
- if (isNaN(parsed)) return i
1055
- buf[offset + i] = parsed;
1056
- }
1057
- return i
1058
- }
1059
-
1060
- function utf8Write (buf, string, offset, length) {
1061
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1062
- }
1063
-
1064
- function asciiWrite (buf, string, offset, length) {
1065
- return blitBuffer(asciiToBytes(string), buf, offset, length)
1066
- }
1067
-
1068
- function latin1Write (buf, string, offset, length) {
1069
- return asciiWrite(buf, string, offset, length)
1070
- }
1071
-
1072
- function base64Write (buf, string, offset, length) {
1073
- return blitBuffer(base64ToBytes(string), buf, offset, length)
1074
- }
1075
-
1076
- function ucs2Write (buf, string, offset, length) {
1077
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1078
- }
1079
-
1080
- Buffer.prototype.write = function write (string, offset, length, encoding) {
1081
- // Buffer#write(string)
1082
- if (offset === undefined) {
1083
- encoding = 'utf8';
1084
- length = this.length;
1085
- offset = 0;
1086
- // Buffer#write(string, encoding)
1087
- } else if (length === undefined && typeof offset === 'string') {
1088
- encoding = offset;
1089
- length = this.length;
1090
- offset = 0;
1091
- // Buffer#write(string, offset[, length][, encoding])
1092
- } else if (isFinite(offset)) {
1093
- offset = offset | 0;
1094
- if (isFinite(length)) {
1095
- length = length | 0;
1096
- if (encoding === undefined) encoding = 'utf8';
1097
- } else {
1098
- encoding = length;
1099
- length = undefined;
1100
- }
1101
- // legacy write(string, encoding, offset, length) - remove in v0.13
1102
- } else {
1103
- throw new Error(
1104
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1105
- )
1106
- }
1107
-
1108
- var remaining = this.length - offset;
1109
- if (length === undefined || length > remaining) length = remaining;
1110
-
1111
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1112
- throw new RangeError('Attempt to write outside buffer bounds')
1113
- }
1114
-
1115
- if (!encoding) encoding = 'utf8';
1116
-
1117
- var loweredCase = false;
1118
- for (;;) {
1119
- switch (encoding) {
1120
- case 'hex':
1121
- return hexWrite(this, string, offset, length)
1122
-
1123
- case 'utf8':
1124
- case 'utf-8':
1125
- return utf8Write(this, string, offset, length)
1126
-
1127
- case 'ascii':
1128
- return asciiWrite(this, string, offset, length)
1129
-
1130
- case 'latin1':
1131
- case 'binary':
1132
- return latin1Write(this, string, offset, length)
1133
-
1134
- case 'base64':
1135
- // Warning: maxLength not taken into account in base64Write
1136
- return base64Write(this, string, offset, length)
1137
-
1138
- case 'ucs2':
1139
- case 'ucs-2':
1140
- case 'utf16le':
1141
- case 'utf-16le':
1142
- return ucs2Write(this, string, offset, length)
1143
-
1144
- default:
1145
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1146
- encoding = ('' + encoding).toLowerCase();
1147
- loweredCase = true;
1148
- }
1149
- }
1150
- };
1151
-
1152
- Buffer.prototype.toJSON = function toJSON () {
1153
- return {
1154
- type: 'Buffer',
1155
- data: Array.prototype.slice.call(this._arr || this, 0)
1156
- }
1157
- };
1158
-
1159
- function base64Slice (buf, start, end) {
1160
- if (start === 0 && end === buf.length) {
1161
- return fromByteArray(buf)
1162
- } else {
1163
- return fromByteArray(buf.slice(start, end))
1164
- }
1165
- }
1166
-
1167
- function utf8Slice (buf, start, end) {
1168
- end = Math.min(buf.length, end);
1169
- var res = [];
1170
-
1171
- var i = start;
1172
- while (i < end) {
1173
- var firstByte = buf[i];
1174
- var codePoint = null;
1175
- var bytesPerSequence = (firstByte > 0xEF) ? 4
1176
- : (firstByte > 0xDF) ? 3
1177
- : (firstByte > 0xBF) ? 2
1178
- : 1;
1179
-
1180
- if (i + bytesPerSequence <= end) {
1181
- var secondByte, thirdByte, fourthByte, tempCodePoint;
1182
-
1183
- switch (bytesPerSequence) {
1184
- case 1:
1185
- if (firstByte < 0x80) {
1186
- codePoint = firstByte;
1187
- }
1188
- break
1189
- case 2:
1190
- secondByte = buf[i + 1];
1191
- if ((secondByte & 0xC0) === 0x80) {
1192
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
1193
- if (tempCodePoint > 0x7F) {
1194
- codePoint = tempCodePoint;
1195
- }
1196
- }
1197
- break
1198
- case 3:
1199
- secondByte = buf[i + 1];
1200
- thirdByte = buf[i + 2];
1201
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1202
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
1203
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1204
- codePoint = tempCodePoint;
1205
- }
1206
- }
1207
- break
1208
- case 4:
1209
- secondByte = buf[i + 1];
1210
- thirdByte = buf[i + 2];
1211
- fourthByte = buf[i + 3];
1212
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1213
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
1214
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1215
- codePoint = tempCodePoint;
1216
- }
1217
- }
1218
- }
1219
- }
1220
-
1221
- if (codePoint === null) {
1222
- // we did not generate a valid codePoint so insert a
1223
- // replacement char (U+FFFD) and advance only 1 byte
1224
- codePoint = 0xFFFD;
1225
- bytesPerSequence = 1;
1226
- } else if (codePoint > 0xFFFF) {
1227
- // encode to utf16 (surrogate pair dance)
1228
- codePoint -= 0x10000;
1229
- res.push(codePoint >>> 10 & 0x3FF | 0xD800);
1230
- codePoint = 0xDC00 | codePoint & 0x3FF;
1231
- }
1232
-
1233
- res.push(codePoint);
1234
- i += bytesPerSequence;
1235
- }
1236
-
1237
- return decodeCodePointsArray(res)
1238
- }
1239
-
1240
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1241
- // the lowest limit is Chrome, with 0x10000 args.
1242
- // We go 1 magnitude less, for safety
1243
- var MAX_ARGUMENTS_LENGTH = 0x1000;
1244
-
1245
- function decodeCodePointsArray (codePoints) {
1246
- var len = codePoints.length;
1247
- if (len <= MAX_ARGUMENTS_LENGTH) {
1248
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1249
- }
1250
-
1251
- // Decode in chunks to avoid "call stack size exceeded".
1252
- var res = '';
1253
- var i = 0;
1254
- while (i < len) {
1255
- res += String.fromCharCode.apply(
1256
- String,
1257
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1258
- );
1259
- }
1260
- return res
1261
- }
1262
-
1263
- function asciiSlice (buf, start, end) {
1264
- var ret = '';
1265
- end = Math.min(buf.length, end);
1266
-
1267
- for (var i = start; i < end; ++i) {
1268
- ret += String.fromCharCode(buf[i] & 0x7F);
1269
- }
1270
- return ret
1271
- }
1272
-
1273
- function latin1Slice (buf, start, end) {
1274
- var ret = '';
1275
- end = Math.min(buf.length, end);
1276
-
1277
- for (var i = start; i < end; ++i) {
1278
- ret += String.fromCharCode(buf[i]);
1279
- }
1280
- return ret
1281
- }
1282
-
1283
- function hexSlice (buf, start, end) {
1284
- var len = buf.length;
1285
-
1286
- if (!start || start < 0) start = 0;
1287
- if (!end || end < 0 || end > len) end = len;
1288
-
1289
- var out = '';
1290
- for (var i = start; i < end; ++i) {
1291
- out += toHex(buf[i]);
1292
- }
1293
- return out
1294
- }
1295
-
1296
- function utf16leSlice (buf, start, end) {
1297
- var bytes = buf.slice(start, end);
1298
- var res = '';
1299
- for (var i = 0; i < bytes.length; i += 2) {
1300
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1301
- }
1302
- return res
1303
- }
1304
-
1305
- Buffer.prototype.slice = function slice (start, end) {
1306
- var len = this.length;
1307
- start = ~~start;
1308
- end = end === undefined ? len : ~~end;
1309
-
1310
- if (start < 0) {
1311
- start += len;
1312
- if (start < 0) start = 0;
1313
- } else if (start > len) {
1314
- start = len;
1315
- }
1316
-
1317
- if (end < 0) {
1318
- end += len;
1319
- if (end < 0) end = 0;
1320
- } else if (end > len) {
1321
- end = len;
1322
- }
1323
-
1324
- if (end < start) end = start;
1325
-
1326
- var newBuf;
1327
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1328
- newBuf = this.subarray(start, end);
1329
- newBuf.__proto__ = Buffer.prototype;
1330
- } else {
1331
- var sliceLen = end - start;
1332
- newBuf = new Buffer(sliceLen, undefined);
1333
- for (var i = 0; i < sliceLen; ++i) {
1334
- newBuf[i] = this[i + start];
1335
- }
1336
- }
1337
-
1338
- return newBuf
1339
- };
1340
-
1341
- /*
1342
- * Need to make sure that buffer isn't trying to write out of bounds.
1343
- */
1344
- function checkOffset (offset, ext, length) {
1345
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1346
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1347
- }
1348
-
1349
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1350
- offset = offset | 0;
1351
- byteLength = byteLength | 0;
1352
- if (!noAssert) checkOffset(offset, byteLength, this.length);
1353
-
1354
- var val = this[offset];
1355
- var mul = 1;
1356
- var i = 0;
1357
- while (++i < byteLength && (mul *= 0x100)) {
1358
- val += this[offset + i] * mul;
1359
- }
1360
-
1361
- return val
1362
- };
1363
-
1364
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1365
- offset = offset | 0;
1366
- byteLength = byteLength | 0;
1367
- if (!noAssert) {
1368
- checkOffset(offset, byteLength, this.length);
1369
- }
1370
-
1371
- var val = this[offset + --byteLength];
1372
- var mul = 1;
1373
- while (byteLength > 0 && (mul *= 0x100)) {
1374
- val += this[offset + --byteLength] * mul;
1375
- }
1376
-
1377
- return val
1378
- };
1379
-
1380
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1381
- if (!noAssert) checkOffset(offset, 1, this.length);
1382
- return this[offset]
1383
- };
1384
-
1385
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1386
- if (!noAssert) checkOffset(offset, 2, this.length);
1387
- return this[offset] | (this[offset + 1] << 8)
1388
- };
1389
-
1390
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1391
- if (!noAssert) checkOffset(offset, 2, this.length);
1392
- return (this[offset] << 8) | this[offset + 1]
1393
- };
1394
-
1395
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1396
- if (!noAssert) checkOffset(offset, 4, this.length);
1397
-
1398
- return ((this[offset]) |
1399
- (this[offset + 1] << 8) |
1400
- (this[offset + 2] << 16)) +
1401
- (this[offset + 3] * 0x1000000)
1402
- };
1403
-
1404
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1405
- if (!noAssert) checkOffset(offset, 4, this.length);
1406
-
1407
- return (this[offset] * 0x1000000) +
1408
- ((this[offset + 1] << 16) |
1409
- (this[offset + 2] << 8) |
1410
- this[offset + 3])
1411
- };
1412
-
1413
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1414
- offset = offset | 0;
1415
- byteLength = byteLength | 0;
1416
- if (!noAssert) checkOffset(offset, byteLength, this.length);
1417
-
1418
- var val = this[offset];
1419
- var mul = 1;
1420
- var i = 0;
1421
- while (++i < byteLength && (mul *= 0x100)) {
1422
- val += this[offset + i] * mul;
1423
- }
1424
- mul *= 0x80;
1425
-
1426
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1427
-
1428
- return val
1429
- };
1430
-
1431
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1432
- offset = offset | 0;
1433
- byteLength = byteLength | 0;
1434
- if (!noAssert) checkOffset(offset, byteLength, this.length);
1435
-
1436
- var i = byteLength;
1437
- var mul = 1;
1438
- var val = this[offset + --i];
1439
- while (i > 0 && (mul *= 0x100)) {
1440
- val += this[offset + --i] * mul;
1441
- }
1442
- mul *= 0x80;
1443
-
1444
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1445
-
1446
- return val
1447
- };
1448
-
1449
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1450
- if (!noAssert) checkOffset(offset, 1, this.length);
1451
- if (!(this[offset] & 0x80)) return (this[offset])
1452
- return ((0xff - this[offset] + 1) * -1)
1453
- };
1454
-
1455
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1456
- if (!noAssert) checkOffset(offset, 2, this.length);
1457
- var val = this[offset] | (this[offset + 1] << 8);
1458
- return (val & 0x8000) ? val | 0xFFFF0000 : val
1459
- };
1460
-
1461
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1462
- if (!noAssert) checkOffset(offset, 2, this.length);
1463
- var val = this[offset + 1] | (this[offset] << 8);
1464
- return (val & 0x8000) ? val | 0xFFFF0000 : val
1465
- };
1466
-
1467
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1468
- if (!noAssert) checkOffset(offset, 4, this.length);
1469
-
1470
- return (this[offset]) |
1471
- (this[offset + 1] << 8) |
1472
- (this[offset + 2] << 16) |
1473
- (this[offset + 3] << 24)
1474
- };
1475
-
1476
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1477
- if (!noAssert) checkOffset(offset, 4, this.length);
1478
-
1479
- return (this[offset] << 24) |
1480
- (this[offset + 1] << 16) |
1481
- (this[offset + 2] << 8) |
1482
- (this[offset + 3])
1483
- };
1484
-
1485
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1486
- if (!noAssert) checkOffset(offset, 4, this.length);
1487
- return read(this, offset, true, 23, 4)
1488
- };
1489
-
1490
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1491
- if (!noAssert) checkOffset(offset, 4, this.length);
1492
- return read(this, offset, false, 23, 4)
1493
- };
1494
-
1495
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1496
- if (!noAssert) checkOffset(offset, 8, this.length);
1497
- return read(this, offset, true, 52, 8)
1498
- };
1499
-
1500
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1501
- if (!noAssert) checkOffset(offset, 8, this.length);
1502
- return read(this, offset, false, 52, 8)
1503
- };
1504
-
1505
- function checkInt (buf, value, offset, ext, max, min) {
1506
- if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1507
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1508
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
1509
- }
1510
-
1511
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1512
- value = +value;
1513
- offset = offset | 0;
1514
- byteLength = byteLength | 0;
1515
- if (!noAssert) {
1516
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1517
- checkInt(this, value, offset, byteLength, maxBytes, 0);
1518
- }
1519
-
1520
- var mul = 1;
1521
- var i = 0;
1522
- this[offset] = value & 0xFF;
1523
- while (++i < byteLength && (mul *= 0x100)) {
1524
- this[offset + i] = (value / mul) & 0xFF;
1525
- }
1526
-
1527
- return offset + byteLength
1528
- };
1529
-
1530
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1531
- value = +value;
1532
- offset = offset | 0;
1533
- byteLength = byteLength | 0;
1534
- if (!noAssert) {
1535
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1536
- checkInt(this, value, offset, byteLength, maxBytes, 0);
1537
- }
1538
-
1539
- var i = byteLength - 1;
1540
- var mul = 1;
1541
- this[offset + i] = value & 0xFF;
1542
- while (--i >= 0 && (mul *= 0x100)) {
1543
- this[offset + i] = (value / mul) & 0xFF;
1544
- }
1545
-
1546
- return offset + byteLength
1547
- };
1548
-
1549
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1550
- value = +value;
1551
- offset = offset | 0;
1552
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
1553
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1554
- this[offset] = (value & 0xff);
1555
- return offset + 1
1556
- };
1557
-
1558
- function objectWriteUInt16 (buf, value, offset, littleEndian) {
1559
- if (value < 0) value = 0xffff + value + 1;
1560
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1561
- buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1562
- (littleEndian ? i : 1 - i) * 8;
1563
- }
1564
- }
1565
-
1566
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1567
- value = +value;
1568
- offset = offset | 0;
1569
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1570
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1571
- this[offset] = (value & 0xff);
1572
- this[offset + 1] = (value >>> 8);
1573
- } else {
1574
- objectWriteUInt16(this, value, offset, true);
1575
- }
1576
- return offset + 2
1577
- };
1578
-
1579
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1580
- value = +value;
1581
- offset = offset | 0;
1582
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1583
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1584
- this[offset] = (value >>> 8);
1585
- this[offset + 1] = (value & 0xff);
1586
- } else {
1587
- objectWriteUInt16(this, value, offset, false);
1588
- }
1589
- return offset + 2
1590
- };
1591
-
1592
- function objectWriteUInt32 (buf, value, offset, littleEndian) {
1593
- if (value < 0) value = 0xffffffff + value + 1;
1594
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1595
- buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
1596
- }
1597
- }
1598
-
1599
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1600
- value = +value;
1601
- offset = offset | 0;
1602
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1603
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1604
- this[offset + 3] = (value >>> 24);
1605
- this[offset + 2] = (value >>> 16);
1606
- this[offset + 1] = (value >>> 8);
1607
- this[offset] = (value & 0xff);
1608
- } else {
1609
- objectWriteUInt32(this, value, offset, true);
1610
- }
1611
- return offset + 4
1612
- };
1613
-
1614
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1615
- value = +value;
1616
- offset = offset | 0;
1617
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1618
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1619
- this[offset] = (value >>> 24);
1620
- this[offset + 1] = (value >>> 16);
1621
- this[offset + 2] = (value >>> 8);
1622
- this[offset + 3] = (value & 0xff);
1623
- } else {
1624
- objectWriteUInt32(this, value, offset, false);
1625
- }
1626
- return offset + 4
1627
- };
1628
-
1629
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1630
- value = +value;
1631
- offset = offset | 0;
1632
- if (!noAssert) {
1633
- var limit = Math.pow(2, 8 * byteLength - 1);
1634
-
1635
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
1636
- }
1637
-
1638
- var i = 0;
1639
- var mul = 1;
1640
- var sub = 0;
1641
- this[offset] = value & 0xFF;
1642
- while (++i < byteLength && (mul *= 0x100)) {
1643
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1644
- sub = 1;
1645
- }
1646
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
1647
- }
1648
-
1649
- return offset + byteLength
1650
- };
1651
-
1652
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1653
- value = +value;
1654
- offset = offset | 0;
1655
- if (!noAssert) {
1656
- var limit = Math.pow(2, 8 * byteLength - 1);
1657
-
1658
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
1659
- }
1660
-
1661
- var i = byteLength - 1;
1662
- var mul = 1;
1663
- var sub = 0;
1664
- this[offset + i] = value & 0xFF;
1665
- while (--i >= 0 && (mul *= 0x100)) {
1666
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1667
- sub = 1;
1668
- }
1669
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
1670
- }
1671
-
1672
- return offset + byteLength
1673
- };
1674
-
1675
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1676
- value = +value;
1677
- offset = offset | 0;
1678
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
1679
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1680
- if (value < 0) value = 0xff + value + 1;
1681
- this[offset] = (value & 0xff);
1682
- return offset + 1
1683
- };
1684
-
1685
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1686
- value = +value;
1687
- offset = offset | 0;
1688
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1689
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1690
- this[offset] = (value & 0xff);
1691
- this[offset + 1] = (value >>> 8);
1692
- } else {
1693
- objectWriteUInt16(this, value, offset, true);
1694
- }
1695
- return offset + 2
1696
- };
1697
-
1698
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1699
- value = +value;
1700
- offset = offset | 0;
1701
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1702
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1703
- this[offset] = (value >>> 8);
1704
- this[offset + 1] = (value & 0xff);
1705
- } else {
1706
- objectWriteUInt16(this, value, offset, false);
1707
- }
1708
- return offset + 2
1709
- };
1710
-
1711
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1712
- value = +value;
1713
- offset = offset | 0;
1714
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1715
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1716
- this[offset] = (value & 0xff);
1717
- this[offset + 1] = (value >>> 8);
1718
- this[offset + 2] = (value >>> 16);
1719
- this[offset + 3] = (value >>> 24);
1720
- } else {
1721
- objectWriteUInt32(this, value, offset, true);
1722
- }
1723
- return offset + 4
1724
- };
1725
-
1726
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1727
- value = +value;
1728
- offset = offset | 0;
1729
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1730
- if (value < 0) value = 0xffffffff + value + 1;
1731
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1732
- this[offset] = (value >>> 24);
1733
- this[offset + 1] = (value >>> 16);
1734
- this[offset + 2] = (value >>> 8);
1735
- this[offset + 3] = (value & 0xff);
1736
- } else {
1737
- objectWriteUInt32(this, value, offset, false);
1738
- }
1739
- return offset + 4
1740
- };
1741
-
1742
- function checkIEEE754 (buf, value, offset, ext, max, min) {
1743
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
1744
- if (offset < 0) throw new RangeError('Index out of range')
1745
- }
1746
-
1747
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
1748
- if (!noAssert) {
1749
- checkIEEE754(buf, value, offset, 4);
1750
- }
1751
- write(buf, value, offset, littleEndian, 23, 4);
1752
- return offset + 4
1753
- }
1754
-
1755
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1756
- return writeFloat(this, value, offset, true, noAssert)
1757
- };
1758
-
1759
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1760
- return writeFloat(this, value, offset, false, noAssert)
1761
- };
1762
-
1763
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
1764
- if (!noAssert) {
1765
- checkIEEE754(buf, value, offset, 8);
1766
- }
1767
- write(buf, value, offset, littleEndian, 52, 8);
1768
- return offset + 8
1769
- }
1770
-
1771
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1772
- return writeDouble(this, value, offset, true, noAssert)
1773
- };
1774
-
1775
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1776
- return writeDouble(this, value, offset, false, noAssert)
1777
- };
1778
-
1779
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1780
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1781
- if (!start) start = 0;
1782
- if (!end && end !== 0) end = this.length;
1783
- if (targetStart >= target.length) targetStart = target.length;
1784
- if (!targetStart) targetStart = 0;
1785
- if (end > 0 && end < start) end = start;
1786
-
1787
- // Copy 0 bytes; we're done
1788
- if (end === start) return 0
1789
- if (target.length === 0 || this.length === 0) return 0
1790
-
1791
- // Fatal error conditions
1792
- if (targetStart < 0) {
1793
- throw new RangeError('targetStart out of bounds')
1794
- }
1795
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1796
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
1797
-
1798
- // Are we oob?
1799
- if (end > this.length) end = this.length;
1800
- if (target.length - targetStart < end - start) {
1801
- end = target.length - targetStart + start;
1802
- }
1803
-
1804
- var len = end - start;
1805
- var i;
1806
-
1807
- if (this === target && start < targetStart && targetStart < end) {
1808
- // descending copy from end
1809
- for (i = len - 1; i >= 0; --i) {
1810
- target[i + targetStart] = this[i + start];
1811
- }
1812
- } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1813
- // ascending copy from start
1814
- for (i = 0; i < len; ++i) {
1815
- target[i + targetStart] = this[i + start];
1816
- }
1817
- } else {
1818
- Uint8Array.prototype.set.call(
1819
- target,
1820
- this.subarray(start, start + len),
1821
- targetStart
1822
- );
1823
- }
1824
-
1825
- return len
1826
- };
1827
-
1828
- // Usage:
1829
- // buffer.fill(number[, offset[, end]])
1830
- // buffer.fill(buffer[, offset[, end]])
1831
- // buffer.fill(string[, offset[, end]][, encoding])
1832
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
1833
- // Handle string cases:
1834
- if (typeof val === 'string') {
1835
- if (typeof start === 'string') {
1836
- encoding = start;
1837
- start = 0;
1838
- end = this.length;
1839
- } else if (typeof end === 'string') {
1840
- encoding = end;
1841
- end = this.length;
1842
- }
1843
- if (val.length === 1) {
1844
- var code = val.charCodeAt(0);
1845
- if (code < 256) {
1846
- val = code;
1847
- }
1848
- }
1849
- if (encoding !== undefined && typeof encoding !== 'string') {
1850
- throw new TypeError('encoding must be a string')
1851
- }
1852
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1853
- throw new TypeError('Unknown encoding: ' + encoding)
1854
- }
1855
- } else if (typeof val === 'number') {
1856
- val = val & 255;
1857
- }
1858
-
1859
- // Invalid ranges are not set to a default, so can range check early.
1860
- if (start < 0 || this.length < start || this.length < end) {
1861
- throw new RangeError('Out of range index')
1862
- }
1863
-
1864
- if (end <= start) {
1865
- return this
1866
- }
1867
-
1868
- start = start >>> 0;
1869
- end = end === undefined ? this.length : end >>> 0;
1870
-
1871
- if (!val) val = 0;
1872
-
1873
- var i;
1874
- if (typeof val === 'number') {
1875
- for (i = start; i < end; ++i) {
1876
- this[i] = val;
1877
- }
1878
- } else {
1879
- var bytes = internalIsBuffer(val)
1880
- ? val
1881
- : utf8ToBytes(new Buffer(val, encoding).toString());
1882
- var len = bytes.length;
1883
- for (i = 0; i < end - start; ++i) {
1884
- this[i + start] = bytes[i % len];
1885
- }
1886
- }
1887
-
1888
- return this
1889
- };
1890
-
1891
- // HELPER FUNCTIONS
1892
- // ================
1893
-
1894
- var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
1895
-
1896
- function base64clean (str) {
1897
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
1898
- str = stringtrim(str).replace(INVALID_BASE64_RE, '');
1899
- // Node converts strings with length < 2 to ''
1900
- if (str.length < 2) return ''
1901
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1902
- while (str.length % 4 !== 0) {
1903
- str = str + '=';
1904
- }
1905
- return str
1906
- }
1907
-
1908
- function stringtrim (str) {
1909
- if (str.trim) return str.trim()
1910
- return str.replace(/^\s+|\s+$/g, '')
1911
- }
1912
-
1913
- function toHex (n) {
1914
- if (n < 16) return '0' + n.toString(16)
1915
- return n.toString(16)
1916
- }
1917
-
1918
- function utf8ToBytes (string, units) {
1919
- units = units || Infinity;
1920
- var codePoint;
1921
- var length = string.length;
1922
- var leadSurrogate = null;
1923
- var bytes = [];
1924
-
1925
- for (var i = 0; i < length; ++i) {
1926
- codePoint = string.charCodeAt(i);
1927
-
1928
- // is surrogate component
1929
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
1930
- // last char was a lead
1931
- if (!leadSurrogate) {
1932
- // no lead yet
1933
- if (codePoint > 0xDBFF) {
1934
- // unexpected trail
1935
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1936
- continue
1937
- } else if (i + 1 === length) {
1938
- // unpaired lead
1939
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1940
- continue
1941
- }
1942
-
1943
- // valid lead
1944
- leadSurrogate = codePoint;
1945
-
1946
- continue
1947
- }
1948
-
1949
- // 2 leads in a row
1950
- if (codePoint < 0xDC00) {
1951
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1952
- leadSurrogate = codePoint;
1953
- continue
1954
- }
1955
-
1956
- // valid surrogate pair
1957
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
1958
- } else if (leadSurrogate) {
1959
- // valid bmp char, but last char was a lead
1960
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1961
- }
1962
-
1963
- leadSurrogate = null;
1964
-
1965
- // encode utf8
1966
- if (codePoint < 0x80) {
1967
- if ((units -= 1) < 0) break
1968
- bytes.push(codePoint);
1969
- } else if (codePoint < 0x800) {
1970
- if ((units -= 2) < 0) break
1971
- bytes.push(
1972
- codePoint >> 0x6 | 0xC0,
1973
- codePoint & 0x3F | 0x80
1974
- );
1975
- } else if (codePoint < 0x10000) {
1976
- if ((units -= 3) < 0) break
1977
- bytes.push(
1978
- codePoint >> 0xC | 0xE0,
1979
- codePoint >> 0x6 & 0x3F | 0x80,
1980
- codePoint & 0x3F | 0x80
1981
- );
1982
- } else if (codePoint < 0x110000) {
1983
- if ((units -= 4) < 0) break
1984
- bytes.push(
1985
- codePoint >> 0x12 | 0xF0,
1986
- codePoint >> 0xC & 0x3F | 0x80,
1987
- codePoint >> 0x6 & 0x3F | 0x80,
1988
- codePoint & 0x3F | 0x80
1989
- );
1990
- } else {
1991
- throw new Error('Invalid code point')
1992
- }
1993
- }
1994
-
1995
- return bytes
1996
- }
1997
-
1998
- function asciiToBytes (str) {
1999
- var byteArray = [];
2000
- for (var i = 0; i < str.length; ++i) {
2001
- // Node's code seems to be doing this and not & 0x7F..
2002
- byteArray.push(str.charCodeAt(i) & 0xFF);
2003
- }
2004
- return byteArray
2005
- }
2006
-
2007
- function utf16leToBytes (str, units) {
2008
- var c, hi, lo;
2009
- var byteArray = [];
2010
- for (var i = 0; i < str.length; ++i) {
2011
- if ((units -= 2) < 0) break
2012
-
2013
- c = str.charCodeAt(i);
2014
- hi = c >> 8;
2015
- lo = c % 256;
2016
- byteArray.push(lo);
2017
- byteArray.push(hi);
2018
- }
2019
-
2020
- return byteArray
2021
- }
2022
-
2023
-
2024
- function base64ToBytes (str) {
2025
- return toByteArray(base64clean(str))
2026
- }
2027
-
2028
- function blitBuffer (src, dst, offset, length) {
2029
- for (var i = 0; i < length; ++i) {
2030
- if ((i + offset >= dst.length) || (i >= src.length)) break
2031
- dst[i + offset] = src[i];
2032
- }
2033
- return i
2034
- }
2035
-
2036
- function isnan (val) {
2037
- return val !== val // eslint-disable-line no-self-compare
2038
- }
2039
-
2040
-
2041
- // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
2042
- // The _isBuffer check is for Safari 5-7 support, because it's missing
2043
- // Object.prototype.constructor. Remove this eventually
2044
- function isBuffer(obj) {
2045
- return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
2046
- }
2047
-
2048
- function isFastBuffer (obj) {
2049
- return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
2050
- }
2051
-
2052
- // For Node v0.10 support. Remove this eventually.
2053
- function isSlowBuffer (obj) {
2054
- return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
2055
- }
2056
-
2057
- // Lodash implementation of `get`
2058
-
2059
- const charCodeOfDot = '.'.charCodeAt(0);
2060
- const reEscapeChar = /\\(\\)?/g;
2061
- const rePropName = RegExp(
2062
- // Match anything that isn't a dot or bracket.
2063
- '[^.[\\]]+' + '|' +
2064
- // Or match property names within brackets.
2065
- '\\[(?:' +
2066
- // Match a non-string expression.
2067
- '([^"\'][^[]*)' + '|' +
2068
- // Or match strings (supports escaping characters).
2069
- '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' +
2070
- ')\\]'+ '|' +
2071
- // Or match "" as the space between consecutive dots or empty brackets.
2072
- '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))'
2073
- , 'g');
2074
- const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
2075
- const reIsPlainProp = /^\w*$/;
2076
- const getTag = function(value){
2077
- return Object.prototype.toString.call(value);
2078
- };
2079
- const isSymbol = function(value){
2080
- const type = typeof value;
2081
- return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]');
2082
- };
2083
- const isKey = function(value, object){
2084
- if(Array.isArray(value)){
2085
- return false;
2086
- }
2087
- const type = typeof value;
2088
- if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){
2089
- return true;
2090
- }
2091
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
2092
- (object != null && value in Object(object));
2093
- };
2094
- const stringToPath = function(string){
2095
- const result = [];
2096
- if(string.charCodeAt(0) === charCodeOfDot){
2097
- result.push('');
2098
- }
2099
- string.replace(rePropName, function(match, expression, quote, subString){
2100
- let key = match;
2101
- if(quote){
2102
- key = subString.replace(reEscapeChar, '$1');
2103
- }else if(expression){
2104
- key = expression.trim();
2105
- }
2106
- result.push(key);
2107
- });
2108
- return result;
2109
- };
2110
- const castPath = function(value, object){
2111
- if(Array.isArray(value)){
2112
- return value;
2113
- } else {
2114
- return isKey(value, object) ? [value] : stringToPath(value);
2115
- }
2116
- };
2117
- const toKey = function(value){
2118
- if(typeof value === 'string' || isSymbol(value))
2119
- return value;
2120
- const result = `${value}`;
2121
- // eslint-disable-next-line
2122
- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
2123
- };
2124
- const get = function(object, path){
2125
- path = castPath(path, object);
2126
- let index = 0;
2127
- const length = path.length;
2128
- while(object != null && index < length){
2129
- object = object[toKey(path[index++])];
2130
- }
2131
- return (index && index === length) ? object : undefined;
2132
- };
2133
-
2134
- const is_object = function(obj){
2135
- return typeof obj === 'object' && obj !== null && ! Array.isArray(obj);
2136
- };
2137
-
2138
- const normalize_columns = function(columns){
2139
- if(columns === undefined || columns === null){
2140
- return [undefined, undefined];
2141
- }
2142
- if(typeof columns !== 'object'){
2143
- return [Error('Invalid option "columns": expect an array or an object')];
2144
- }
2145
- if(!Array.isArray(columns)){
2146
- const newcolumns = [];
2147
- for(const k in columns){
2148
- newcolumns.push({
2149
- key: k,
2150
- header: columns[k]
2151
- });
2152
- }
2153
- columns = newcolumns;
2154
- }else {
2155
- const newcolumns = [];
2156
- for(const column of columns){
2157
- if(typeof column === 'string'){
2158
- newcolumns.push({
2159
- key: column,
2160
- header: column
2161
- });
2162
- }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){
2163
- if(!column.key){
2164
- return [Error('Invalid column definition: property "key" is required')];
2165
- }
2166
- if(column.header === undefined){
2167
- column.header = column.key;
2168
- }
2169
- newcolumns.push(column);
2170
- }else {
2171
- return [Error('Invalid column definition: expect a string or an object')];
2172
- }
2173
- }
2174
- columns = newcolumns;
2175
- }
2176
- return [undefined, columns];
2177
- };
2178
-
2179
- class CsvError extends Error {
2180
- constructor(code, message, ...contexts) {
2181
- if(Array.isArray(message)) message = message.join(' ');
2182
- super(message);
2183
- if(Error.captureStackTrace !== undefined){
2184
- Error.captureStackTrace(this, CsvError);
2185
- }
2186
- this.code = code;
2187
- for(const context of contexts){
2188
- for(const key in context){
2189
- const value = context[key];
2190
- this[key] = isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value));
2191
- }
2192
- }
2193
- }
2194
- }
2195
-
2196
- const underscore = function(str){
2197
- return str.replace(/([A-Z])/g, function(_, match){
2198
- return '_' + match.toLowerCase();
2199
- });
2200
- };
2201
-
2202
- const normalize_options = function(opts) {
2203
- const options = {};
2204
- // Merge with user options
2205
- for(const opt in opts){
2206
- options[underscore(opt)] = opts[opt];
2207
- }
2208
- // Normalize option `bom`
2209
- if(options.bom === undefined || options.bom === null || options.bom === false){
2210
- options.bom = false;
2211
- }else if(options.bom !== true){
2212
- return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [
2213
- 'option `bom` is optional and must be a boolean value,',
2214
- `got ${JSON.stringify(options.bom)}`
2215
- ])];
2216
- }
2217
- // Normalize option `delimiter`
2218
- if(options.delimiter === undefined || options.delimiter === null){
2219
- options.delimiter = ',';
2220
- }else if(isBuffer(options.delimiter)){
2221
- options.delimiter = options.delimiter.toString();
2222
- }else if(typeof options.delimiter !== 'string'){
2223
- return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [
2224
- 'option `delimiter` must be a buffer or a string,',
2225
- `got ${JSON.stringify(options.delimiter)}`
2226
- ])];
2227
- }
2228
- // Normalize option `quote`
2229
- if(options.quote === undefined || options.quote === null){
2230
- options.quote = '"';
2231
- }else if(options.quote === true){
2232
- options.quote = '"';
2233
- }else if(options.quote === false){
2234
- options.quote = '';
2235
- }else if (isBuffer(options.quote)){
2236
- options.quote = options.quote.toString();
2237
- }else if(typeof options.quote !== 'string'){
2238
- return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [
2239
- 'option `quote` must be a boolean, a buffer or a string,',
2240
- `got ${JSON.stringify(options.quote)}`
2241
- ])];
2242
- }
2243
- // Normalize option `quoted`
2244
- if(options.quoted === undefined || options.quoted === null){
2245
- options.quoted = false;
2246
- }
2247
- // Normalize option `escape_formulas`
2248
- if(options.escape_formulas === undefined || options.escape_formulas === null){
2249
- options.escape_formulas = false;
2250
- }else if(typeof options.escape_formulas !== 'boolean'){
2251
- return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [
2252
- 'option `escape_formulas` must be a boolean,',
2253
- `got ${JSON.stringify(options.escape_formulas)}`
2254
- ])];
2255
- }
2256
- // Normalize option `quoted_empty`
2257
- if(options.quoted_empty === undefined || options.quoted_empty === null){
2258
- options.quoted_empty = undefined;
2259
- }
2260
- // Normalize option `quoted_match`
2261
- if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){
2262
- options.quoted_match = null;
2263
- }else if(!Array.isArray(options.quoted_match)){
2264
- options.quoted_match = [options.quoted_match];
2265
- }
2266
- if(options.quoted_match){
2267
- for(const quoted_match of options.quoted_match){
2268
- const isString = typeof quoted_match === 'string';
2269
- const isRegExp = quoted_match instanceof RegExp;
2270
- if(!isString && !isRegExp){
2271
- return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)];
2272
- }
2273
- }
2274
- }
2275
- // Normalize option `quoted_string`
2276
- if(options.quoted_string === undefined || options.quoted_string === null){
2277
- options.quoted_string = false;
2278
- }
2279
- // Normalize option `eof`
2280
- if(options.eof === undefined || options.eof === null){
2281
- options.eof = true;
2282
- }
2283
- // Normalize option `escape`
2284
- if(options.escape === undefined || options.escape === null){
2285
- options.escape = '"';
2286
- }else if(isBuffer(options.escape)){
2287
- options.escape = options.escape.toString();
2288
- }else if(typeof options.escape !== 'string'){
2289
- return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)];
2290
- }
2291
- if (options.escape.length > 1){
2292
- return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)];
2293
- }
2294
- // Normalize option `header`
2295
- if(options.header === undefined || options.header === null){
2296
- options.header = false;
2297
- }
2298
- // Normalize option `columns`
2299
- const [errColumns, columns] = normalize_columns(options.columns);
2300
- if(errColumns !== undefined) return [errColumns];
2301
- options.columns = columns;
2302
- // Normalize option `quoted`
2303
- if(options.quoted === undefined || options.quoted === null){
2304
- options.quoted = false;
2305
- }
2306
- // Normalize option `cast`
2307
- if(options.cast === undefined || options.cast === null){
2308
- options.cast = {};
2309
- }
2310
- // Normalize option cast.bigint
2311
- if(options.cast.bigint === undefined || options.cast.bigint === null){
2312
- // Cast boolean to string by default
2313
- options.cast.bigint = value => '' + value;
2314
- }
2315
- // Normalize option cast.boolean
2316
- if(options.cast.boolean === undefined || options.cast.boolean === null){
2317
- // Cast boolean to string by default
2318
- options.cast.boolean = value => value ? '1' : '';
2319
- }
2320
- // Normalize option cast.date
2321
- if(options.cast.date === undefined || options.cast.date === null){
2322
- // Cast date to timestamp string by default
2323
- options.cast.date = value => '' + value.getTime();
2324
- }
2325
- // Normalize option cast.number
2326
- if(options.cast.number === undefined || options.cast.number === null){
2327
- // Cast number to string using native casting by default
2328
- options.cast.number = value => '' + value;
2329
- }
2330
- // Normalize option cast.object
2331
- if(options.cast.object === undefined || options.cast.object === null){
2332
- // Stringify object as JSON by default
2333
- options.cast.object = value => JSON.stringify(value);
2334
- }
2335
- // Normalize option cast.string
2336
- if(options.cast.string === undefined || options.cast.string === null){
2337
- // Leave string untouched
2338
- options.cast.string = function(value){return value;};
2339
- }
2340
- // Normalize option `on_record`
2341
- if(options.on_record !== undefined && typeof options.on_record !== 'function'){
2342
- return [Error(`Invalid Option: "on_record" must be a function.`)];
2343
- }
2344
- // Normalize option `record_delimiter`
2345
- if(options.record_delimiter === undefined || options.record_delimiter === null){
2346
- options.record_delimiter = '\n';
2347
- }else if(isBuffer(options.record_delimiter)){
2348
- options.record_delimiter = options.record_delimiter.toString();
2349
- }else if(typeof options.record_delimiter !== 'string'){
2350
- return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)];
2351
- }
2352
- switch(options.record_delimiter){
2353
- case 'unix':
2354
- options.record_delimiter = "\n";
2355
- break;
2356
- case 'mac':
2357
- options.record_delimiter = "\r";
2358
- break;
2359
- case 'windows':
2360
- options.record_delimiter = "\r\n";
2361
- break;
2362
- case 'ascii':
2363
- options.record_delimiter = "\u001e";
2364
- break;
2365
- case 'unicode':
2366
- options.record_delimiter = "\u2028";
2367
- break;
2368
- }
2369
- return [undefined, options];
2370
- };
2371
-
2372
- const bom_utf8 = Buffer.from([239, 187, 191]);
2373
-
2374
- const stringifier = function(options, state, info){
2375
- return {
2376
- options: options,
2377
- state: state,
2378
- info: info,
2379
- __transform: function(chunk, push){
2380
- // Chunk validation
2381
- if(!Array.isArray(chunk) && typeof chunk !== 'object'){
2382
- return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`);
2383
- }
2384
- // Detect columns from the first record
2385
- if(this.info.records === 0){
2386
- if(Array.isArray(chunk)){
2387
- if(this.options.header === true && this.options.columns === undefined){
2388
- return Error('Undiscoverable Columns: header option requires column option or object records');
2389
- }
2390
- }else if(this.options.columns === undefined){
2391
- const [err, columns] = normalize_columns(Object.keys(chunk));
2392
- if(err) return;
2393
- this.options.columns = columns;
2394
- }
2395
- }
2396
- // Emit the header
2397
- if(this.info.records === 0){
2398
- this.bom(push);
2399
- const err = this.headers(push);
2400
- if(err) return err;
2401
- }
2402
- // Emit and stringify the record if an object or an array
2403
- try{
2404
- // this.emit('record', chunk, this.info.records);
2405
- if(this.options.on_record){
2406
- this.options.on_record(chunk, this.info.records);
2407
- }
2408
- }catch(err){
2409
- return err;
2410
- }
2411
- // Convert the record into a string
2412
- let err, chunk_string;
2413
- if(this.options.eof){
2414
- [err, chunk_string] = this.stringify(chunk);
2415
- if(err) return err;
2416
- if(chunk_string === undefined){
2417
- return;
2418
- }else {
2419
- chunk_string = chunk_string + this.options.record_delimiter;
2420
- }
2421
- }else {
2422
- [err, chunk_string] = this.stringify(chunk);
2423
- if(err) return err;
2424
- if(chunk_string === undefined){
2425
- return;
2426
- }else {
2427
- if(this.options.header || this.info.records){
2428
- chunk_string = this.options.record_delimiter + chunk_string;
2429
- }
2430
- }
2431
- }
2432
- // Emit the csv
2433
- this.info.records++;
2434
- push(chunk_string);
2435
- },
2436
- stringify: function(chunk, chunkIsHeader=false){
2437
- if(typeof chunk !== 'object'){
2438
- return [undefined, chunk];
2439
- }
2440
- const {columns} = this.options;
2441
- const record = [];
2442
- // Record is an array
2443
- if(Array.isArray(chunk)){
2444
- // We are getting an array but the user has specified output columns. In
2445
- // this case, we respect the columns indexes
2446
- if(columns){
2447
- chunk.splice(columns.length);
2448
- }
2449
- // Cast record elements
2450
- for(let i=0; i<chunk.length; i++){
2451
- const field = chunk[i];
2452
- const [err, value] = this.__cast(field, {
2453
- index: i, column: i, records: this.info.records, header: chunkIsHeader
2454
- });
2455
- if(err) return [err];
2456
- record[i] = [value, field];
2457
- }
2458
- // Record is a literal object
2459
- // `columns` is always defined: it is either provided or discovered.
2460
- }else {
2461
- for(let i=0; i<columns.length; i++){
2462
- const field = get(chunk, columns[i].key);
2463
- const [err, value] = this.__cast(field, {
2464
- index: i, column: columns[i].key, records: this.info.records, header: chunkIsHeader
2465
- });
2466
- if(err) return [err];
2467
- record[i] = [value, field];
2468
- }
2469
- }
2470
- let csvrecord = '';
2471
- for(let i=0; i<record.length; i++){
2472
- let options, err;
2473
- // eslint-disable-next-line
2474
- let [value, field] = record[i];
2475
- if(typeof value === "string"){
2476
- options = this.options;
2477
- }else if(is_object(value)){
2478
- options = value;
2479
- value = options.value;
2480
- delete options.value;
2481
- if(typeof value !== "string" && value !== undefined && value !== null){
2482
- if(err) return [Error(`Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(value)}`)];
2483
- }
2484
- options = {...this.options, ...options};
2485
- [err, options] = normalize_options(options);
2486
- if(err !== undefined){
2487
- return [err];
2488
- }
2489
- }else if(value === undefined || value === null){
2490
- options = this.options;
2491
- }else {
2492
- return [Error(`Invalid Casting Value: returned value must return a string, an object, null or undefined, got ${JSON.stringify(value)}`)];
2493
- }
2494
- const {delimiter, escape, quote, quoted, quoted_empty, quoted_string, quoted_match, record_delimiter, escape_formulas} = options;
2495
- if('' === value && '' === field){
2496
- let quotedMatch = quoted_match && quoted_match.filter(quoted_match => {
2497
- if(typeof quoted_match === 'string'){
2498
- return value.indexOf(quoted_match) !== -1;
2499
- }else {
2500
- return quoted_match.test(value);
2501
- }
2502
- });
2503
- quotedMatch = quotedMatch && quotedMatch.length > 0;
2504
- const shouldQuote = quotedMatch || true === quoted_empty ||
2505
- (true === quoted_string && false !== quoted_empty);
2506
- if(shouldQuote === true){
2507
- value = quote + value + quote;
2508
- }
2509
- csvrecord += value;
2510
- }else if(value){
2511
- if(typeof value !== 'string'){
2512
- return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)];
2513
- }
2514
- const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0;
2515
- const containsQuote = (quote !== '') && value.indexOf(quote) >= 0;
2516
- const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote);
2517
- const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0;
2518
- const quotedString = quoted_string && typeof field === 'string';
2519
- let quotedMatch = quoted_match && quoted_match.filter(quoted_match => {
2520
- if(typeof quoted_match === 'string'){
2521
- return value.indexOf(quoted_match) !== -1;
2522
- }else {
2523
- return quoted_match.test(value);
2524
- }
2525
- });
2526
- quotedMatch = quotedMatch && quotedMatch.length > 0;
2527
- // See https://github.com/adaltas/node-csv/pull/387
2528
- // More about CSV injection or formula injection, when websites embed
2529
- // untrusted input inside CSV files:
2530
- // https://owasp.org/www-community/attacks/CSV_Injection
2531
- // http://georgemauer.net/2017/10/07/csv-injection.html
2532
- // Apple Numbers unicode normalization is empirical from testing
2533
- if (escape_formulas) {
2534
- switch (value[0]) {
2535
- case '=':
2536
- case '+':
2537
- case '-':
2538
- case '@':
2539
- case '\t':
2540
- case '\r':
2541
- case '\uFF1D': // Unicode '='
2542
- case '\uFF0B': // Unicode '+'
2543
- case '\uFF0D': // Unicode '-'
2544
- case '\uFF20': // Unicode '@'
2545
- value = `'${value}`;
2546
- break;
2547
- }
2548
- }
2549
- const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch;
2550
- if(shouldQuote === true && containsEscape === true){
2551
- const regexp = escape === '\\'
2552
- ? new RegExp(escape + escape, 'g')
2553
- : new RegExp(escape, 'g');
2554
- value = value.replace(regexp, escape + escape);
2555
- }
2556
- if(containsQuote === true){
2557
- const regexp = new RegExp(quote,'g');
2558
- value = value.replace(regexp, escape + quote);
2559
- }
2560
- if(shouldQuote === true){
2561
- value = quote + value + quote;
2562
- }
2563
- csvrecord += value;
2564
- }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){
2565
- csvrecord += quote + quote;
2566
- }
2567
- if(i !== record.length - 1){
2568
- csvrecord += delimiter;
2569
- }
2570
- }
2571
- return [undefined, csvrecord];
2572
- },
2573
- bom: function(push){
2574
- if(this.options.bom !== true){
2575
- return;
2576
- }
2577
- push(bom_utf8);
2578
- },
2579
- headers: function(push){
2580
- if(this.options.header === false){
2581
- return;
2582
- }
2583
- if(this.options.columns === undefined){
2584
- return;
2585
- }
2586
- let err;
2587
- let headers = this.options.columns.map(column => column.header);
2588
- if(this.options.eof){
2589
- [err, headers] = this.stringify(headers, true);
2590
- headers += this.options.record_delimiter;
2591
- }else {
2592
- [err, headers] = this.stringify(headers);
2593
- }
2594
- if(err) return err;
2595
- push(headers);
2596
- },
2597
- __cast: function(value, context){
2598
- const type = typeof value;
2599
- try{
2600
- if(type === 'string'){ // Fine for 99% of the cases
2601
- return [undefined, this.options.cast.string(value, context)];
2602
- }else if(type === 'bigint'){
2603
- return [undefined, this.options.cast.bigint(value, context)];
2604
- }else if(type === 'number'){
2605
- return [undefined, this.options.cast.number(value, context)];
2606
- }else if(type === 'boolean'){
2607
- return [undefined, this.options.cast.boolean(value, context)];
2608
- }else if(value instanceof Date){
2609
- return [undefined, this.options.cast.date(value, context)];
2610
- }else if(type === 'object' && value !== null){
2611
- return [undefined, this.options.cast.object(value, context)];
2612
- }else {
2613
- return [undefined, value, value];
2614
- }
2615
- }catch(err){
2616
- return [err];
2617
- }
2618
- }
2619
- };
2620
- };
2621
-
2622
- const stringify = function(records, opts={}){
2623
- const data = [];
2624
- const [err, options] = normalize_options(opts);
2625
- if(err !== undefined) throw err;
2626
- const state = {
2627
- stop: false
2628
- };
2629
- // Information
2630
- const info = {
2631
- records: 0
2632
- };
2633
- const api = stringifier(options, state, info);
2634
- for(const record of records){
2635
- const err = api.__transform(record, function(record){
2636
- data.push(record);
2637
- });
2638
- if(err !== undefined) throw err;
2639
- }
2640
- if(data.length === 0){
2641
- api.bom((d) => {
2642
- data.push(d);
2643
- });
2644
- const err = api.headers((headers) => {
2645
- data.push(headers);
2646
- });
2647
- if(err !== undefined) throw err;
2648
- }
2649
- return data.join('');
2650
- };
2651
-
2652
- var styles = "/**\n *\n * IBM Confidential\n *\n * (C) Copyright IBM Corp. 2024\n *\n * The source code for this program is not published or otherwise\n * divested of its trade secrets, irrespective of what has been\n * deposited with the U. S. Copyright Office\n *\n * US Government Users Restricted Rights - Use, duplication or\n * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n *\n */\ncds-table-header-title,\ncds-table-header-description,\ncds-table-toolbar {\n position: sticky;\n width: var(--cds-chat-table-width, auto);\n left: 0;\n}\n\n:dir(rtl) cds-table-header-title,\n:dir(rtl) cds-table-header-description,\n:dir(rtl) cds-table-toolbar {\n left: unset;\n right: 0;\n}\n\ncds-table-header-title,\ncds-table-header-description {\n width: calc(var(--cds-chat-table-width, auto) - 1rem - 1rem);\n margin-left: -1rem;\n margin-right: -1rem;\n padding: 0 1rem;\n}\n\ncds-table-header-description {\n margin-bottom: -0.5rem;\n}\n\ncds-pagination {\n width: 100%;\n}";
2653
-
2654
- /**
2655
- *
2656
- * IBM Confidential
2657
- *
2658
- * (C) Copyright IBM Corp. 2024
2659
- *
2660
- * The source code for this program is not published or otherwise
2661
- * divested of its trade secrets, irrespective of what has been
2662
- * deposited with the U. S. Copyright Office
2663
- *
2664
- * US Government Users Restricted Rights - Use, duplication or
2665
- * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
2666
- *
2667
- */
2668
- const Download16svg = cdsAichatInternal.toString({
2669
- ..._16,
2670
- attrs: {
2671
- ..._16.attrs,
2672
- slot: 'icon',
2673
- },
2674
- });
2675
- // NOTE TABLE: Carbon currently has a constant web component prefix defined as "cds". If they expose a way to configure
2676
- // that prefix we could use it to avoid conflicts with other carbon imports. We could still have conflicts with other
2677
- // chats that have set the same prefix, but that would only be an issue if those chats were on different versions. And
2678
- // even then we could potentially use our version number in the prefix to avoid conflict with other chats on different
2679
- // versions.
2680
- /**
2681
- * Table view logic.
2682
- */
2683
- function tableTemplate(tableElement) {
2684
- const { tableTitle, tableDescription, headers, containerWidth, filterPlaceholderText, locale, _handleDownload: handleDownload, _rowsWithIDs: tableRowsWithIDs, _allowFiltering: allowTableFiltering, _handleFilterEvent: handleFilterEvent, } = tableElement;
2685
- function toolbarElement() {
2686
- return lit.html `<cds-table-toolbar slot="toolbar">
2687
- <cds-table-toolbar-content>
2688
- ${allowTableFiltering
2689
- ? lit.html `<cds-table-toolbar-search persistent placeholder=${filterPlaceholderText}></cds-table-toolbar-search>`
2690
- : ''}
2691
- <cds-button @click=${handleDownload}>${unsafeSvg_js.unsafeSVG(Download16svg)}</cds-button>
2692
- </cds-table-toolbar-content>
2693
- </cds-table-toolbar>`;
2694
- }
2695
- function headersElement() {
2696
- return lit.html `<cds-table-head>
2697
- <cds-table-header-row>
2698
- ${headers.map(header => lit.html `<cds-table-header-cell>${header}</cds-table-header-cell>`)}
2699
- </cds-table-header-row>
2700
- </cds-table-head>`;
2701
- }
2702
- function rowsElement() {
2703
- return lit.html `<cds-table-body>
2704
- ${repeat_js.repeat(tableRowsWithIDs, row => row.id, row =>
2705
- // TODO TABLE: The Carbon table is suppose to support mixing expandable and non-expandable rows by using the
2706
- // "expandable" prop on a row that should expand (as described towards the bottom of this section
2707
- // https://web-components.carbondesignsystem.com/?path=/docs/components-datatable-basic--overview#expansion).
2708
- // However, that functionality is currently broken. When this issue
2709
- // (https://github.com/carbon-design-system/carbon/issues/17612) is resolved, then we can implement dynamic
2710
- // expansion.
2711
- lit.html `<cds-table-row id=${row.id}
2712
- >${row.cells.map(cell => lit.html `<cds-table-cell>${cell}</cds-table-cell>`)}</cds-table-row
2713
- >`)}
2714
- </cds-table-body>`;
2715
- }
2716
- // TODO TABLE: Do not enable expansion for now since we can't mix expandable and non-expandable rows (and support for
2717
- // styling of user defined sections is not ready at this time). When we do decide to support expansion we will need to
2718
- // render something like <MessageTypeComponent /> within the React container, pass it down to the TableElement
2719
- // component, render the contents in a React portal, and have the root of the portal fill the slot of the appropriate
2720
- // expandable section.
2721
- // TODO TABLE: There is a bug with size="sm" and is-sortable that prevents the header row from being the same size as
2722
- // the rest of the rows https://github.com/carbon-design-system/carbon/issues/17680. For now keep size="md" until that
2723
- // bug is fixed.
2724
- // Enable sorting if filtering is enabled.
2725
- return lit.html `<cds-table
2726
- style="--cds-chat-table-width:${containerWidth}px"
2727
- size="md"
2728
- locale=${locale}
2729
- .isSortable=${allowTableFiltering}
2730
- @cds-table-filtered=${handleFilterEvent}
2731
- >
2732
- ${tableTitle && lit.html `<cds-table-header-title slot="title">${tableTitle}</cds-table-header-title>`}
2733
- ${tableDescription &&
2734
- lit.html `<cds-table-header-description slot="description">${tableDescription}</cds-table-header-description>`}
2735
- ${toolbarElement()} ${headersElement()} ${rowsElement()}
2736
- </cds-table>`;
2737
- }
2738
-
2739
- /**
2740
- *
2741
- * IBM Confidential
2742
- *
2743
- * (C) Copyright IBM Corp. 2024
2744
- *
2745
- * The source code for this program is not published or otherwise
2746
- * divested of its trade secrets, irrespective of what has been
2747
- * deposited with the U. S. Copyright Office
2748
- *
2749
- * US Government Users Restricted Rights - Use, duplication or
2750
- * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
2751
- *
2752
- */
2753
- /**
2754
- * Table pagination view logic.
2755
- */
2756
- function tablePaginationTemplate(tableElement) {
2757
- const { _currentPageSize: currentPageSize, _currentPageNumber: currentPageNumber, _filterVisibleRowIDs: filterVisibleRowIDs, rows, previousPageText, nextPageText, itemsPerPageText, getPaginationSupplementalText, getPaginationStatusText, _handlePageChangeEvent: handlePageChangeEvent, _handlePageSizeChangeEvent: handlePageSizeChangeEvent, } = tableElement;
2758
- const totalVisibleRows = filterVisibleRowIDs.size;
2759
- const totalRows = rows.length;
2760
- // Page sizes will only be included if the page size is less than the total number of rows.
2761
- const supportedPageSizes = POSSIBLE_PAGE_SIZES.filter(pageSize => pageSize < totalRows);
2762
- // TODO TABLE: This component is quite wide. Because of the shadow dom we can't select it's contents to hide items
2763
- // with css, nor can we extend this class to manipulate it's styles because of Carbon's use of :host(cds-pagination)
2764
- // within their styles. There is however a smaller variation of this component
2765
- // (https://carbondesignsystem.com/components/pagination/usage/#responsive-behavior) but it's only used at a specific
2766
- // breakpoint, when the viewport is narrow (i.e. a mobile device). A Carbon enhancement request has been made to
2767
- // expose a prop that can be used to enable this smaller variation
2768
- // (https://github.com/carbon-design-system/carbon/issues/17564). When that enhancement is done, and we can
2769
- // dynamically enable a narrow form factor of this pagination component, then we could use the same css trick we used
2770
- // for the header to make the pagination component sticky (if the carbon component doesn't already do it for us).
2771
- return lit.html `<cds-pagination
2772
- page-size=${currentPageSize}
2773
- page=${currentPageNumber}
2774
- total-items=${totalVisibleRows}
2775
- totalPages=${Math.ceil(totalVisibleRows / currentPageSize)}
2776
- backward-text=${previousPageText}
2777
- forward-text=${nextPageText}
2778
- items-per-page-text=${itemsPerPageText}
2779
- .formatSupplementalText=${getPaginationSupplementalText}
2780
- .formatStatusWithDeterminateTotal=${getPaginationStatusText}
2781
- @cds-pagination-changed-current=${handlePageChangeEvent}
2782
- @cds-page-sizes-select-changed=${handlePageSizeChangeEvent}
2783
- >
2784
- ${supportedPageSizes.map(pageSize => lit.html `<cds-select-item value="${pageSize}">${pageSize}</cds-select-item>`)}
2785
- <cds-select-item value="${totalRows}">${totalRows}</cds-select-item>
2786
- </cds-pagination>`;
2787
- }
2788
-
2789
- /**
2790
- *
2791
- * IBM Confidential
2792
- *
2793
- * (C) Copyright IBM Corp. 2024
2794
- *
2795
- * The source code for this program is not published or otherwise
2796
- * divested of its trade secrets, irrespective of what has been
2797
- * deposited with the U. S. Copyright Office
2798
- *
2799
- * US Government Users Restricted Rights - Use, duplication or
2800
- * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
2801
- *
2802
- */
2803
- /**
2804
- * Table skeleton view logic.
2805
- */
2806
- function tableSkeletonTemplate() {
2807
- // Can add header names to the skeleton if we want to
2808
- // https://web-components.carbondesignsystem.com/?path=/docs/components-datatable-skeleton--overview#custom-headers.
2809
- return lit.html `<cds-table-skeleton row-count="3" column-count="2"> </cds-table-skeleton>`;
2810
- }
2811
-
2812
- /**
2813
- *
2814
- * IBM Confidential
2815
- *
2816
- * (C) Copyright IBM Corp. 2024
2817
- *
2818
- * The source code for this program is not published or otherwise
2819
- * divested of its trade secrets, irrespective of what has been
2820
- * deposited with the U. S. Copyright Office
2821
- *
2822
- * US Government Users Restricted Rights - Use, duplication or
2823
- * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
2824
- *
2825
- */
2826
- const DEFAULT_TABLE_PAGE_SIZE = 5;
2827
- const DEFAULT_TABLE_PAGE_SIZE_TALL_CHAT = 10;
2828
- // The supported possible page sizes are 5, 10, 15, 20, 50, and all rows.
2829
- const POSSIBLE_PAGE_SIZES = [DEFAULT_TABLE_PAGE_SIZE, DEFAULT_TABLE_PAGE_SIZE_TALL_CHAT, 15, 20, 50];
2830
- const TALL_CHAT_HEIGHT = 850;
2831
- // We will have to give this component a unique ID on the name when we register it to avoid conflicts in a world where
2832
- // multiple versions of the web chat can be on the same page.
2833
- const TABLE_COMPONENT_TAG_NAME = 'cds-aichat-table';
2834
- /**
2835
- * Class functionality for the Table custom element.
2836
- */
2837
- let TableElement = class TableElement extends lit.LitElement {
2838
- constructor() {
2839
- super(...arguments);
2840
- /**
2841
- * If the table is valid or not.
2842
- */
2843
- this._isValid = true;
2844
- /**
2845
- * The current page of the table we're on.
2846
- */
2847
- this._currentPageNumber = 1;
2848
- /**
2849
- * Whether or not the number of rows per page was changed with the pagination component. If the user used the
2850
- * pagination controls to show all rows, the pagination component would normally hide itself because the number of is
2851
- * no longer greater than the page size. However the pagination component needs to persist in this case, since the
2852
- * user may want to change the page size again. This is used to keep track of whether the pagination controls were
2853
- * used to change page size, and if they have, it forces pagination component to persist.
2854
- */
2855
- this._rowsPerPageChanged = false;
2856
- /**
2857
- * All of the rows for the table with IDs.
2858
- */
2859
- this._rowsWithIDs = [];
2860
- }
2861
- static { this.styles = lit.css `
2862
- ${lit.unsafeCSS(styles)}
2863
- `; }
2864
- /**
2865
- * Depending on the properties that changed validate the table or change the number of rows displayed in the table.
2866
- * There is also a [firstUpdated](https://lit.dev/docs/components/lifecycle/#firstupdated) function from lit that only
2867
- * fires after the components DOM has been updated the first time. That could potentially be used in these scenarios /
2868
- * similar scenarios as it seems similar to the old componentDidMount. For now use this broader function to make sure
2869
- * we see the prop updates we're expecting.
2870
- */
2871
- updated(changedProperties) {
2872
- // If the headers or rows has recently updated and both are defined than we should validate the table
2873
- // data. This will likely only happen on the web components first render cycle when the props go from undefined to
2874
- // defined.
2875
- if ((changedProperties.has('headers') || changedProperties.has('rows')) &&
2876
- this.headers !== undefined &&
2877
- this.rows !== undefined) {
2878
- this._calcIsTableValid();
2879
- }
2880
- // If the value of tableRows updated then initialize the internal rows arrays.
2881
- if (changedProperties.has('rows') && this.rows !== undefined) {
2882
- this._initializeRowsArrays();
2883
- }
2884
- // If the page size is not currently defined, and the chatHeight has been set, then this is the first render and we
2885
- // need to choose the starting page size based off the chatHeight.
2886
- if (this._currentPageSize === undefined &&
2887
- changedProperties.has('chatHeight') &&
2888
- this.chatHeight !== changedProperties.get('chatHeight')) {
2889
- this._initializePageSize();
2890
- }
2891
- }
2892
- /**
2893
- * Check if the table content is valid. A table is valid if the number of cells in each row is the same as the number
2894
- * of cells in the header.
2895
- */
2896
- _calcIsTableValid() {
2897
- const columnCount = this.headers.length;
2898
- // If one of the rows has a different number of cells than the number of columns in the header then set our internal
2899
- // valid state to false.
2900
- this._isValid = !this.rows.some(row => row.cells.length !== columnCount);
2901
- // In the future, once we have an inlineError web component to use, we can render that when our table is not valid
2902
- // (as well as throwing the below error). Until then our React container is rendering the error component and
2903
- // throwing the error.
2904
- // throw new Error(
2905
- // `${WA_CONSOLE_PREFIX} Number of cells in the table header does not match the number of cells in one or more of the table rows. In order to render a table there needs to be the same number of columns in the table header and all of the table rows.`,
2906
- // );
2907
- }
2908
- /**
2909
- * Create a new array of rows that includes ids for each row. Also build an array of those same ids representing the
2910
- * rows that have not been filtered out.
2911
- */
2912
- _initializeRowsArrays() {
2913
- // Reset both arrays.
2914
- this._rowsWithIDs = [];
2915
- this._filterVisibleRowIDs = new Set();
2916
- this.rows.forEach((row, index) => {
2917
- const id = index.toString();
2918
- this._rowsWithIDs.push({ ...row, id });
2919
- this._filterVisibleRowIDs.add(id);
2920
- });
2921
- }
2922
- /**
2923
- * If the chat container is over a certain height then show more rows per page.
2924
- */
2925
- _initializePageSize() {
2926
- // If the chat container is above a certain height then show more rows per page.
2927
- if (this.chatHeight > TALL_CHAT_HEIGHT) {
2928
- this._currentPageSize = DEFAULT_TABLE_PAGE_SIZE_TALL_CHAT;
2929
- }
2930
- else {
2931
- this._currentPageSize = DEFAULT_TABLE_PAGE_SIZE;
2932
- }
2933
- // If there are more rows than the page size then enable filtering.
2934
- this._allowFiltering = this.rows.length > this._currentPageSize;
2935
- // Update the visible rows in case the page size has changed or this is the first time this web component has
2936
- // rendered.
2937
- this._updateVisibleRows();
2938
- }
2939
- /**
2940
- * When the page change event is fired by the pagination component, change which rows are visible. For some reason
2941
- * only this event is firing twice. However the page size and number is the same both times so the functionality of
2942
- * the pagination component works as expected. Ignore this double firing for now since it appears to be a bug on
2943
- * Carbon's end that will likely be fixed in a future release.
2944
- */
2945
- _handlePageChangeEvent(event) {
2946
- this._updateVisibleRows(event.detail?.page, event.detail?.pageSize);
2947
- event.stopPropagation();
2948
- }
2949
- /**
2950
- * When the number of rows per page is changed, update the current page size and change which rows are visible.
2951
- */
2952
- _handlePageSizeChangeEvent(event) {
2953
- this._rowsPerPageChanged = true;
2954
- this._currentPageSize = event.detail?.pageSize;
2955
- this._updateVisibleRows();
2956
- event.stopPropagation();
2957
- }
2958
- /**
2959
- * When the filter event is fired, record which rows have not been filtered out, and update which rows are visible.
2960
- * This event is fired when the columns are sorted using the header cells AND when the table is filtered using the
2961
- * search bar.
2962
- */
2963
- _handleFilterEvent(event) {
2964
- // Record the new set of unfiltered row ids.
2965
- this._filterVisibleRowIDs = new Set(event?.detail?.unfilteredRows.map(row => row.id));
2966
- // Go back to the first page.
2967
- this._currentPageNumber = 1;
2968
- // Update which rows are visible.
2969
- this._updateVisibleRows();
2970
- event.stopPropagation();
2971
- }
2972
- /**
2973
- * Given the current page number, page size, and array of rows that have not been filtered out, determine which rows
2974
- * to show and hide using css.
2975
- */
2976
- _updateVisibleRows(page = this._currentPageNumber, pageSize = this._currentPageSize) {
2977
- // Set the current page number and only show the rows for that page.
2978
- this._currentPageNumber = page;
2979
- // Grab all the rows that have been rendered. It's necessary to grab them from the page because the cds-table puts
2980
- // the rows in a specific order when sorting and we want to preserve that order.
2981
- const rows = Array.from(this.renderRoot.querySelectorAll('cds-table-row'));
2982
- // This is similar to the carbon example here https://stackblitz.com/edit/github-kbd9xw-s3y3s6?file=index.html. I
2983
- // originally tried creating and passing an array of the specific rows the template should render for the current
2984
- // page. Unfortunately doing that doesn't work with the combination of the is-sortable prop for the table and
2985
- // page-size prop for pagination. What would happen is old rows would persist if you were on the last page and there
2986
- // weren't enough rows to fill the page (even though the old rows weren't included in the new rows provided to the
2987
- // template). Using Carbon's example of hiding the rows with styling works so I'm extending that concept here even
2988
- // though, ideally, render controls the view and reacts to the state that would be determined here.
2989
- // Hide all the rows to start.
2990
- rows.forEach(row => row.setAttribute('style', 'display: none'));
2991
- // Now filter the rows down to what is visible according to the filter.
2992
- const filterVisibleRows = rows.filter(row => this._filterVisibleRowIDs.has(row.id));
2993
- // Now show all the rows that are within the current page.
2994
- const pageStart = (page - 1) * pageSize;
2995
- const pageEnd = page * pageSize - 1;
2996
- for (let index = pageStart; index <= pageEnd; index++) {
2997
- // If there is a row at that index then show it. If there aren't enough rows to fill the page then there won't be
2998
- // a row at that index.
2999
- filterVisibleRows[index]?.removeAttribute('style');
3000
- }
3001
- }
3002
- /**
3003
- * Carbon's data table component by default only downloads rows that have been selected, and only downloads json. We
3004
- * don't want to implement selection at this time and we want our download to be csv so we need to implement own
3005
- * download function.
3006
- */
3007
- _handleDownload() {
3008
- // Don't save content from the expandable rows at this time. This could be added in the future but it's unclear how
3009
- // this would look in the download.
3010
- const tableArray = [this.headers, ...this.rows.map(row => row.cells)];
3011
- // stringify docs here: https://csv.js.org/stringify/api/sync/
3012
- const stringifiedTable = stringify(tableArray);
3013
- const blob = new Blob([stringifiedTable], { type: 'text/csv;charset=utf-8;' });
3014
- // It appears the only way to control the file name of a downloaded file is through an anchor element with a
3015
- // download attribute. So create such an element and add our data to be downloaded.
3016
- const link = document.createElement('a');
3017
- const url = URL.createObjectURL(blob);
3018
- link.setAttribute('href', url);
3019
- link.setAttribute('download', 'table-data.csv');
3020
- link.style.visibility = 'hidden';
3021
- document.body.appendChild(link);
3022
- // Click on the link we've created to download the blob with our stringified table data.
3023
- link.click();
3024
- document.body.removeChild(link);
3025
- }
3026
- /**
3027
- * Renders either the table skeleton or the table. If the table is larger than the page size then also render the
3028
- * pagination component to change pages.
3029
- */
3030
- render() {
3031
- // TODO TABLE: Once we have a web component version of the inline error state we could render that here if
3032
- // !this._isValid.
3033
- // This could be used while we wait for a md stream containing a table to complete.
3034
- if (this.loading) {
3035
- return tableSkeletonTemplate();
3036
- }
3037
- // If there are more rows than the page size then we need to add the pagination component. If the rows per page has
3038
- // been changed by the pagination component then we need to keep the pagination component around so the user can
3039
- // change the page size again, even if the current page size is the same as the number of table rows.
3040
- if (this.rows.length > this._currentPageSize || this._rowsPerPageChanged) {
3041
- return lit.html `${tableTemplate(this)} ${tablePaginationTemplate(this)}`;
3042
- }
3043
- // Otherwise, just render the table.
3044
- return lit.html `${tableTemplate(this)}`;
3045
- }
3046
- };
3047
- cdsAichatInternal.__decorate([
3048
- decorators_js.property({ type: String, attribute: 'table-title' })
3049
- ], TableElement.prototype, "tableTitle", void 0);
3050
- cdsAichatInternal.__decorate([
3051
- decorators_js.property({ type: String, attribute: 'table-description' })
3052
- ], TableElement.prototype, "tableDescription", void 0);
3053
- cdsAichatInternal.__decorate([
3054
- decorators_js.property({ type: Array })
3055
- ], TableElement.prototype, "headers", void 0);
3056
- cdsAichatInternal.__decorate([
3057
- decorators_js.property({ type: Array })
3058
- ], TableElement.prototype, "rows", void 0);
3059
- cdsAichatInternal.__decorate([
3060
- decorators_js.property({ type: Number, attribute: 'container-width' })
3061
- ], TableElement.prototype, "containerWidth", void 0);
3062
- cdsAichatInternal.__decorate([
3063
- decorators_js.property({ type: Number, attribute: 'chat-height' })
3064
- ], TableElement.prototype, "chatHeight", void 0);
3065
- cdsAichatInternal.__decorate([
3066
- decorators_js.property({ type: Boolean, attribute: 'loading' })
3067
- ], TableElement.prototype, "loading", void 0);
3068
- cdsAichatInternal.__decorate([
3069
- decorators_js.property({ type: String, attribute: 'filter-placeholder-text' })
3070
- ], TableElement.prototype, "filterPlaceholderText", void 0);
3071
- cdsAichatInternal.__decorate([
3072
- decorators_js.property({ type: String, attribute: 'previous-page-text' })
3073
- ], TableElement.prototype, "previousPageText", void 0);
3074
- cdsAichatInternal.__decorate([
3075
- decorators_js.property({ type: String, attribute: 'next-page-text' })
3076
- ], TableElement.prototype, "nextPageText", void 0);
3077
- cdsAichatInternal.__decorate([
3078
- decorators_js.property({ type: String, attribute: 'items-per-page-text' })
3079
- ], TableElement.prototype, "itemsPerPageText", void 0);
3080
- cdsAichatInternal.__decorate([
3081
- decorators_js.property({ type: String, attribute: 'locale' })
3082
- ], TableElement.prototype, "locale", void 0);
3083
- cdsAichatInternal.__decorate([
3084
- decorators_js.property({ type: Function })
3085
- ], TableElement.prototype, "getPaginationSupplementalText", void 0);
3086
- cdsAichatInternal.__decorate([
3087
- decorators_js.property({ type: Function })
3088
- ], TableElement.prototype, "getPaginationStatusText", void 0);
3089
- cdsAichatInternal.__decorate([
3090
- decorators_js.state()
3091
- ], TableElement.prototype, "_isValid", void 0);
3092
- cdsAichatInternal.__decorate([
3093
- decorators_js.state()
3094
- ], TableElement.prototype, "_currentPageNumber", void 0);
3095
- cdsAichatInternal.__decorate([
3096
- decorators_js.state()
3097
- ], TableElement.prototype, "_currentPageSize", void 0);
3098
- cdsAichatInternal.__decorate([
3099
- decorators_js.state()
3100
- ], TableElement.prototype, "_rowsPerPageChanged", void 0);
3101
- cdsAichatInternal.__decorate([
3102
- decorators_js.state()
3103
- ], TableElement.prototype, "_filterVisibleRowIDs", void 0);
3104
- cdsAichatInternal.__decorate([
3105
- decorators_js.state()
3106
- ], TableElement.prototype, "_rowsWithIDs", void 0);
3107
- cdsAichatInternal.__decorate([
3108
- decorators_js.state()
3109
- ], TableElement.prototype, "_allowFiltering", void 0);
3110
- cdsAichatInternal.__decorate([
3111
- cdsAichatInternal._default
3112
- ], TableElement.prototype, "_handlePageChangeEvent", null);
3113
- cdsAichatInternal.__decorate([
3114
- cdsAichatInternal._default
3115
- ], TableElement.prototype, "_handlePageSizeChangeEvent", null);
3116
- cdsAichatInternal.__decorate([
3117
- cdsAichatInternal._default
3118
- ], TableElement.prototype, "_handleFilterEvent", null);
3119
- TableElement = cdsAichatInternal.__decorate([
3120
- cdsAichatInternal.carbonElement(TABLE_COMPONENT_TAG_NAME)
3121
- ], TableElement);
3122
-
3123
- /**
3124
- *
3125
- * IBM Confidential
3126
- *
3127
- * (C) Copyright IBM Corp. 2024
3128
- *
3129
- * The source code for this program is not published or otherwise
3130
- * divested of its trade secrets, irrespective of what has been
3131
- * deposited with the U. S. Copyright Office
3132
- *
3133
- * US Government Users Restricted Rights - Use, duplication or
3134
- * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
3135
- *
3136
- */
3137
- /**
3138
- * This file creates React bindings for the Table web component and registers the web component in the DOM.
3139
- */
3140
- const Table = cdsAichatInternal.o({
3141
- tagName: TABLE_COMPONENT_TAG_NAME,
3142
- elementClass: TableElement,
3143
- react: React,
3144
- });
3145
-
3146
- exports.default = Table;