plist 2.0.0 → 3.0.1

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.
@@ -1,11 +1,9 @@
1
- (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.plist = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
1
+ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.plist = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
2
2
  (function (Buffer){
3
-
4
3
  /**
5
4
  * Module dependencies.
6
5
  */
7
6
 
8
- var deprecate = require('util-deprecate');
9
7
  var DOMParser = require('xmldom').DOMParser;
10
8
 
11
9
  /**
@@ -13,10 +11,11 @@ var DOMParser = require('xmldom').DOMParser;
13
11
  */
14
12
 
15
13
  exports.parse = parse;
16
- exports.parseString = deprecate(parseString, '`parseString()` is deprecated. ' +
17
- 'It\'s not actually async. Use `parse()` instead.');
18
- exports.parseStringSync = deprecate(parseStringSync, '`parseStringSync()` is ' +
19
- 'deprecated. Use `parse()` instead.');
14
+
15
+ var TEXT_NODE = 3;
16
+ var CDATA_NODE = 4;
17
+ var COMMENT_NODE = 8;
18
+
20
19
 
21
20
  /**
22
21
  * We ignore raw text (usually whitespace), <!-- xml comments -->,
@@ -28,77 +27,55 @@ exports.parseStringSync = deprecate(parseStringSync, '`parseStringSync()` is ' +
28
27
  */
29
28
 
30
29
  function shouldIgnoreNode (node) {
31
- return node.nodeType === 3 // text
32
- || node.nodeType === 8 // comment
33
- || node.nodeType === 4; // cdata
30
+ return node.nodeType === TEXT_NODE
31
+ || node.nodeType === COMMENT_NODE
32
+ || node.nodeType === CDATA_NODE;
34
33
  }
35
34
 
36
-
37
35
  /**
38
- * Parses a Plist XML string. Returns an Object.
36
+ * Check if the node is empty. Some plist file has such node:
37
+ * <key />
38
+ * this node shoud be ignored.
39
39
  *
40
- * @param {String} xml - the XML String to decode
41
- * @returns {Mixed} the decoded value from the Plist XML
42
- * @api public
40
+ * @see https://github.com/TooTallNate/plist.js/issues/66
41
+ * @param {Element} node
42
+ * @returns {Boolean}
43
+ * @api private
43
44
  */
44
-
45
- function parse (xml) {
46
- var doc = new DOMParser().parseFromString(xml);
47
- if (doc.documentElement.nodeName !== 'plist') {
48
- throw new Error('malformed document. First element should be <plist>');
45
+ function isEmptyNode(node){
46
+ if(!node.childNodes || node.childNodes.length === 0) {
47
+ return true;
48
+ } else {
49
+ return false;
49
50
  }
50
- var plist = parsePlistXML(doc.documentElement);
51
-
52
- // the root <plist> node gets interpreted as an Array,
53
- // so pull out the inner data first
54
- if (plist.length == 1) plist = plist[0];
55
-
56
- return plist;
57
51
  }
58
52
 
59
- /**
60
- * Parses a Plist XML string. Returns an Object. Takes a `callback` function.
61
- *
62
- * @param {String} xml - the XML String to decode
63
- * @param {Function} callback - callback function
64
- * @returns {Mixed} the decoded value from the Plist XML
65
- * @api public
66
- * @deprecated not actually async. use parse() instead
67
- */
68
-
69
- function parseString (xml, callback) {
70
- var doc, error, plist;
71
- try {
72
- doc = new DOMParser().parseFromString(xml);
73
- plist = parsePlistXML(doc.documentElement);
74
- } catch(e) {
75
- error = e;
53
+ function invariant(test, message) {
54
+ if (!test) {
55
+ throw new Error(message);
76
56
  }
77
- callback(error, plist);
78
57
  }
79
58
 
80
59
  /**
81
60
  * Parses a Plist XML string. Returns an Object.
82
61
  *
83
62
  * @param {String} xml - the XML String to decode
84
- * @param {Function} callback - callback function
85
63
  * @returns {Mixed} the decoded value from the Plist XML
86
64
  * @api public
87
- * @deprecated use parse() instead
88
65
  */
89
66
 
90
- function parseStringSync (xml) {
67
+ function parse (xml) {
91
68
  var doc = new DOMParser().parseFromString(xml);
92
- var plist;
93
- if (doc.documentElement.nodeName !== 'plist') {
94
- throw new Error('malformed document. First element should be <plist>');
95
- }
96
- plist = parsePlistXML(doc.documentElement);
69
+ invariant(
70
+ doc.documentElement.nodeName === 'plist',
71
+ 'malformed document. First element should be <plist>'
72
+ );
73
+ var plist = parsePlistXML(doc.documentElement);
74
+
75
+ // the root <plist> node gets interpreted as an Array,
76
+ // so pull out the inner data first
77
+ if (plist.length == 1) plist = plist[0];
97
78
 
98
- // if the plist is an array with 1 element, pull it out of the array
99
- if (plist.length == 1) {
100
- plist = plist[0];
101
- }
102
79
  return plist;
103
80
  }
104
81
 
@@ -111,41 +88,59 @@ function parseStringSync (xml) {
111
88
  */
112
89
 
113
90
  function parsePlistXML (node) {
114
- var i, new_obj, key, val, new_arr, res, d;
91
+ var i, new_obj, key, val, new_arr, res, counter, type;
115
92
 
116
93
  if (!node)
117
94
  return null;
118
95
 
119
96
  if (node.nodeName === 'plist') {
120
97
  new_arr = [];
98
+ if (isEmptyNode(node)) {
99
+ return new_arr;
100
+ }
121
101
  for (i=0; i < node.childNodes.length; i++) {
122
- // ignore comment nodes (text)
123
102
  if (!shouldIgnoreNode(node.childNodes[i])) {
124
103
  new_arr.push( parsePlistXML(node.childNodes[i]));
125
104
  }
126
105
  }
127
106
  return new_arr;
128
-
129
107
  } else if (node.nodeName === 'dict') {
130
108
  new_obj = {};
131
109
  key = null;
110
+ counter = 0;
111
+ if (isEmptyNode(node)) {
112
+ return new_obj;
113
+ }
132
114
  for (i=0; i < node.childNodes.length; i++) {
133
- // ignore comment nodes (text)
134
- if (!shouldIgnoreNode(node.childNodes[i])) {
135
- if (key === null) {
136
- key = parsePlistXML(node.childNodes[i]);
137
- } else {
138
- new_obj[key] = parsePlistXML(node.childNodes[i]);
139
- key = null;
140
- }
115
+ if (shouldIgnoreNode(node.childNodes[i])) continue;
116
+ if (counter % 2 === 0) {
117
+ invariant(
118
+ node.childNodes[i].nodeName === 'key',
119
+ 'Missing key while parsing <dict/>.'
120
+ );
121
+ key = parsePlistXML(node.childNodes[i]);
122
+ } else {
123
+ invariant(
124
+ node.childNodes[i].nodeName !== 'key',
125
+ 'Unexpected key "'
126
+ + parsePlistXML(node.childNodes[i])
127
+ + '" while parsing <dict/>.'
128
+ );
129
+ new_obj[key] = parsePlistXML(node.childNodes[i]);
141
130
  }
131
+ counter += 1;
132
+ }
133
+ if (counter % 2 === 1) {
134
+ throw new Error('Missing value for "' + key + '" while parsing <dict/>');
142
135
  }
143
136
  return new_obj;
144
137
 
145
138
  } else if (node.nodeName === 'array') {
146
139
  new_arr = [];
140
+ if (isEmptyNode(node)) {
141
+ return new_arr;
142
+ }
147
143
  for (i=0; i < node.childNodes.length; i++) {
148
- // ignore comment nodes (text)
149
144
  if (!shouldIgnoreNode(node.childNodes[i])) {
150
145
  res = parsePlistXML(node.childNodes[i]);
151
146
  if (null != res) new_arr.push(res);
@@ -157,40 +152,60 @@ function parsePlistXML (node) {
157
152
  // TODO: what should we do with text types? (CDATA sections)
158
153
 
159
154
  } else if (node.nodeName === 'key') {
155
+ if (isEmptyNode(node)) {
156
+ return '';
157
+ }
160
158
  return node.childNodes[0].nodeValue;
161
-
162
159
  } else if (node.nodeName === 'string') {
163
160
  res = '';
164
- for (d=0; d < node.childNodes.length; d++) {
165
- res += node.childNodes[d].nodeValue;
161
+ if (isEmptyNode(node)) {
162
+ return res;
163
+ }
164
+ for (i=0; i < node.childNodes.length; i++) {
165
+ var type = node.childNodes[i].nodeType;
166
+ if (type === TEXT_NODE || type === CDATA_NODE) {
167
+ res += node.childNodes[i].nodeValue;
168
+ }
166
169
  }
167
170
  return res;
168
171
 
169
172
  } else if (node.nodeName === 'integer') {
170
- // parse as base 10 integer
173
+ invariant(
174
+ !isEmptyNode(node),
175
+ 'Cannot parse "" as integer.'
176
+ );
171
177
  return parseInt(node.childNodes[0].nodeValue, 10);
172
178
 
173
179
  } else if (node.nodeName === 'real') {
180
+ invariant(
181
+ !isEmptyNode(node),
182
+ 'Cannot parse "" as real.'
183
+ );
174
184
  res = '';
175
- for (d=0; d < node.childNodes.length; d++) {
176
- if (node.childNodes[d].nodeType === 3) {
177
- res += node.childNodes[d].nodeValue;
185
+ for (i=0; i < node.childNodes.length; i++) {
186
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
187
+ res += node.childNodes[i].nodeValue;
178
188
  }
179
189
  }
180
190
  return parseFloat(res);
181
191
 
182
192
  } else if (node.nodeName === 'data') {
183
193
  res = '';
184
- for (d=0; d < node.childNodes.length; d++) {
185
- if (node.childNodes[d].nodeType === 3) {
186
- res += node.childNodes[d].nodeValue.replace(/\s+/g, '');
194
+ if (isEmptyNode(node)) {
195
+ return Buffer.from(res, 'base64');
196
+ }
197
+ for (i=0; i < node.childNodes.length; i++) {
198
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
199
+ res += node.childNodes[i].nodeValue.replace(/\s+/g, '');
187
200
  }
188
201
  }
189
-
190
- // decode base64 data to a Buffer instance
191
- return new Buffer(res, 'base64');
202
+ return Buffer.from(res, 'base64');
192
203
 
193
204
  } else if (node.nodeName === 'date') {
205
+ invariant(
206
+ !isEmptyNode(node),
207
+ 'Cannot parse "" as Date.'
208
+ )
194
209
  return new Date(node.childNodes[0].nodeValue);
195
210
 
196
211
  } else if (node.nodeName === 'true') {
@@ -202,395 +217,431 @@ function parsePlistXML (node) {
202
217
  }
203
218
 
204
219
  }).call(this,require("buffer").Buffer)
205
- },{"buffer":3,"util-deprecate":6,"xmldom":7}],2:[function(require,module,exports){
206
- var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
207
-
208
- ;(function (exports) {
209
- 'use strict';
210
-
211
- var Arr = (typeof Uint8Array !== 'undefined')
212
- ? Uint8Array
213
- : Array
214
-
215
- var PLUS = '+'.charCodeAt(0)
216
- var SLASH = '/'.charCodeAt(0)
217
- var NUMBER = '0'.charCodeAt(0)
218
- var LOWER = 'a'.charCodeAt(0)
219
- var UPPER = 'A'.charCodeAt(0)
220
- var PLUS_URL_SAFE = '-'.charCodeAt(0)
221
- var SLASH_URL_SAFE = '_'.charCodeAt(0)
222
-
223
- function decode (elt) {
224
- var code = elt.charCodeAt(0)
225
- if (code === PLUS ||
226
- code === PLUS_URL_SAFE)
227
- return 62 // '+'
228
- if (code === SLASH ||
229
- code === SLASH_URL_SAFE)
230
- return 63 // '/'
231
- if (code < NUMBER)
232
- return -1 //no match
233
- if (code < NUMBER + 10)
234
- return code - NUMBER + 26 + 26
235
- if (code < UPPER + 26)
236
- return code - UPPER
237
- if (code < LOWER + 26)
238
- return code - LOWER + 26
239
- }
220
+ },{"buffer":3,"xmldom":5}],2:[function(require,module,exports){
221
+ 'use strict'
240
222
 
241
- function b64ToByteArray (b64) {
242
- var i, j, l, tmp, placeHolders, arr
223
+ exports.byteLength = byteLength
224
+ exports.toByteArray = toByteArray
225
+ exports.fromByteArray = fromByteArray
243
226
 
244
- if (b64.length % 4 > 0) {
245
- throw new Error('Invalid string. Length must be a multiple of 4')
246
- }
227
+ var lookup = []
228
+ var revLookup = []
229
+ var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
230
+
231
+ var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
232
+ for (var i = 0, len = code.length; i < len; ++i) {
233
+ lookup[i] = code[i]
234
+ revLookup[code.charCodeAt(i)] = i
235
+ }
236
+
237
+ // Support decoding URL-safe base64 strings, as Node.js does.
238
+ // See: https://en.wikipedia.org/wiki/Base64#URL_applications
239
+ revLookup['-'.charCodeAt(0)] = 62
240
+ revLookup['_'.charCodeAt(0)] = 63
247
241
 
248
- // the number of equal signs (place holders)
249
- // if there are two placeholders, than the two characters before it
250
- // represent one byte
251
- // if there is only one, then the three characters before it represent 2 bytes
252
- // this is just a cheap hack to not do indexOf twice
253
- var len = b64.length
254
- placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
242
+ function placeHoldersCount (b64) {
243
+ var len = b64.length
244
+ if (len % 4 > 0) {
245
+ throw new Error('Invalid string. Length must be a multiple of 4')
246
+ }
255
247
 
256
- // base64 is 4/3 + up to two characters of the original data
257
- arr = new Arr(b64.length * 3 / 4 - placeHolders)
248
+ // the number of equal signs (place holders)
249
+ // if there are two placeholders, than the two characters before it
250
+ // represent one byte
251
+ // if there is only one, then the three characters before it represent 2 bytes
252
+ // this is just a cheap hack to not do indexOf twice
253
+ return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
254
+ }
258
255
 
259
- // if there are placeholders, only get up to the last complete 4 chars
260
- l = placeHolders > 0 ? b64.length - 4 : b64.length
256
+ function byteLength (b64) {
257
+ // base64 is 4/3 + up to two characters of the original data
258
+ return (b64.length * 3 / 4) - placeHoldersCount(b64)
259
+ }
261
260
 
262
- var L = 0
261
+ function toByteArray (b64) {
262
+ var i, l, tmp, placeHolders, arr
263
+ var len = b64.length
264
+ placeHolders = placeHoldersCount(b64)
263
265
 
264
- function push (v) {
265
- arr[L++] = v
266
- }
266
+ arr = new Arr((len * 3 / 4) - placeHolders)
267
267
 
268
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
269
- tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
270
- push((tmp & 0xFF0000) >> 16)
271
- push((tmp & 0xFF00) >> 8)
272
- push(tmp & 0xFF)
273
- }
268
+ // if there are placeholders, only get up to the last complete 4 chars
269
+ l = placeHolders > 0 ? len - 4 : len
274
270
 
275
- if (placeHolders === 2) {
276
- tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
277
- push(tmp & 0xFF)
278
- } else if (placeHolders === 1) {
279
- tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
280
- push((tmp >> 8) & 0xFF)
281
- push(tmp & 0xFF)
282
- }
271
+ var L = 0
283
272
 
284
- return arr
285
- }
273
+ for (i = 0; i < l; i += 4) {
274
+ tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
275
+ arr[L++] = (tmp >> 16) & 0xFF
276
+ arr[L++] = (tmp >> 8) & 0xFF
277
+ arr[L++] = tmp & 0xFF
278
+ }
286
279
 
287
- function uint8ToBase64 (uint8) {
288
- var i,
289
- extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
290
- output = "",
291
- temp, length
280
+ if (placeHolders === 2) {
281
+ tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
282
+ arr[L++] = tmp & 0xFF
283
+ } else if (placeHolders === 1) {
284
+ tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
285
+ arr[L++] = (tmp >> 8) & 0xFF
286
+ arr[L++] = tmp & 0xFF
287
+ }
292
288
 
293
- function encode (num) {
294
- return lookup.charAt(num)
295
- }
289
+ return arr
290
+ }
296
291
 
297
- function tripletToBase64 (num) {
298
- return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
299
- }
292
+ function tripletToBase64 (num) {
293
+ return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
294
+ }
300
295
 
301
- // go through the array every three bytes, we'll deal with trailing stuff later
302
- for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
303
- temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
304
- output += tripletToBase64(temp)
305
- }
296
+ function encodeChunk (uint8, start, end) {
297
+ var tmp
298
+ var output = []
299
+ for (var i = start; i < end; i += 3) {
300
+ tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
301
+ output.push(tripletToBase64(tmp))
302
+ }
303
+ return output.join('')
304
+ }
306
305
 
307
- // pad the end with zeros, but make sure to not forget the extra bytes
308
- switch (extraBytes) {
309
- case 1:
310
- temp = uint8[uint8.length - 1]
311
- output += encode(temp >> 2)
312
- output += encode((temp << 4) & 0x3F)
313
- output += '=='
314
- break
315
- case 2:
316
- temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
317
- output += encode(temp >> 10)
318
- output += encode((temp >> 4) & 0x3F)
319
- output += encode((temp << 2) & 0x3F)
320
- output += '='
321
- break
322
- }
306
+ function fromByteArray (uint8) {
307
+ var tmp
308
+ var len = uint8.length
309
+ var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
310
+ var output = ''
311
+ var parts = []
312
+ var maxChunkLength = 16383 // must be multiple of 3
323
313
 
324
- return output
325
- }
314
+ // go through the array every three bytes, we'll deal with trailing stuff later
315
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
316
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
317
+ }
326
318
 
327
- exports.toByteArray = b64ToByteArray
328
- exports.fromByteArray = uint8ToBase64
329
- }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
319
+ // pad the end with zeros, but make sure to not forget the extra bytes
320
+ if (extraBytes === 1) {
321
+ tmp = uint8[len - 1]
322
+ output += lookup[tmp >> 2]
323
+ output += lookup[(tmp << 4) & 0x3F]
324
+ output += '=='
325
+ } else if (extraBytes === 2) {
326
+ tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
327
+ output += lookup[tmp >> 10]
328
+ output += lookup[(tmp >> 4) & 0x3F]
329
+ output += lookup[(tmp << 2) & 0x3F]
330
+ output += '='
331
+ }
332
+
333
+ parts.push(output)
334
+
335
+ return parts.join('')
336
+ }
330
337
 
331
338
  },{}],3:[function(require,module,exports){
332
- (function (global){
333
339
  /*!
334
340
  * The buffer module from node.js, for the browser.
335
341
  *
336
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
342
+ * @author Feross Aboukhadijeh <https://feross.org>
337
343
  * @license MIT
338
344
  */
339
345
  /* eslint-disable no-proto */
340
346
 
347
+ 'use strict'
348
+
341
349
  var base64 = require('base64-js')
342
350
  var ieee754 = require('ieee754')
343
- var isArray = require('is-array')
344
351
 
345
352
  exports.Buffer = Buffer
346
353
  exports.SlowBuffer = SlowBuffer
347
354
  exports.INSPECT_MAX_BYTES = 50
348
- Buffer.poolSize = 8192 // not used by this implementation
349
355
 
350
- var rootParent = {}
356
+ var K_MAX_LENGTH = 0x7fffffff
357
+ exports.kMaxLength = K_MAX_LENGTH
351
358
 
352
359
  /**
353
360
  * If `Buffer.TYPED_ARRAY_SUPPORT`:
354
361
  * === true Use Uint8Array implementation (fastest)
355
- * === false Use Object implementation (most compatible, even IE6)
362
+ * === false Print warning and recommend using `buffer` v4.x which has an Object
363
+ * implementation (most compatible, even IE6)
356
364
  *
357
365
  * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
358
366
  * Opera 11.6+, iOS 4.2+.
359
367
  *
360
- * Due to various browser bugs, sometimes the Object implementation will be used even
361
- * when the browser supports typed arrays.
362
- *
363
- * Note:
364
- *
365
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
366
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
367
- *
368
- * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
369
- * on objects.
370
- *
371
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
372
- *
373
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
374
- * incorrect length in some situations.
375
-
376
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
377
- * get the Object implementation, which is slower but behaves correctly.
368
+ * We report that the browser does not support typed arrays if the are not subclassable
369
+ * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
370
+ * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
371
+ * for __proto__ and has a buggy typed array implementation.
378
372
  */
379
- Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
380
- ? global.TYPED_ARRAY_SUPPORT
381
- : typedArraySupport()
373
+ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
374
+
375
+ if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
376
+ typeof console.error === 'function') {
377
+ console.error(
378
+ 'This browser lacks typed array (Uint8Array) support which is required by ' +
379
+ '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
380
+ )
381
+ }
382
382
 
383
383
  function typedArraySupport () {
384
- function Bar () {}
384
+ // Can typed array instances can be augmented?
385
385
  try {
386
386
  var arr = new Uint8Array(1)
387
- arr.foo = function () { return 42 }
388
- arr.constructor = Bar
389
- return arr.foo() === 42 && // typed array instances can be augmented
390
- arr.constructor === Bar && // constructor can be set
391
- typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
392
- arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
387
+ arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
388
+ return arr.foo() === 42
393
389
  } catch (e) {
394
390
  return false
395
391
  }
396
392
  }
397
393
 
398
- function kMaxLength () {
399
- return Buffer.TYPED_ARRAY_SUPPORT
400
- ? 0x7fffffff
401
- : 0x3fffffff
394
+ Object.defineProperty(Buffer.prototype, 'parent', {
395
+ get: function () {
396
+ if (!(this instanceof Buffer)) {
397
+ return undefined
398
+ }
399
+ return this.buffer
400
+ }
401
+ })
402
+
403
+ Object.defineProperty(Buffer.prototype, 'offset', {
404
+ get: function () {
405
+ if (!(this instanceof Buffer)) {
406
+ return undefined
407
+ }
408
+ return this.byteOffset
409
+ }
410
+ })
411
+
412
+ function createBuffer (length) {
413
+ if (length > K_MAX_LENGTH) {
414
+ throw new RangeError('Invalid typed array length')
415
+ }
416
+ // Return an augmented `Uint8Array` instance
417
+ var buf = new Uint8Array(length)
418
+ buf.__proto__ = Buffer.prototype
419
+ return buf
402
420
  }
403
421
 
404
422
  /**
405
- * Class: Buffer
406
- * =============
423
+ * The Buffer constructor returns instances of `Uint8Array` that have their
424
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
425
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
426
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
427
+ * returns a single octet.
407
428
  *
408
- * The Buffer constructor returns instances of `Uint8Array` that are augmented
409
- * with function properties for all the node `Buffer` API functions. We use
410
- * `Uint8Array` so that square bracket notation works as expected -- it returns
411
- * a single octet.
412
- *
413
- * By augmenting the instances, we can avoid modifying the `Uint8Array`
414
- * prototype.
429
+ * The `Uint8Array` prototype remains unmodified.
415
430
  */
416
- function Buffer (arg) {
417
- if (!(this instanceof Buffer)) {
418
- // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
419
- if (arguments.length > 1) return new Buffer(arg, arguments[1])
420
- return new Buffer(arg)
421
- }
422
-
423
- this.length = 0
424
- this.parent = undefined
425
431
 
432
+ function Buffer (arg, encodingOrOffset, length) {
426
433
  // Common case.
427
434
  if (typeof arg === 'number') {
428
- return fromNumber(this, arg)
429
- }
430
-
431
- // Slightly less common case.
432
- if (typeof arg === 'string') {
433
- return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
435
+ if (typeof encodingOrOffset === 'string') {
436
+ throw new Error(
437
+ 'If encoding is specified then the first argument must be a string'
438
+ )
439
+ }
440
+ return allocUnsafe(arg)
434
441
  }
435
-
436
- // Unusual.
437
- return fromObject(this, arg)
442
+ return from(arg, encodingOrOffset, length)
438
443
  }
439
444
 
440
- function fromNumber (that, length) {
441
- that = allocate(that, length < 0 ? 0 : checked(length) | 0)
442
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
443
- for (var i = 0; i < length; i++) {
444
- that[i] = 0
445
- }
446
- }
447
- return that
445
+ // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
446
+ if (typeof Symbol !== 'undefined' && Symbol.species &&
447
+ Buffer[Symbol.species] === Buffer) {
448
+ Object.defineProperty(Buffer, Symbol.species, {
449
+ value: null,
450
+ configurable: true,
451
+ enumerable: false,
452
+ writable: false
453
+ })
448
454
  }
449
455
 
450
- function fromString (that, string, encoding) {
451
- if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
456
+ Buffer.poolSize = 8192 // not used by this implementation
452
457
 
453
- // Assumption: byteLength() return value is always < kMaxLength.
454
- var length = byteLength(string, encoding) | 0
455
- that = allocate(that, length)
458
+ function from (value, encodingOrOffset, length) {
459
+ if (typeof value === 'number') {
460
+ throw new TypeError('"value" argument must not be a number')
461
+ }
456
462
 
457
- that.write(string, encoding)
458
- return that
459
- }
463
+ if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) {
464
+ return fromArrayBuffer(value, encodingOrOffset, length)
465
+ }
460
466
 
461
- function fromObject (that, object) {
462
- if (Buffer.isBuffer(object)) return fromBuffer(that, object)
467
+ if (typeof value === 'string') {
468
+ return fromString(value, encodingOrOffset)
469
+ }
463
470
 
464
- if (isArray(object)) return fromArray(that, object)
471
+ return fromObject(value)
472
+ }
465
473
 
466
- if (object == null) {
467
- throw new TypeError('must start with number, buffer, array or string')
474
+ /**
475
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
476
+ * if value is a number.
477
+ * Buffer.from(str[, encoding])
478
+ * Buffer.from(array)
479
+ * Buffer.from(buffer)
480
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
481
+ **/
482
+ Buffer.from = function (value, encodingOrOffset, length) {
483
+ return from(value, encodingOrOffset, length)
484
+ }
485
+
486
+ // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
487
+ // https://github.com/feross/buffer/pull/148
488
+ Buffer.prototype.__proto__ = Uint8Array.prototype
489
+ Buffer.__proto__ = Uint8Array
490
+
491
+ function assertSize (size) {
492
+ if (typeof size !== 'number') {
493
+ throw new TypeError('"size" argument must be of type number')
494
+ } else if (size < 0) {
495
+ throw new RangeError('"size" argument must not be negative')
468
496
  }
497
+ }
469
498
 
470
- if (typeof ArrayBuffer !== 'undefined') {
471
- if (object.buffer instanceof ArrayBuffer) {
472
- return fromTypedArray(that, object)
473
- }
474
- if (object instanceof ArrayBuffer) {
475
- return fromArrayBuffer(that, object)
476
- }
499
+ function alloc (size, fill, encoding) {
500
+ assertSize(size)
501
+ if (size <= 0) {
502
+ return createBuffer(size)
503
+ }
504
+ if (fill !== undefined) {
505
+ // Only pay attention to encoding if it's a string. This
506
+ // prevents accidentally sending in a number that would
507
+ // be interpretted as a start offset.
508
+ return typeof encoding === 'string'
509
+ ? createBuffer(size).fill(fill, encoding)
510
+ : createBuffer(size).fill(fill)
477
511
  }
512
+ return createBuffer(size)
513
+ }
478
514
 
479
- if (object.length) return fromArrayLike(that, object)
515
+ /**
516
+ * Creates a new filled Buffer instance.
517
+ * alloc(size[, fill[, encoding]])
518
+ **/
519
+ Buffer.alloc = function (size, fill, encoding) {
520
+ return alloc(size, fill, encoding)
521
+ }
480
522
 
481
- return fromJsonObject(that, object)
523
+ function allocUnsafe (size) {
524
+ assertSize(size)
525
+ return createBuffer(size < 0 ? 0 : checked(size) | 0)
482
526
  }
483
527
 
484
- function fromBuffer (that, buffer) {
485
- var length = checked(buffer.length) | 0
486
- that = allocate(that, length)
487
- buffer.copy(that, 0, 0, length)
488
- return that
528
+ /**
529
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
530
+ * */
531
+ Buffer.allocUnsafe = function (size) {
532
+ return allocUnsafe(size)
533
+ }
534
+ /**
535
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
536
+ */
537
+ Buffer.allocUnsafeSlow = function (size) {
538
+ return allocUnsafe(size)
489
539
  }
490
540
 
491
- function fromArray (that, array) {
492
- var length = checked(array.length) | 0
493
- that = allocate(that, length)
494
- for (var i = 0; i < length; i += 1) {
495
- that[i] = array[i] & 255
541
+ function fromString (string, encoding) {
542
+ if (typeof encoding !== 'string' || encoding === '') {
543
+ encoding = 'utf8'
496
544
  }
497
- return that
498
- }
499
545
 
500
- // Duplicate of fromArray() to keep fromArray() monomorphic.
501
- function fromTypedArray (that, array) {
502
- var length = checked(array.length) | 0
503
- that = allocate(that, length)
504
- // Truncating the elements is probably not what people expect from typed
505
- // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
506
- // of the old Buffer constructor.
507
- for (var i = 0; i < length; i += 1) {
508
- that[i] = array[i] & 255
546
+ if (!Buffer.isEncoding(encoding)) {
547
+ throw new TypeError('Unknown encoding: ' + encoding)
509
548
  }
510
- return that
511
- }
512
549
 
513
- function fromArrayBuffer (that, array) {
514
- if (Buffer.TYPED_ARRAY_SUPPORT) {
515
- // Return an augmented `Uint8Array` instance, for best performance
516
- array.byteLength
517
- that = Buffer._augment(new Uint8Array(array))
518
- } else {
519
- // Fallback: Return an object instance of the Buffer class
520
- that = fromTypedArray(that, new Uint8Array(array))
550
+ var length = byteLength(string, encoding) | 0
551
+ var buf = createBuffer(length)
552
+
553
+ var actual = buf.write(string, encoding)
554
+
555
+ if (actual !== length) {
556
+ // Writing a hex string, for example, that contains invalid characters will
557
+ // cause everything after the first invalid character to be ignored. (e.g.
558
+ // 'abxxcd' will be treated as 'ab')
559
+ buf = buf.slice(0, actual)
521
560
  }
522
- return that
561
+
562
+ return buf
523
563
  }
524
564
 
525
- function fromArrayLike (that, array) {
526
- var length = checked(array.length) | 0
527
- that = allocate(that, length)
565
+ function fromArrayLike (array) {
566
+ var length = array.length < 0 ? 0 : checked(array.length) | 0
567
+ var buf = createBuffer(length)
528
568
  for (var i = 0; i < length; i += 1) {
529
- that[i] = array[i] & 255
569
+ buf[i] = array[i] & 255
530
570
  }
531
- return that
571
+ return buf
532
572
  }
533
573
 
534
- // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
535
- // Returns a zero-length buffer for inputs that don't conform to the spec.
536
- function fromJsonObject (that, object) {
537
- var array
538
- var length = 0
574
+ function fromArrayBuffer (array, byteOffset, length) {
575
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
576
+ throw new RangeError('"offset" is outside of buffer bounds')
577
+ }
539
578
 
540
- if (object.type === 'Buffer' && isArray(object.data)) {
541
- array = object.data
542
- length = checked(array.length) | 0
579
+ if (array.byteLength < byteOffset + (length || 0)) {
580
+ throw new RangeError('"length" is outside of buffer bounds')
543
581
  }
544
- that = allocate(that, length)
545
582
 
546
- for (var i = 0; i < length; i += 1) {
547
- that[i] = array[i] & 255
583
+ var buf
584
+ if (byteOffset === undefined && length === undefined) {
585
+ buf = new Uint8Array(array)
586
+ } else if (length === undefined) {
587
+ buf = new Uint8Array(array, byteOffset)
588
+ } else {
589
+ buf = new Uint8Array(array, byteOffset, length)
548
590
  }
549
- return that
550
- }
551
591
 
552
- if (Buffer.TYPED_ARRAY_SUPPORT) {
553
- Buffer.prototype.__proto__ = Uint8Array.prototype
554
- Buffer.__proto__ = Uint8Array
592
+ // Return an augmented `Uint8Array` instance
593
+ buf.__proto__ = Buffer.prototype
594
+ return buf
555
595
  }
556
596
 
557
- function allocate (that, length) {
558
- if (Buffer.TYPED_ARRAY_SUPPORT) {
559
- // Return an augmented `Uint8Array` instance, for best performance
560
- that = Buffer._augment(new Uint8Array(length))
561
- that.__proto__ = Buffer.prototype
562
- } else {
563
- // Fallback: Return an object instance of the Buffer class
564
- that.length = length
565
- that._isBuffer = true
597
+ function fromObject (obj) {
598
+ if (Buffer.isBuffer(obj)) {
599
+ var len = checked(obj.length) | 0
600
+ var buf = createBuffer(len)
601
+
602
+ if (buf.length === 0) {
603
+ return buf
604
+ }
605
+
606
+ obj.copy(buf, 0, 0, len)
607
+ return buf
566
608
  }
567
609
 
568
- var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
569
- if (fromPool) that.parent = rootParent
610
+ if (obj) {
611
+ if (ArrayBuffer.isView(obj) || 'length' in obj) {
612
+ if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
613
+ return createBuffer(0)
614
+ }
615
+ return fromArrayLike(obj)
616
+ }
570
617
 
571
- return that
618
+ if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
619
+ return fromArrayLike(obj.data)
620
+ }
621
+ }
622
+
623
+ throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.')
572
624
  }
573
625
 
574
626
  function checked (length) {
575
- // Note: cannot use `length < kMaxLength` here because that fails when
627
+ // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
576
628
  // length is NaN (which is otherwise coerced to zero.)
577
- if (length >= kMaxLength()) {
629
+ if (length >= K_MAX_LENGTH) {
578
630
  throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
579
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
631
+ 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
580
632
  }
581
633
  return length | 0
582
634
  }
583
635
 
584
- function SlowBuffer (subject, encoding) {
585
- if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
586
-
587
- var buf = new Buffer(subject, encoding)
588
- delete buf.parent
589
- return buf
636
+ function SlowBuffer (length) {
637
+ if (+length != length) { // eslint-disable-line eqeqeq
638
+ length = 0
639
+ }
640
+ return Buffer.alloc(+length)
590
641
  }
591
642
 
592
643
  Buffer.isBuffer = function isBuffer (b) {
593
- return !!(b != null && b._isBuffer)
644
+ return b != null && b._isBuffer === true
594
645
  }
595
646
 
596
647
  Buffer.compare = function compare (a, b) {
@@ -603,17 +654,12 @@ Buffer.compare = function compare (a, b) {
603
654
  var x = a.length
604
655
  var y = b.length
605
656
 
606
- var i = 0
607
- var len = Math.min(x, y)
608
- while (i < len) {
609
- if (a[i] !== b[i]) break
610
-
611
- ++i
612
- }
613
-
614
- if (i !== len) {
615
- x = a[i]
616
- y = b[i]
657
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
658
+ if (a[i] !== b[i]) {
659
+ x = a[i]
660
+ y = b[i]
661
+ break
662
+ }
617
663
  }
618
664
 
619
665
  if (x < y) return -1
@@ -627,9 +673,9 @@ Buffer.isEncoding = function isEncoding (encoding) {
627
673
  case 'utf8':
628
674
  case 'utf-8':
629
675
  case 'ascii':
676
+ case 'latin1':
630
677
  case 'binary':
631
678
  case 'base64':
632
- case 'raw':
633
679
  case 'ucs2':
634
680
  case 'ucs-2':
635
681
  case 'utf16le':
@@ -641,32 +687,48 @@ Buffer.isEncoding = function isEncoding (encoding) {
641
687
  }
642
688
 
643
689
  Buffer.concat = function concat (list, length) {
644
- if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
690
+ if (!Array.isArray(list)) {
691
+ throw new TypeError('"list" argument must be an Array of Buffers')
692
+ }
645
693
 
646
694
  if (list.length === 0) {
647
- return new Buffer(0)
695
+ return Buffer.alloc(0)
648
696
  }
649
697
 
650
698
  var i
651
699
  if (length === undefined) {
652
700
  length = 0
653
- for (i = 0; i < list.length; i++) {
701
+ for (i = 0; i < list.length; ++i) {
654
702
  length += list[i].length
655
703
  }
656
704
  }
657
705
 
658
- var buf = new Buffer(length)
706
+ var buffer = Buffer.allocUnsafe(length)
659
707
  var pos = 0
660
- for (i = 0; i < list.length; i++) {
661
- var item = list[i]
662
- item.copy(buf, pos)
663
- pos += item.length
708
+ for (i = 0; i < list.length; ++i) {
709
+ var buf = list[i]
710
+ if (ArrayBuffer.isView(buf)) {
711
+ buf = Buffer.from(buf)
712
+ }
713
+ if (!Buffer.isBuffer(buf)) {
714
+ throw new TypeError('"list" argument must be an Array of Buffers')
715
+ }
716
+ buf.copy(buffer, pos)
717
+ pos += buf.length
664
718
  }
665
- return buf
719
+ return buffer
666
720
  }
667
721
 
668
722
  function byteLength (string, encoding) {
669
- if (typeof string !== 'string') string = '' + string
723
+ if (Buffer.isBuffer(string)) {
724
+ return string.length
725
+ }
726
+ if (ArrayBuffer.isView(string) || isArrayBuffer(string)) {
727
+ return string.byteLength
728
+ }
729
+ if (typeof string !== 'string') {
730
+ string = '' + string
731
+ }
670
732
 
671
733
  var len = string.length
672
734
  if (len === 0) return 0
@@ -676,13 +738,12 @@ function byteLength (string, encoding) {
676
738
  for (;;) {
677
739
  switch (encoding) {
678
740
  case 'ascii':
741
+ case 'latin1':
679
742
  case 'binary':
680
- // Deprecated
681
- case 'raw':
682
- case 'raws':
683
743
  return len
684
744
  case 'utf8':
685
745
  case 'utf-8':
746
+ case undefined:
686
747
  return utf8ToBytes(string).length
687
748
  case 'ucs2':
688
749
  case 'ucs-2':
@@ -702,20 +763,42 @@ function byteLength (string, encoding) {
702
763
  }
703
764
  Buffer.byteLength = byteLength
704
765
 
705
- // pre-set for values that may exist in the future
706
- Buffer.prototype.length = undefined
707
- Buffer.prototype.parent = undefined
708
-
709
766
  function slowToString (encoding, start, end) {
710
767
  var loweredCase = false
711
768
 
712
- start = start | 0
713
- end = end === undefined || end === Infinity ? this.length : end | 0
769
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
770
+ // property of a typed array.
771
+
772
+ // This behaves neither like String nor Uint8Array in that we set start/end
773
+ // to their upper/lower bounds if the value passed is out of range.
774
+ // undefined is handled specially as per ECMA-262 6th Edition,
775
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
776
+ if (start === undefined || start < 0) {
777
+ start = 0
778
+ }
779
+ // Return early if start > this.length. Done here to prevent potential uint32
780
+ // coercion fail below.
781
+ if (start > this.length) {
782
+ return ''
783
+ }
784
+
785
+ if (end === undefined || end > this.length) {
786
+ end = this.length
787
+ }
788
+
789
+ if (end <= 0) {
790
+ return ''
791
+ }
792
+
793
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
794
+ end >>>= 0
795
+ start >>>= 0
796
+
797
+ if (end <= start) {
798
+ return ''
799
+ }
714
800
 
715
801
  if (!encoding) encoding = 'utf8'
716
- if (start < 0) start = 0
717
- if (end > this.length) end = this.length
718
- if (end <= start) return ''
719
802
 
720
803
  while (true) {
721
804
  switch (encoding) {
@@ -729,8 +812,9 @@ function slowToString (encoding, start, end) {
729
812
  case 'ascii':
730
813
  return asciiSlice(this, start, end)
731
814
 
815
+ case 'latin1':
732
816
  case 'binary':
733
- return binarySlice(this, start, end)
817
+ return latin1Slice(this, start, end)
734
818
 
735
819
  case 'base64':
736
820
  return base64Slice(this, start, end)
@@ -749,13 +833,66 @@ function slowToString (encoding, start, end) {
749
833
  }
750
834
  }
751
835
 
836
+ // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
837
+ // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
838
+ // reliably in a browserify context because there could be multiple different
839
+ // copies of the 'buffer' package in use. This method works even for Buffer
840
+ // instances that were created from another copy of the `buffer` package.
841
+ // See: https://github.com/feross/buffer/issues/154
842
+ Buffer.prototype._isBuffer = true
843
+
844
+ function swap (b, n, m) {
845
+ var i = b[n]
846
+ b[n] = b[m]
847
+ b[m] = i
848
+ }
849
+
850
+ Buffer.prototype.swap16 = function swap16 () {
851
+ var len = this.length
852
+ if (len % 2 !== 0) {
853
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
854
+ }
855
+ for (var i = 0; i < len; i += 2) {
856
+ swap(this, i, i + 1)
857
+ }
858
+ return this
859
+ }
860
+
861
+ Buffer.prototype.swap32 = function swap32 () {
862
+ var len = this.length
863
+ if (len % 4 !== 0) {
864
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
865
+ }
866
+ for (var i = 0; i < len; i += 4) {
867
+ swap(this, i, i + 3)
868
+ swap(this, i + 1, i + 2)
869
+ }
870
+ return this
871
+ }
872
+
873
+ Buffer.prototype.swap64 = function swap64 () {
874
+ var len = this.length
875
+ if (len % 8 !== 0) {
876
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
877
+ }
878
+ for (var i = 0; i < len; i += 8) {
879
+ swap(this, i, i + 7)
880
+ swap(this, i + 1, i + 6)
881
+ swap(this, i + 2, i + 5)
882
+ swap(this, i + 3, i + 4)
883
+ }
884
+ return this
885
+ }
886
+
752
887
  Buffer.prototype.toString = function toString () {
753
- var length = this.length | 0
888
+ var length = this.length
754
889
  if (length === 0) return ''
755
890
  if (arguments.length === 0) return utf8Slice(this, 0, length)
756
891
  return slowToString.apply(this, arguments)
757
892
  }
758
893
 
894
+ Buffer.prototype.toLocaleString = Buffer.prototype.toString
895
+
759
896
  Buffer.prototype.equals = function equals (b) {
760
897
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
761
898
  if (this === b) return true
@@ -772,63 +909,196 @@ Buffer.prototype.inspect = function inspect () {
772
909
  return '<Buffer ' + str + '>'
773
910
  }
774
911
 
775
- Buffer.prototype.compare = function compare (b) {
776
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
777
- if (this === b) return 0
778
- return Buffer.compare(this, b)
779
- }
912
+ Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
913
+ if (!Buffer.isBuffer(target)) {
914
+ throw new TypeError('Argument must be a Buffer')
915
+ }
780
916
 
781
- Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
782
- if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
783
- else if (byteOffset < -0x80000000) byteOffset = -0x80000000
784
- byteOffset >>= 0
917
+ if (start === undefined) {
918
+ start = 0
919
+ }
920
+ if (end === undefined) {
921
+ end = target ? target.length : 0
922
+ }
923
+ if (thisStart === undefined) {
924
+ thisStart = 0
925
+ }
926
+ if (thisEnd === undefined) {
927
+ thisEnd = this.length
928
+ }
785
929
 
786
- if (this.length === 0) return -1
787
- if (byteOffset >= this.length) return -1
930
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
931
+ throw new RangeError('out of range index')
932
+ }
788
933
 
789
- // Negative offsets start from the end of the buffer
790
- if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
934
+ if (thisStart >= thisEnd && start >= end) {
935
+ return 0
936
+ }
937
+ if (thisStart >= thisEnd) {
938
+ return -1
939
+ }
940
+ if (start >= end) {
941
+ return 1
942
+ }
943
+
944
+ start >>>= 0
945
+ end >>>= 0
946
+ thisStart >>>= 0
947
+ thisEnd >>>= 0
948
+
949
+ if (this === target) return 0
950
+
951
+ var x = thisEnd - thisStart
952
+ var y = end - start
953
+ var len = Math.min(x, y)
791
954
 
955
+ var thisCopy = this.slice(thisStart, thisEnd)
956
+ var targetCopy = target.slice(start, end)
957
+
958
+ for (var i = 0; i < len; ++i) {
959
+ if (thisCopy[i] !== targetCopy[i]) {
960
+ x = thisCopy[i]
961
+ y = targetCopy[i]
962
+ break
963
+ }
964
+ }
965
+
966
+ if (x < y) return -1
967
+ if (y < x) return 1
968
+ return 0
969
+ }
970
+
971
+ // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
972
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
973
+ //
974
+ // Arguments:
975
+ // - buffer - a Buffer to search
976
+ // - val - a string, Buffer, or number
977
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
978
+ // - encoding - an optional encoding, relevant is val is a string
979
+ // - dir - true for indexOf, false for lastIndexOf
980
+ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
981
+ // Empty buffer means no match
982
+ if (buffer.length === 0) return -1
983
+
984
+ // Normalize byteOffset
985
+ if (typeof byteOffset === 'string') {
986
+ encoding = byteOffset
987
+ byteOffset = 0
988
+ } else if (byteOffset > 0x7fffffff) {
989
+ byteOffset = 0x7fffffff
990
+ } else if (byteOffset < -0x80000000) {
991
+ byteOffset = -0x80000000
992
+ }
993
+ byteOffset = +byteOffset // Coerce to Number.
994
+ if (numberIsNaN(byteOffset)) {
995
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
996
+ byteOffset = dir ? 0 : (buffer.length - 1)
997
+ }
998
+
999
+ // Normalize byteOffset: negative offsets start from the end of the buffer
1000
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1001
+ if (byteOffset >= buffer.length) {
1002
+ if (dir) return -1
1003
+ else byteOffset = buffer.length - 1
1004
+ } else if (byteOffset < 0) {
1005
+ if (dir) byteOffset = 0
1006
+ else return -1
1007
+ }
1008
+
1009
+ // Normalize val
792
1010
  if (typeof val === 'string') {
793
- if (val.length === 0) return -1 // special case: looking for empty string always fails
794
- return String.prototype.indexOf.call(this, val, byteOffset)
1011
+ val = Buffer.from(val, encoding)
795
1012
  }
1013
+
1014
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
796
1015
  if (Buffer.isBuffer(val)) {
797
- return arrayIndexOf(this, val, byteOffset)
1016
+ // Special case: looking for empty string/buffer always fails
1017
+ if (val.length === 0) {
1018
+ return -1
1019
+ }
1020
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1021
+ } else if (typeof val === 'number') {
1022
+ val = val & 0xFF // Search for a byte value [0-255]
1023
+ if (typeof Uint8Array.prototype.indexOf === 'function') {
1024
+ if (dir) {
1025
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1026
+ } else {
1027
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1028
+ }
1029
+ }
1030
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
798
1031
  }
799
- if (typeof val === 'number') {
800
- if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
801
- return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
1032
+
1033
+ throw new TypeError('val must be string, number or Buffer')
1034
+ }
1035
+
1036
+ function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1037
+ var indexSize = 1
1038
+ var arrLength = arr.length
1039
+ var valLength = val.length
1040
+
1041
+ if (encoding !== undefined) {
1042
+ encoding = String(encoding).toLowerCase()
1043
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1044
+ encoding === 'utf16le' || encoding === 'utf-16le') {
1045
+ if (arr.length < 2 || val.length < 2) {
1046
+ return -1
1047
+ }
1048
+ indexSize = 2
1049
+ arrLength /= 2
1050
+ valLength /= 2
1051
+ byteOffset /= 2
1052
+ }
1053
+ }
1054
+
1055
+ function read (buf, i) {
1056
+ if (indexSize === 1) {
1057
+ return buf[i]
1058
+ } else {
1059
+ return buf.readUInt16BE(i * indexSize)
802
1060
  }
803
- return arrayIndexOf(this, [ val ], byteOffset)
804
1061
  }
805
1062
 
806
- function arrayIndexOf (arr, val, byteOffset) {
1063
+ var i
1064
+ if (dir) {
807
1065
  var foundIndex = -1
808
- for (var i = 0; byteOffset + i < arr.length; i++) {
809
- if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
1066
+ for (i = byteOffset; i < arrLength; i++) {
1067
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
810
1068
  if (foundIndex === -1) foundIndex = i
811
- if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
1069
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
812
1070
  } else {
1071
+ if (foundIndex !== -1) i -= i - foundIndex
813
1072
  foundIndex = -1
814
1073
  }
815
1074
  }
816
- return -1
1075
+ } else {
1076
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1077
+ for (i = byteOffset; i >= 0; i--) {
1078
+ var found = true
1079
+ for (var j = 0; j < valLength; j++) {
1080
+ if (read(arr, i + j) !== read(val, j)) {
1081
+ found = false
1082
+ break
1083
+ }
1084
+ }
1085
+ if (found) return i
1086
+ }
817
1087
  }
818
1088
 
819
- throw new TypeError('val must be string, number or Buffer')
1089
+ return -1
820
1090
  }
821
1091
 
822
- // `get` is deprecated
823
- Buffer.prototype.get = function get (offset) {
824
- console.log('.get() is deprecated. Access using array indexes instead.')
825
- return this.readUInt8(offset)
1092
+ Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1093
+ return this.indexOf(val, byteOffset, encoding) !== -1
826
1094
  }
827
1095
 
828
- // `set` is deprecated
829
- Buffer.prototype.set = function set (v, offset) {
830
- console.log('.set() is deprecated. Access using array indexes instead.')
831
- return this.writeUInt8(v, offset)
1096
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1097
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1098
+ }
1099
+
1100
+ Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1101
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
832
1102
  }
833
1103
 
834
1104
  function hexWrite (buf, string, offset, length) {
@@ -843,16 +1113,14 @@ function hexWrite (buf, string, offset, length) {
843
1113
  }
844
1114
  }
845
1115
 
846
- // must be an even number of digits
847
1116
  var strLen = string.length
848
- if (strLen % 2 !== 0) throw new Error('Invalid hex string')
849
1117
 
850
1118
  if (length > strLen / 2) {
851
1119
  length = strLen / 2
852
1120
  }
853
- for (var i = 0; i < length; i++) {
1121
+ for (var i = 0; i < length; ++i) {
854
1122
  var parsed = parseInt(string.substr(i * 2, 2), 16)
855
- if (isNaN(parsed)) throw new Error('Invalid hex string')
1123
+ if (numberIsNaN(parsed)) return i
856
1124
  buf[offset + i] = parsed
857
1125
  }
858
1126
  return i
@@ -866,7 +1134,7 @@ function asciiWrite (buf, string, offset, length) {
866
1134
  return blitBuffer(asciiToBytes(string), buf, offset, length)
867
1135
  }
868
1136
 
869
- function binaryWrite (buf, string, offset, length) {
1137
+ function latin1Write (buf, string, offset, length) {
870
1138
  return asciiWrite(buf, string, offset, length)
871
1139
  }
872
1140
 
@@ -891,27 +1159,25 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
891
1159
  offset = 0
892
1160
  // Buffer#write(string, offset[, length][, encoding])
893
1161
  } else if (isFinite(offset)) {
894
- offset = offset | 0
1162
+ offset = offset >>> 0
895
1163
  if (isFinite(length)) {
896
- length = length | 0
1164
+ length = length >>> 0
897
1165
  if (encoding === undefined) encoding = 'utf8'
898
1166
  } else {
899
1167
  encoding = length
900
1168
  length = undefined
901
1169
  }
902
- // legacy write(string, encoding, offset, length) - remove in v0.13
903
1170
  } else {
904
- var swap = encoding
905
- encoding = offset
906
- offset = length | 0
907
- length = swap
1171
+ throw new Error(
1172
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1173
+ )
908
1174
  }
909
1175
 
910
1176
  var remaining = this.length - offset
911
1177
  if (length === undefined || length > remaining) length = remaining
912
1178
 
913
1179
  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
914
- throw new RangeError('attempt to write outside buffer bounds')
1180
+ throw new RangeError('Attempt to write outside buffer bounds')
915
1181
  }
916
1182
 
917
1183
  if (!encoding) encoding = 'utf8'
@@ -929,8 +1195,9 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
929
1195
  case 'ascii':
930
1196
  return asciiWrite(this, string, offset, length)
931
1197
 
1198
+ case 'latin1':
932
1199
  case 'binary':
933
- return binaryWrite(this, string, offset, length)
1200
+ return latin1Write(this, string, offset, length)
934
1201
 
935
1202
  case 'base64':
936
1203
  // Warning: maxLength not taken into account in base64Write
@@ -1065,17 +1332,17 @@ function asciiSlice (buf, start, end) {
1065
1332
  var ret = ''
1066
1333
  end = Math.min(buf.length, end)
1067
1334
 
1068
- for (var i = start; i < end; i++) {
1335
+ for (var i = start; i < end; ++i) {
1069
1336
  ret += String.fromCharCode(buf[i] & 0x7F)
1070
1337
  }
1071
1338
  return ret
1072
1339
  }
1073
1340
 
1074
- function binarySlice (buf, start, end) {
1341
+ function latin1Slice (buf, start, end) {
1075
1342
  var ret = ''
1076
1343
  end = Math.min(buf.length, end)
1077
1344
 
1078
- for (var i = start; i < end; i++) {
1345
+ for (var i = start; i < end; ++i) {
1079
1346
  ret += String.fromCharCode(buf[i])
1080
1347
  }
1081
1348
  return ret
@@ -1088,7 +1355,7 @@ function hexSlice (buf, start, end) {
1088
1355
  if (!end || end < 0 || end > len) end = len
1089
1356
 
1090
1357
  var out = ''
1091
- for (var i = start; i < end; i++) {
1358
+ for (var i = start; i < end; ++i) {
1092
1359
  out += toHex(buf[i])
1093
1360
  }
1094
1361
  return out
@@ -1098,7 +1365,7 @@ function utf16leSlice (buf, start, end) {
1098
1365
  var bytes = buf.slice(start, end)
1099
1366
  var res = ''
1100
1367
  for (var i = 0; i < bytes.length; i += 2) {
1101
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1368
+ res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1102
1369
  }
1103
1370
  return res
1104
1371
  }
@@ -1124,19 +1391,9 @@ Buffer.prototype.slice = function slice (start, end) {
1124
1391
 
1125
1392
  if (end < start) end = start
1126
1393
 
1127
- var newBuf
1128
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1129
- newBuf = Buffer._augment(this.subarray(start, end))
1130
- } else {
1131
- var sliceLen = end - start
1132
- newBuf = new Buffer(sliceLen, undefined)
1133
- for (var i = 0; i < sliceLen; i++) {
1134
- newBuf[i] = this[i + start]
1135
- }
1136
- }
1137
-
1138
- if (newBuf.length) newBuf.parent = this.parent || this
1139
-
1394
+ var newBuf = this.subarray(start, end)
1395
+ // Return an augmented `Uint8Array` instance
1396
+ newBuf.__proto__ = Buffer.prototype
1140
1397
  return newBuf
1141
1398
  }
1142
1399
 
@@ -1149,8 +1406,8 @@ function checkOffset (offset, ext, length) {
1149
1406
  }
1150
1407
 
1151
1408
  Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1152
- offset = offset | 0
1153
- byteLength = byteLength | 0
1409
+ offset = offset >>> 0
1410
+ byteLength = byteLength >>> 0
1154
1411
  if (!noAssert) checkOffset(offset, byteLength, this.length)
1155
1412
 
1156
1413
  var val = this[offset]
@@ -1164,8 +1421,8 @@ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert)
1164
1421
  }
1165
1422
 
1166
1423
  Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1167
- offset = offset | 0
1168
- byteLength = byteLength | 0
1424
+ offset = offset >>> 0
1425
+ byteLength = byteLength >>> 0
1169
1426
  if (!noAssert) {
1170
1427
  checkOffset(offset, byteLength, this.length)
1171
1428
  }
@@ -1180,21 +1437,25 @@ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert)
1180
1437
  }
1181
1438
 
1182
1439
  Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1440
+ offset = offset >>> 0
1183
1441
  if (!noAssert) checkOffset(offset, 1, this.length)
1184
1442
  return this[offset]
1185
1443
  }
1186
1444
 
1187
1445
  Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1446
+ offset = offset >>> 0
1188
1447
  if (!noAssert) checkOffset(offset, 2, this.length)
1189
1448
  return this[offset] | (this[offset + 1] << 8)
1190
1449
  }
1191
1450
 
1192
1451
  Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1452
+ offset = offset >>> 0
1193
1453
  if (!noAssert) checkOffset(offset, 2, this.length)
1194
1454
  return (this[offset] << 8) | this[offset + 1]
1195
1455
  }
1196
1456
 
1197
1457
  Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1458
+ offset = offset >>> 0
1198
1459
  if (!noAssert) checkOffset(offset, 4, this.length)
1199
1460
 
1200
1461
  return ((this[offset]) |
@@ -1204,6 +1465,7 @@ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1204
1465
  }
1205
1466
 
1206
1467
  Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1468
+ offset = offset >>> 0
1207
1469
  if (!noAssert) checkOffset(offset, 4, this.length)
1208
1470
 
1209
1471
  return (this[offset] * 0x1000000) +
@@ -1213,8 +1475,8 @@ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1213
1475
  }
1214
1476
 
1215
1477
  Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1216
- offset = offset | 0
1217
- byteLength = byteLength | 0
1478
+ offset = offset >>> 0
1479
+ byteLength = byteLength >>> 0
1218
1480
  if (!noAssert) checkOffset(offset, byteLength, this.length)
1219
1481
 
1220
1482
  var val = this[offset]
@@ -1231,8 +1493,8 @@ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1231
1493
  }
1232
1494
 
1233
1495
  Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1234
- offset = offset | 0
1235
- byteLength = byteLength | 0
1496
+ offset = offset >>> 0
1497
+ byteLength = byteLength >>> 0
1236
1498
  if (!noAssert) checkOffset(offset, byteLength, this.length)
1237
1499
 
1238
1500
  var i = byteLength
@@ -1249,24 +1511,28 @@ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1249
1511
  }
1250
1512
 
1251
1513
  Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1514
+ offset = offset >>> 0
1252
1515
  if (!noAssert) checkOffset(offset, 1, this.length)
1253
1516
  if (!(this[offset] & 0x80)) return (this[offset])
1254
1517
  return ((0xff - this[offset] + 1) * -1)
1255
1518
  }
1256
1519
 
1257
1520
  Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1521
+ offset = offset >>> 0
1258
1522
  if (!noAssert) checkOffset(offset, 2, this.length)
1259
1523
  var val = this[offset] | (this[offset + 1] << 8)
1260
1524
  return (val & 0x8000) ? val | 0xFFFF0000 : val
1261
1525
  }
1262
1526
 
1263
1527
  Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1528
+ offset = offset >>> 0
1264
1529
  if (!noAssert) checkOffset(offset, 2, this.length)
1265
1530
  var val = this[offset + 1] | (this[offset] << 8)
1266
1531
  return (val & 0x8000) ? val | 0xFFFF0000 : val
1267
1532
  }
1268
1533
 
1269
1534
  Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1535
+ offset = offset >>> 0
1270
1536
  if (!noAssert) checkOffset(offset, 4, this.length)
1271
1537
 
1272
1538
  return (this[offset]) |
@@ -1276,6 +1542,7 @@ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1276
1542
  }
1277
1543
 
1278
1544
  Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1545
+ offset = offset >>> 0
1279
1546
  if (!noAssert) checkOffset(offset, 4, this.length)
1280
1547
 
1281
1548
  return (this[offset] << 24) |
@@ -1285,36 +1552,43 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1285
1552
  }
1286
1553
 
1287
1554
  Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1555
+ offset = offset >>> 0
1288
1556
  if (!noAssert) checkOffset(offset, 4, this.length)
1289
1557
  return ieee754.read(this, offset, true, 23, 4)
1290
1558
  }
1291
1559
 
1292
1560
  Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1561
+ offset = offset >>> 0
1293
1562
  if (!noAssert) checkOffset(offset, 4, this.length)
1294
1563
  return ieee754.read(this, offset, false, 23, 4)
1295
1564
  }
1296
1565
 
1297
1566
  Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1567
+ offset = offset >>> 0
1298
1568
  if (!noAssert) checkOffset(offset, 8, this.length)
1299
1569
  return ieee754.read(this, offset, true, 52, 8)
1300
1570
  }
1301
1571
 
1302
1572
  Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1573
+ offset = offset >>> 0
1303
1574
  if (!noAssert) checkOffset(offset, 8, this.length)
1304
1575
  return ieee754.read(this, offset, false, 52, 8)
1305
1576
  }
1306
1577
 
1307
1578
  function checkInt (buf, value, offset, ext, max, min) {
1308
- if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
1309
- if (value > max || value < min) throw new RangeError('value is out of bounds')
1310
- if (offset + ext > buf.length) throw new RangeError('index out of range')
1579
+ if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1580
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1581
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
1311
1582
  }
1312
1583
 
1313
1584
  Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1314
1585
  value = +value
1315
- offset = offset | 0
1316
- byteLength = byteLength | 0
1317
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1586
+ offset = offset >>> 0
1587
+ byteLength = byteLength >>> 0
1588
+ if (!noAssert) {
1589
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
1590
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
1591
+ }
1318
1592
 
1319
1593
  var mul = 1
1320
1594
  var i = 0
@@ -1328,9 +1602,12 @@ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength,
1328
1602
 
1329
1603
  Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1330
1604
  value = +value
1331
- offset = offset | 0
1332
- byteLength = byteLength | 0
1333
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1605
+ offset = offset >>> 0
1606
+ byteLength = byteLength >>> 0
1607
+ if (!noAssert) {
1608
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
1609
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
1610
+ }
1334
1611
 
1335
1612
  var i = byteLength - 1
1336
1613
  var mul = 1
@@ -1344,98 +1621,69 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength,
1344
1621
 
1345
1622
  Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1346
1623
  value = +value
1347
- offset = offset | 0
1624
+ offset = offset >>> 0
1348
1625
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1349
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1350
1626
  this[offset] = (value & 0xff)
1351
1627
  return offset + 1
1352
1628
  }
1353
1629
 
1354
- function objectWriteUInt16 (buf, value, offset, littleEndian) {
1355
- if (value < 0) value = 0xffff + value + 1
1356
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
1357
- buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1358
- (littleEndian ? i : 1 - i) * 8
1359
- }
1360
- }
1361
-
1362
1630
  Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1363
1631
  value = +value
1364
- offset = offset | 0
1632
+ offset = offset >>> 0
1365
1633
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1366
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1367
- this[offset] = (value & 0xff)
1368
- this[offset + 1] = (value >>> 8)
1369
- } else {
1370
- objectWriteUInt16(this, value, offset, true)
1371
- }
1634
+ this[offset] = (value & 0xff)
1635
+ this[offset + 1] = (value >>> 8)
1372
1636
  return offset + 2
1373
1637
  }
1374
1638
 
1375
1639
  Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1376
1640
  value = +value
1377
- offset = offset | 0
1641
+ offset = offset >>> 0
1378
1642
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1379
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1380
- this[offset] = (value >>> 8)
1381
- this[offset + 1] = (value & 0xff)
1382
- } else {
1383
- objectWriteUInt16(this, value, offset, false)
1384
- }
1643
+ this[offset] = (value >>> 8)
1644
+ this[offset + 1] = (value & 0xff)
1385
1645
  return offset + 2
1386
1646
  }
1387
1647
 
1388
- function objectWriteUInt32 (buf, value, offset, littleEndian) {
1389
- if (value < 0) value = 0xffffffff + value + 1
1390
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
1391
- buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1392
- }
1393
- }
1394
-
1395
1648
  Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1396
1649
  value = +value
1397
- offset = offset | 0
1650
+ offset = offset >>> 0
1398
1651
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1399
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1400
- this[offset + 3] = (value >>> 24)
1401
- this[offset + 2] = (value >>> 16)
1402
- this[offset + 1] = (value >>> 8)
1403
- this[offset] = (value & 0xff)
1404
- } else {
1405
- objectWriteUInt32(this, value, offset, true)
1406
- }
1652
+ this[offset + 3] = (value >>> 24)
1653
+ this[offset + 2] = (value >>> 16)
1654
+ this[offset + 1] = (value >>> 8)
1655
+ this[offset] = (value & 0xff)
1407
1656
  return offset + 4
1408
1657
  }
1409
1658
 
1410
1659
  Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1411
1660
  value = +value
1412
- offset = offset | 0
1661
+ offset = offset >>> 0
1413
1662
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1414
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1415
- this[offset] = (value >>> 24)
1416
- this[offset + 1] = (value >>> 16)
1417
- this[offset + 2] = (value >>> 8)
1418
- this[offset + 3] = (value & 0xff)
1419
- } else {
1420
- objectWriteUInt32(this, value, offset, false)
1421
- }
1663
+ this[offset] = (value >>> 24)
1664
+ this[offset + 1] = (value >>> 16)
1665
+ this[offset + 2] = (value >>> 8)
1666
+ this[offset + 3] = (value & 0xff)
1422
1667
  return offset + 4
1423
1668
  }
1424
1669
 
1425
1670
  Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1426
1671
  value = +value
1427
- offset = offset | 0
1672
+ offset = offset >>> 0
1428
1673
  if (!noAssert) {
1429
- var limit = Math.pow(2, 8 * byteLength - 1)
1674
+ var limit = Math.pow(2, (8 * byteLength) - 1)
1430
1675
 
1431
1676
  checkInt(this, value, offset, byteLength, limit - 1, -limit)
1432
1677
  }
1433
1678
 
1434
1679
  var i = 0
1435
1680
  var mul = 1
1436
- var sub = value < 0 ? 1 : 0
1681
+ var sub = 0
1437
1682
  this[offset] = value & 0xFF
1438
1683
  while (++i < byteLength && (mul *= 0x100)) {
1684
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1685
+ sub = 1
1686
+ }
1439
1687
  this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1440
1688
  }
1441
1689
 
@@ -1444,18 +1692,21 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no
1444
1692
 
1445
1693
  Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1446
1694
  value = +value
1447
- offset = offset | 0
1695
+ offset = offset >>> 0
1448
1696
  if (!noAssert) {
1449
- var limit = Math.pow(2, 8 * byteLength - 1)
1697
+ var limit = Math.pow(2, (8 * byteLength) - 1)
1450
1698
 
1451
1699
  checkInt(this, value, offset, byteLength, limit - 1, -limit)
1452
1700
  }
1453
1701
 
1454
1702
  var i = byteLength - 1
1455
1703
  var mul = 1
1456
- var sub = value < 0 ? 1 : 0
1704
+ var sub = 0
1457
1705
  this[offset + i] = value & 0xFF
1458
1706
  while (--i >= 0 && (mul *= 0x100)) {
1707
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1708
+ sub = 1
1709
+ }
1459
1710
  this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1460
1711
  }
1461
1712
 
@@ -1464,9 +1715,8 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no
1464
1715
 
1465
1716
  Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1466
1717
  value = +value
1467
- offset = offset | 0
1718
+ offset = offset >>> 0
1468
1719
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1469
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1470
1720
  if (value < 0) value = 0xff + value + 1
1471
1721
  this[offset] = (value & 0xff)
1472
1722
  return offset + 1
@@ -1474,68 +1724,53 @@ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1474
1724
 
1475
1725
  Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1476
1726
  value = +value
1477
- offset = offset | 0
1727
+ offset = offset >>> 0
1478
1728
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1479
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1480
- this[offset] = (value & 0xff)
1481
- this[offset + 1] = (value >>> 8)
1482
- } else {
1483
- objectWriteUInt16(this, value, offset, true)
1484
- }
1729
+ this[offset] = (value & 0xff)
1730
+ this[offset + 1] = (value >>> 8)
1485
1731
  return offset + 2
1486
1732
  }
1487
1733
 
1488
1734
  Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1489
1735
  value = +value
1490
- offset = offset | 0
1736
+ offset = offset >>> 0
1491
1737
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1492
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1493
- this[offset] = (value >>> 8)
1494
- this[offset + 1] = (value & 0xff)
1495
- } else {
1496
- objectWriteUInt16(this, value, offset, false)
1497
- }
1738
+ this[offset] = (value >>> 8)
1739
+ this[offset + 1] = (value & 0xff)
1498
1740
  return offset + 2
1499
1741
  }
1500
1742
 
1501
1743
  Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1502
1744
  value = +value
1503
- offset = offset | 0
1745
+ offset = offset >>> 0
1504
1746
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1505
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1506
- this[offset] = (value & 0xff)
1507
- this[offset + 1] = (value >>> 8)
1508
- this[offset + 2] = (value >>> 16)
1509
- this[offset + 3] = (value >>> 24)
1510
- } else {
1511
- objectWriteUInt32(this, value, offset, true)
1512
- }
1747
+ this[offset] = (value & 0xff)
1748
+ this[offset + 1] = (value >>> 8)
1749
+ this[offset + 2] = (value >>> 16)
1750
+ this[offset + 3] = (value >>> 24)
1513
1751
  return offset + 4
1514
1752
  }
1515
1753
 
1516
1754
  Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1517
1755
  value = +value
1518
- offset = offset | 0
1756
+ offset = offset >>> 0
1519
1757
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1520
1758
  if (value < 0) value = 0xffffffff + value + 1
1521
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1522
- this[offset] = (value >>> 24)
1523
- this[offset + 1] = (value >>> 16)
1524
- this[offset + 2] = (value >>> 8)
1525
- this[offset + 3] = (value & 0xff)
1526
- } else {
1527
- objectWriteUInt32(this, value, offset, false)
1528
- }
1759
+ this[offset] = (value >>> 24)
1760
+ this[offset + 1] = (value >>> 16)
1761
+ this[offset + 2] = (value >>> 8)
1762
+ this[offset + 3] = (value & 0xff)
1529
1763
  return offset + 4
1530
1764
  }
1531
1765
 
1532
1766
  function checkIEEE754 (buf, value, offset, ext, max, min) {
1533
- if (value > max || value < min) throw new RangeError('value is out of bounds')
1534
- if (offset + ext > buf.length) throw new RangeError('index out of range')
1535
- if (offset < 0) throw new RangeError('index out of range')
1767
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
1768
+ if (offset < 0) throw new RangeError('Index out of range')
1536
1769
  }
1537
1770
 
1538
1771
  function writeFloat (buf, value, offset, littleEndian, noAssert) {
1772
+ value = +value
1773
+ offset = offset >>> 0
1539
1774
  if (!noAssert) {
1540
1775
  checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1541
1776
  }
@@ -1552,6 +1787,8 @@ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert)
1552
1787
  }
1553
1788
 
1554
1789
  function writeDouble (buf, value, offset, littleEndian, noAssert) {
1790
+ value = +value
1791
+ offset = offset >>> 0
1555
1792
  if (!noAssert) {
1556
1793
  checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1557
1794
  }
@@ -1569,6 +1806,7 @@ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert
1569
1806
 
1570
1807
  // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1571
1808
  Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1809
+ if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
1572
1810
  if (!start) start = 0
1573
1811
  if (!end && end !== 0) end = this.length
1574
1812
  if (targetStart >= target.length) targetStart = target.length
@@ -1583,7 +1821,7 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1583
1821
  if (targetStart < 0) {
1584
1822
  throw new RangeError('targetStart out of bounds')
1585
1823
  }
1586
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1824
+ if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
1587
1825
  if (end < 0) throw new RangeError('sourceEnd out of bounds')
1588
1826
 
1589
1827
  // Are we oob?
@@ -1593,152 +1831,105 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1593
1831
  }
1594
1832
 
1595
1833
  var len = end - start
1596
- var i
1597
1834
 
1598
- if (this === target && start < targetStart && targetStart < end) {
1835
+ if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
1836
+ // Use built-in when available, missing from IE11
1837
+ this.copyWithin(targetStart, start, end)
1838
+ } else if (this === target && start < targetStart && targetStart < end) {
1599
1839
  // descending copy from end
1600
- for (i = len - 1; i >= 0; i--) {
1601
- target[i + targetStart] = this[i + start]
1602
- }
1603
- } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1604
- // ascending copy from start
1605
- for (i = 0; i < len; i++) {
1840
+ for (var i = len - 1; i >= 0; --i) {
1606
1841
  target[i + targetStart] = this[i + start]
1607
1842
  }
1608
1843
  } else {
1609
- target._set(this.subarray(start, start + len), targetStart)
1844
+ Uint8Array.prototype.set.call(
1845
+ target,
1846
+ this.subarray(start, end),
1847
+ targetStart
1848
+ )
1610
1849
  }
1611
1850
 
1612
1851
  return len
1613
1852
  }
1614
1853
 
1615
- // fill(value, start=0, end=buffer.length)
1616
- Buffer.prototype.fill = function fill (value, start, end) {
1617
- if (!value) value = 0
1618
- if (!start) start = 0
1619
- if (!end) end = this.length
1854
+ // Usage:
1855
+ // buffer.fill(number[, offset[, end]])
1856
+ // buffer.fill(buffer[, offset[, end]])
1857
+ // buffer.fill(string[, offset[, end]][, encoding])
1858
+ Buffer.prototype.fill = function fill (val, start, end, encoding) {
1859
+ // Handle string cases:
1860
+ if (typeof val === 'string') {
1861
+ if (typeof start === 'string') {
1862
+ encoding = start
1863
+ start = 0
1864
+ end = this.length
1865
+ } else if (typeof end === 'string') {
1866
+ encoding = end
1867
+ end = this.length
1868
+ }
1869
+ if (encoding !== undefined && typeof encoding !== 'string') {
1870
+ throw new TypeError('encoding must be a string')
1871
+ }
1872
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1873
+ throw new TypeError('Unknown encoding: ' + encoding)
1874
+ }
1875
+ if (val.length === 1) {
1876
+ var code = val.charCodeAt(0)
1877
+ if ((encoding === 'utf8' && code < 128) ||
1878
+ encoding === 'latin1') {
1879
+ // Fast path: If `val` fits into a single byte, use that numeric value.
1880
+ val = code
1881
+ }
1882
+ }
1883
+ } else if (typeof val === 'number') {
1884
+ val = val & 255
1885
+ }
1886
+
1887
+ // Invalid ranges are not set to a default, so can range check early.
1888
+ if (start < 0 || this.length < start || this.length < end) {
1889
+ throw new RangeError('Out of range index')
1890
+ }
1620
1891
 
1621
- if (end < start) throw new RangeError('end < start')
1892
+ if (end <= start) {
1893
+ return this
1894
+ }
1622
1895
 
1623
- // Fill 0 bytes; we're done
1624
- if (end === start) return
1625
- if (this.length === 0) return
1896
+ start = start >>> 0
1897
+ end = end === undefined ? this.length : end >>> 0
1626
1898
 
1627
- if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
1628
- if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
1899
+ if (!val) val = 0
1629
1900
 
1630
1901
  var i
1631
- if (typeof value === 'number') {
1632
- for (i = start; i < end; i++) {
1633
- this[i] = value
1902
+ if (typeof val === 'number') {
1903
+ for (i = start; i < end; ++i) {
1904
+ this[i] = val
1634
1905
  }
1635
1906
  } else {
1636
- var bytes = utf8ToBytes(value.toString())
1907
+ var bytes = Buffer.isBuffer(val)
1908
+ ? val
1909
+ : new Buffer(val, encoding)
1637
1910
  var len = bytes.length
1638
- for (i = start; i < end; i++) {
1639
- this[i] = bytes[i % len]
1911
+ if (len === 0) {
1912
+ throw new TypeError('The value "' + val +
1913
+ '" is invalid for argument "value"')
1914
+ }
1915
+ for (i = 0; i < end - start; ++i) {
1916
+ this[i + start] = bytes[i % len]
1640
1917
  }
1641
1918
  }
1642
1919
 
1643
1920
  return this
1644
1921
  }
1645
1922
 
1646
- /**
1647
- * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
1648
- * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
1649
- */
1650
- Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
1651
- if (typeof Uint8Array !== 'undefined') {
1652
- if (Buffer.TYPED_ARRAY_SUPPORT) {
1653
- return (new Buffer(this)).buffer
1654
- } else {
1655
- var buf = new Uint8Array(this.length)
1656
- for (var i = 0, len = buf.length; i < len; i += 1) {
1657
- buf[i] = this[i]
1658
- }
1659
- return buf.buffer
1660
- }
1661
- } else {
1662
- throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
1663
- }
1664
- }
1665
-
1666
1923
  // HELPER FUNCTIONS
1667
1924
  // ================
1668
1925
 
1669
- var BP = Buffer.prototype
1670
-
1671
- /**
1672
- * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
1673
- */
1674
- Buffer._augment = function _augment (arr) {
1675
- arr.constructor = Buffer
1676
- arr._isBuffer = true
1677
-
1678
- // save reference to original Uint8Array set method before overwriting
1679
- arr._set = arr.set
1680
-
1681
- // deprecated
1682
- arr.get = BP.get
1683
- arr.set = BP.set
1684
-
1685
- arr.write = BP.write
1686
- arr.toString = BP.toString
1687
- arr.toLocaleString = BP.toString
1688
- arr.toJSON = BP.toJSON
1689
- arr.equals = BP.equals
1690
- arr.compare = BP.compare
1691
- arr.indexOf = BP.indexOf
1692
- arr.copy = BP.copy
1693
- arr.slice = BP.slice
1694
- arr.readUIntLE = BP.readUIntLE
1695
- arr.readUIntBE = BP.readUIntBE
1696
- arr.readUInt8 = BP.readUInt8
1697
- arr.readUInt16LE = BP.readUInt16LE
1698
- arr.readUInt16BE = BP.readUInt16BE
1699
- arr.readUInt32LE = BP.readUInt32LE
1700
- arr.readUInt32BE = BP.readUInt32BE
1701
- arr.readIntLE = BP.readIntLE
1702
- arr.readIntBE = BP.readIntBE
1703
- arr.readInt8 = BP.readInt8
1704
- arr.readInt16LE = BP.readInt16LE
1705
- arr.readInt16BE = BP.readInt16BE
1706
- arr.readInt32LE = BP.readInt32LE
1707
- arr.readInt32BE = BP.readInt32BE
1708
- arr.readFloatLE = BP.readFloatLE
1709
- arr.readFloatBE = BP.readFloatBE
1710
- arr.readDoubleLE = BP.readDoubleLE
1711
- arr.readDoubleBE = BP.readDoubleBE
1712
- arr.writeUInt8 = BP.writeUInt8
1713
- arr.writeUIntLE = BP.writeUIntLE
1714
- arr.writeUIntBE = BP.writeUIntBE
1715
- arr.writeUInt16LE = BP.writeUInt16LE
1716
- arr.writeUInt16BE = BP.writeUInt16BE
1717
- arr.writeUInt32LE = BP.writeUInt32LE
1718
- arr.writeUInt32BE = BP.writeUInt32BE
1719
- arr.writeIntLE = BP.writeIntLE
1720
- arr.writeIntBE = BP.writeIntBE
1721
- arr.writeInt8 = BP.writeInt8
1722
- arr.writeInt16LE = BP.writeInt16LE
1723
- arr.writeInt16BE = BP.writeInt16BE
1724
- arr.writeInt32LE = BP.writeInt32LE
1725
- arr.writeInt32BE = BP.writeInt32BE
1726
- arr.writeFloatLE = BP.writeFloatLE
1727
- arr.writeFloatBE = BP.writeFloatBE
1728
- arr.writeDoubleLE = BP.writeDoubleLE
1729
- arr.writeDoubleBE = BP.writeDoubleBE
1730
- arr.fill = BP.fill
1731
- arr.inspect = BP.inspect
1732
- arr.toArrayBuffer = BP.toArrayBuffer
1733
-
1734
- return arr
1735
- }
1736
-
1737
- var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
1926
+ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
1738
1927
 
1739
1928
  function base64clean (str) {
1929
+ // Node takes equal signs as end of the Base64 encoding
1930
+ str = str.split('=')[0]
1740
1931
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
1741
- str = stringtrim(str).replace(INVALID_BASE64_RE, '')
1932
+ str = str.trim().replace(INVALID_BASE64_RE, '')
1742
1933
  // Node converts strings with length < 2 to ''
1743
1934
  if (str.length < 2) return ''
1744
1935
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
@@ -1748,11 +1939,6 @@ function base64clean (str) {
1748
1939
  return str
1749
1940
  }
1750
1941
 
1751
- function stringtrim (str) {
1752
- if (str.trim) return str.trim()
1753
- return str.replace(/^\s+|\s+$/g, '')
1754
- }
1755
-
1756
1942
  function toHex (n) {
1757
1943
  if (n < 16) return '0' + n.toString(16)
1758
1944
  return n.toString(16)
@@ -1765,7 +1951,7 @@ function utf8ToBytes (string, units) {
1765
1951
  var leadSurrogate = null
1766
1952
  var bytes = []
1767
1953
 
1768
- for (var i = 0; i < length; i++) {
1954
+ for (var i = 0; i < length; ++i) {
1769
1955
  codePoint = string.charCodeAt(i)
1770
1956
 
1771
1957
  // is surrogate component
@@ -1797,7 +1983,7 @@ function utf8ToBytes (string, units) {
1797
1983
  }
1798
1984
 
1799
1985
  // valid surrogate pair
1800
- codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
1986
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
1801
1987
  } else if (leadSurrogate) {
1802
1988
  // valid bmp char, but last char was a lead
1803
1989
  if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
@@ -1840,7 +2026,7 @@ function utf8ToBytes (string, units) {
1840
2026
 
1841
2027
  function asciiToBytes (str) {
1842
2028
  var byteArray = []
1843
- for (var i = 0; i < str.length; i++) {
2029
+ for (var i = 0; i < str.length; ++i) {
1844
2030
  // Node's code seems to be doing this and not & 0x7F..
1845
2031
  byteArray.push(str.charCodeAt(i) & 0xFF)
1846
2032
  }
@@ -1850,7 +2036,7 @@ function asciiToBytes (str) {
1850
2036
  function utf16leToBytes (str, units) {
1851
2037
  var c, hi, lo
1852
2038
  var byteArray = []
1853
- for (var i = 0; i < str.length; i++) {
2039
+ for (var i = 0; i < str.length; ++i) {
1854
2040
  if ((units -= 2) < 0) break
1855
2041
 
1856
2042
  c = str.charCodeAt(i)
@@ -1868,18 +2054,29 @@ function base64ToBytes (str) {
1868
2054
  }
1869
2055
 
1870
2056
  function blitBuffer (src, dst, offset, length) {
1871
- for (var i = 0; i < length; i++) {
2057
+ for (var i = 0; i < length; ++i) {
1872
2058
  if ((i + offset >= dst.length) || (i >= src.length)) break
1873
2059
  dst[i + offset] = src[i]
1874
2060
  }
1875
2061
  return i
1876
2062
  }
1877
2063
 
1878
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1879
- },{"base64-js":2,"ieee754":4,"is-array":5}],4:[function(require,module,exports){
2064
+ // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
2065
+ // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
2066
+ function isArrayBuffer (obj) {
2067
+ return obj instanceof ArrayBuffer ||
2068
+ (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
2069
+ typeof obj.byteLength === 'number')
2070
+ }
2071
+
2072
+ function numberIsNaN (obj) {
2073
+ return obj !== obj // eslint-disable-line no-self-compare
2074
+ }
2075
+
2076
+ },{"base64-js":2,"ieee754":4}],4:[function(require,module,exports){
1880
2077
  exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1881
2078
  var e, m
1882
- var eLen = nBytes * 8 - mLen - 1
2079
+ var eLen = (nBytes * 8) - mLen - 1
1883
2080
  var eMax = (1 << eLen) - 1
1884
2081
  var eBias = eMax >> 1
1885
2082
  var nBits = -7
@@ -1892,12 +2089,12 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1892
2089
  e = s & ((1 << (-nBits)) - 1)
1893
2090
  s >>= (-nBits)
1894
2091
  nBits += eLen
1895
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2092
+ for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
1896
2093
 
1897
2094
  m = e & ((1 << (-nBits)) - 1)
1898
2095
  e >>= (-nBits)
1899
2096
  nBits += mLen
1900
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2097
+ for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
1901
2098
 
1902
2099
  if (e === 0) {
1903
2100
  e = 1 - eBias
@@ -1912,7 +2109,7 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1912
2109
 
1913
2110
  exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1914
2111
  var e, m, c
1915
- var eLen = nBytes * 8 - mLen - 1
2112
+ var eLen = (nBytes * 8) - mLen - 1
1916
2113
  var eMax = (1 << eLen) - 1
1917
2114
  var eBias = eMax >> 1
1918
2115
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
@@ -1945,7 +2142,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1945
2142
  m = 0
1946
2143
  e = eMax
1947
2144
  } else if (e + eBias >= 1) {
1948
- m = (value * c - 1) * Math.pow(2, mLen)
2145
+ m = ((value * c) - 1) * Math.pow(2, mLen)
1949
2146
  e = e + eBias
1950
2147
  } else {
1951
2148
  m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
@@ -1963,117 +2160,11 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1963
2160
  }
1964
2161
 
1965
2162
  },{}],5:[function(require,module,exports){
1966
-
1967
- /**
1968
- * isArray
1969
- */
1970
-
1971
- var isArray = Array.isArray;
1972
-
1973
- /**
1974
- * toString
1975
- */
1976
-
1977
- var str = Object.prototype.toString;
1978
-
1979
- /**
1980
- * Whether or not the given `val`
1981
- * is an array.
1982
- *
1983
- * example:
1984
- *
1985
- * isArray([]);
1986
- * // > true
1987
- * isArray(arguments);
1988
- * // > false
1989
- * isArray('');
1990
- * // > false
1991
- *
1992
- * @param {mixed} val
1993
- * @return {bool}
1994
- */
1995
-
1996
- module.exports = isArray || function (val) {
1997
- return !! val && '[object Array]' == str.call(val);
1998
- };
1999
-
2000
- },{}],6:[function(require,module,exports){
2001
- (function (global){
2002
-
2003
- /**
2004
- * Module exports.
2005
- */
2006
-
2007
- module.exports = deprecate;
2008
-
2009
- /**
2010
- * Mark that a method should not be used.
2011
- * Returns a modified function which warns once by default.
2012
- *
2013
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
2014
- *
2015
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
2016
- * will throw an Error when invoked.
2017
- *
2018
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
2019
- * will invoke `console.trace()` instead of `console.error()`.
2020
- *
2021
- * @param {Function} fn - the function to deprecate
2022
- * @param {String} msg - the string to print to the console when `fn` is invoked
2023
- * @returns {Function} a new "deprecated" version of `fn`
2024
- * @api public
2025
- */
2026
-
2027
- function deprecate (fn, msg) {
2028
- if (config('noDeprecation')) {
2029
- return fn;
2030
- }
2031
-
2032
- var warned = false;
2033
- function deprecated() {
2034
- if (!warned) {
2035
- if (config('throwDeprecation')) {
2036
- throw new Error(msg);
2037
- } else if (config('traceDeprecation')) {
2038
- console.trace(msg);
2039
- } else {
2040
- console.warn(msg);
2041
- }
2042
- warned = true;
2043
- }
2044
- return fn.apply(this, arguments);
2045
- }
2046
-
2047
- return deprecated;
2048
- }
2049
-
2050
- /**
2051
- * Checks `localStorage` for boolean values for the given `name`.
2052
- *
2053
- * @param {String} name
2054
- * @returns {Boolean}
2055
- * @api private
2056
- */
2057
-
2058
- function config (name) {
2059
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
2060
- try {
2061
- if (!global.localStorage) return false;
2062
- } catch (_) {
2063
- return false;
2064
- }
2065
- var val = global.localStorage[name];
2066
- if (null == val) return false;
2067
- return String(val).toLowerCase() === 'true';
2068
- }
2069
-
2070
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2071
- },{}],7:[function(require,module,exports){
2072
2163
  function DOMParser(options){
2073
2164
  this.options = options ||{locator:{}};
2074
2165
 
2075
2166
  }
2076
- DOMParser.prototype.parseFromString = function(source,mimeType){
2167
+ DOMParser.prototype.parseFromString = function(source,mimeType){
2077
2168
  var options = this.options;
2078
2169
  var sax = new XMLReader();
2079
2170
  var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
@@ -2092,12 +2183,13 @@ DOMParser.prototype.parseFromString = function(source,mimeType){
2092
2183
  entityMap.copy = '\xa9';
2093
2184
  defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
2094
2185
  }
2186
+ defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
2095
2187
  if(source){
2096
2188
  sax.parse(source,defaultNSMap,entityMap);
2097
2189
  }else{
2098
- sax.errorHandler.error("invalid document source");
2190
+ sax.errorHandler.error("invalid doc source");
2099
2191
  }
2100
- return domBuilder.document;
2192
+ return domBuilder.doc;
2101
2193
  }
2102
2194
  function buildErrorHandler(errorImpl,domBuilder,locator){
2103
2195
  if(!errorImpl){
@@ -2111,27 +2203,20 @@ function buildErrorHandler(errorImpl,domBuilder,locator){
2111
2203
  locator = locator||{}
2112
2204
  function build(key){
2113
2205
  var fn = errorImpl[key];
2114
- if(!fn){
2115
- if(isCallback){
2116
- fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
2117
- }else{
2118
- var i=arguments.length;
2119
- while(--i){
2120
- if(fn = errorImpl[arguments[i]]){
2121
- break;
2122
- }
2123
- }
2124
- }
2206
+ if(!fn && isCallback){
2207
+ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
2125
2208
  }
2126
2209
  errorHandler[key] = fn && function(msg){
2127
- fn(msg+_locator(locator));
2210
+ fn('[xmldom '+key+']\t'+msg+_locator(locator));
2128
2211
  }||function(){};
2129
2212
  }
2130
- build('warning','warn');
2131
- build('error','warn','warning');
2132
- build('fatalError','warn','warning','error');
2213
+ build('warning');
2214
+ build('error');
2215
+ build('fatalError');
2133
2216
  return errorHandler;
2134
2217
  }
2218
+
2219
+ //console.log('#\n\n\n\n\n\n\n####')
2135
2220
  /**
2136
2221
  * +ContentHandler+ErrorHandler
2137
2222
  * +LexicalHandler+EntityResolver2
@@ -2154,13 +2239,13 @@ function position(locator,node){
2154
2239
  */
2155
2240
  DOMHandler.prototype = {
2156
2241
  startDocument : function() {
2157
- this.document = new DOMImplementation().createDocument(null, null, null);
2242
+ this.doc = new DOMImplementation().createDocument(null, null, null);
2158
2243
  if (this.locator) {
2159
- this.document.documentURI = this.locator.systemId;
2244
+ this.doc.documentURI = this.locator.systemId;
2160
2245
  }
2161
2246
  },
2162
2247
  startElement:function(namespaceURI, localName, qName, attrs) {
2163
- var doc = this.document;
2248
+ var doc = this.doc;
2164
2249
  var el = doc.createElementNS(namespaceURI, qName||localName);
2165
2250
  var len = attrs.length;
2166
2251
  appendElement(this, el);
@@ -2172,24 +2257,22 @@ DOMHandler.prototype = {
2172
2257
  var value = attrs.getValue(i);
2173
2258
  var qName = attrs.getQName(i);
2174
2259
  var attr = doc.createAttributeNS(namespaceURI, qName);
2175
- if( attr.getOffset){
2176
- position(attr.getOffset(1),attr)
2177
- }
2260
+ this.locator &&position(attrs.getLocator(i),attr);
2178
2261
  attr.value = attr.nodeValue = value;
2179
2262
  el.setAttributeNode(attr)
2180
2263
  }
2181
2264
  },
2182
2265
  endElement:function(namespaceURI, localName, qName) {
2183
2266
  var current = this.currentElement
2184
- var tagName = current.tagName;
2185
- this.currentElement = current.parentNode;
2267
+ var tagName = current.tagName;
2268
+ this.currentElement = current.parentNode;
2186
2269
  },
2187
2270
  startPrefixMapping:function(prefix, uri) {
2188
2271
  },
2189
2272
  endPrefixMapping:function(prefix) {
2190
2273
  },
2191
2274
  processingInstruction:function(target, data) {
2192
- var ins = this.document.createProcessingInstruction(target, data);
2275
+ var ins = this.doc.createProcessingInstruction(target, data);
2193
2276
  this.locator && position(this.locator,ins)
2194
2277
  appendElement(this, ins);
2195
2278
  },
@@ -2198,13 +2281,17 @@ DOMHandler.prototype = {
2198
2281
  characters:function(chars, start, length) {
2199
2282
  chars = _toString.apply(this,arguments)
2200
2283
  //console.log(chars)
2201
- if(this.currentElement && chars){
2284
+ if(chars){
2202
2285
  if (this.cdata) {
2203
- var charNode = this.document.createCDATASection(chars);
2204
- this.currentElement.appendChild(charNode);
2286
+ var charNode = this.doc.createCDATASection(chars);
2205
2287
  } else {
2206
- var charNode = this.document.createTextNode(chars);
2288
+ var charNode = this.doc.createTextNode(chars);
2289
+ }
2290
+ if(this.currentElement){
2207
2291
  this.currentElement.appendChild(charNode);
2292
+ }else if(/^\s*$/.test(chars)){
2293
+ this.doc.appendChild(charNode);
2294
+ //process xml
2208
2295
  }
2209
2296
  this.locator && position(this.locator,charNode)
2210
2297
  }
@@ -2212,7 +2299,7 @@ DOMHandler.prototype = {
2212
2299
  skippedEntity:function(name) {
2213
2300
  },
2214
2301
  endDocument:function() {
2215
- this.document.normalize();
2302
+ this.doc.normalize();
2216
2303
  },
2217
2304
  setDocumentLocator:function (locator) {
2218
2305
  if(this.locator = locator){// && !('lineNumber' in locator)){
@@ -2222,7 +2309,7 @@ DOMHandler.prototype = {
2222
2309
  //LexicalHandler
2223
2310
  comment:function(chars, start, length) {
2224
2311
  chars = _toString.apply(this,arguments)
2225
- var comm = this.document.createComment(chars);
2312
+ var comm = this.doc.createComment(chars);
2226
2313
  this.locator && position(this.locator,comm)
2227
2314
  appendElement(this, comm);
2228
2315
  },
@@ -2236,7 +2323,7 @@ DOMHandler.prototype = {
2236
2323
  },
2237
2324
 
2238
2325
  startDTD:function(name, publicId, systemId) {
2239
- var impl = this.document.implementation;
2326
+ var impl = this.doc.implementation;
2240
2327
  if (impl && impl.createDocumentType) {
2241
2328
  var dt = impl.createDocumentType(name, publicId, systemId);
2242
2329
  this.locator && position(this.locator,dt)
@@ -2248,13 +2335,13 @@ DOMHandler.prototype = {
2248
2335
  * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
2249
2336
  */
2250
2337
  warning:function(error) {
2251
- console.warn(error,_locator(this.locator));
2338
+ console.warn('[xmldom warning]\t'+error,_locator(this.locator));
2252
2339
  },
2253
2340
  error:function(error) {
2254
- console.error(error,_locator(this.locator));
2341
+ console.error('[xmldom error]\t'+error,_locator(this.locator));
2255
2342
  },
2256
2343
  fatalError:function(error) {
2257
- console.error(error,_locator(this.locator));
2344
+ console.error('[xmldom fatalError]\t'+error,_locator(this.locator));
2258
2345
  throw error;
2259
2346
  }
2260
2347
  }
@@ -2312,20 +2399,20 @@ function _toString(chars,start,length){
2312
2399
  /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
2313
2400
  function appendElement (hander,node) {
2314
2401
  if (!hander.currentElement) {
2315
- hander.document.appendChild(node);
2402
+ hander.doc.appendChild(node);
2316
2403
  } else {
2317
2404
  hander.currentElement.appendChild(node);
2318
2405
  }
2319
2406
  }//appendChild and setAttributeNS are preformance key
2320
2407
 
2321
- if(typeof require == 'function'){
2408
+ //if(typeof require == 'function'){
2322
2409
  var XMLReader = require('./sax').XMLReader;
2323
2410
  var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
2324
2411
  exports.XMLSerializer = require('./dom').XMLSerializer ;
2325
2412
  exports.DOMParser = DOMParser;
2326
- }
2413
+ //}
2327
2414
 
2328
- },{"./dom":8,"./sax":9}],8:[function(require,module,exports){
2415
+ },{"./dom":6,"./sax":7}],6:[function(require,module,exports){
2329
2416
  /*
2330
2417
  * DOM Level 2
2331
2418
  * Object DOMException
@@ -2437,6 +2524,12 @@ NodeList.prototype = {
2437
2524
  */
2438
2525
  item: function(index) {
2439
2526
  return this[index] || null;
2527
+ },
2528
+ toString:function(isHTML,nodeFilter){
2529
+ for(var buf = [], i = 0;i<this.length;i++){
2530
+ serializeToString(this[i],buf,isHTML,nodeFilter);
2531
+ }
2532
+ return buf.join('');
2440
2533
  }
2441
2534
  };
2442
2535
  function LiveNodeList(node,refresh){
@@ -2492,6 +2585,7 @@ function _addNamedNode(el,list,newAttr,oldAttr){
2492
2585
  }
2493
2586
  }
2494
2587
  function _removeNamedNode(el,list,attr){
2588
+ //console.log('remove attr:'+attr)
2495
2589
  var i = _findNodeIndex(list,attr);
2496
2590
  if(i>=0){
2497
2591
  var lastIndex = list.length-1
@@ -2507,7 +2601,7 @@ function _removeNamedNode(el,list,attr){
2507
2601
  }
2508
2602
  }
2509
2603
  }else{
2510
- throw DOMException(NOT_FOUND_ERR,new Error())
2604
+ throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
2511
2605
  }
2512
2606
  }
2513
2607
  NamedNodeMap.prototype = {
@@ -2517,9 +2611,11 @@ NamedNodeMap.prototype = {
2517
2611
  // if(key.indexOf(':')>0 || key == 'xmlns'){
2518
2612
  // return null;
2519
2613
  // }
2614
+ //console.log()
2520
2615
  var i = this.length;
2521
2616
  while(i--){
2522
2617
  var attr = this[i];
2618
+ //console.log(attr.nodeName,key)
2523
2619
  if(attr.nodeName == key){
2524
2620
  return attr;
2525
2621
  }
@@ -2595,12 +2691,12 @@ DOMImplementation.prototype = {
2595
2691
  // Introduced in DOM Level 2:
2596
2692
  createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
2597
2693
  var doc = new Document();
2694
+ doc.implementation = this;
2695
+ doc.childNodes = new NodeList();
2598
2696
  doc.doctype = doctype;
2599
2697
  if(doctype){
2600
2698
  doc.appendChild(doctype);
2601
2699
  }
2602
- doc.implementation = this;
2603
- doc.childNodes = new NodeList();
2604
2700
  if(qualifiedName){
2605
2701
  var root = doc.createElementNS(namespaceURI,qualifiedName);
2606
2702
  doc.appendChild(root);
@@ -2701,7 +2797,7 @@ Node.prototype = {
2701
2797
  }
2702
2798
  }
2703
2799
  }
2704
- el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2800
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
2705
2801
  }
2706
2802
  return null;
2707
2803
  },
@@ -2716,7 +2812,7 @@ Node.prototype = {
2716
2812
  return map[prefix] ;
2717
2813
  }
2718
2814
  }
2719
- el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2815
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
2720
2816
  }
2721
2817
  return null;
2722
2818
  },
@@ -2901,7 +2997,7 @@ Document.prototype = {
2901
2997
  }
2902
2998
  return newChild;
2903
2999
  }
2904
- if(this.documentElement == null && newChild.nodeType == 1){
3000
+ if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
2905
3001
  this.documentElement = newChild;
2906
3002
  }
2907
3003
 
@@ -2921,7 +3017,7 @@ Document.prototype = {
2921
3017
  getElementById : function(id){
2922
3018
  var rtv = null;
2923
3019
  _visitNode(this.documentElement,function(node){
2924
- if(node.nodeType == 1){
3020
+ if(node.nodeType == ELEMENT_NODE){
2925
3021
  if(node.getAttribute('id') == id){
2926
3022
  rtv = node;
2927
3023
  return true;
@@ -3070,6 +3166,7 @@ Element.prototype = {
3070
3166
  return this.attributes.setNamedItemNS(newAttr);
3071
3167
  },
3072
3168
  removeAttributeNode : function(oldAttr){
3169
+ //console.log(this == oldAttr.ownerElement)
3073
3170
  return this.attributes.removeNamedItem(oldAttr.nodeName);
3074
3171
  },
3075
3172
  //get real attribute name,and remove it by removeAttributeNode
@@ -3087,7 +3184,7 @@ Element.prototype = {
3087
3184
  },
3088
3185
  setAttributeNS : function(namespaceURI, qualifiedName, value){
3089
3186
  var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
3090
- attr.value = attr.nodeValue = value;
3187
+ attr.value = attr.nodeValue = "" + value;
3091
3188
  this.setAttributeNode(attr)
3092
3189
  },
3093
3190
  getAttributeNodeNS : function(namespaceURI, localName){
@@ -3109,11 +3206,12 @@ Element.prototype = {
3109
3206
  return new LiveNodeList(this,function(base){
3110
3207
  var ls = [];
3111
3208
  _visitNode(base,function(node){
3112
- if(node !== base && node.nodeType === ELEMENT_NODE && node.namespaceURI === namespaceURI && (localName === '*' || node.localName == localName)){
3209
+ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
3113
3210
  ls.push(node);
3114
3211
  }
3115
3212
  });
3116
3213
  return ls;
3214
+
3117
3215
  });
3118
3216
  }
3119
3217
  };
@@ -3145,10 +3243,7 @@ CharacterData.prototype = {
3145
3243
 
3146
3244
  },
3147
3245
  appendChild:function(newChild){
3148
- //if(!(newChild instanceof CharacterData)){
3149
- throw new Error(ExceptionMessage[3])
3150
- //}
3151
- return Node.prototype.appendChild.apply(this,arguments)
3246
+ throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
3152
3247
  },
3153
3248
  deleteData: function(offset, count) {
3154
3249
  this.replaceData(offset,count,"");
@@ -3230,36 +3325,132 @@ function ProcessingInstruction() {
3230
3325
  ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
3231
3326
  _extends(ProcessingInstruction,Node);
3232
3327
  function XMLSerializer(){}
3233
- XMLSerializer.prototype.serializeToString = function(node){
3328
+ XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
3329
+ return nodeSerializeToString.call(node,isHtml,nodeFilter);
3330
+ }
3331
+ Node.prototype.toString = nodeSerializeToString;
3332
+ function nodeSerializeToString(isHtml,nodeFilter){
3234
3333
  var buf = [];
3235
- serializeToString(node,buf);
3334
+ var refNode = this.nodeType == 9?this.documentElement:this;
3335
+ var prefix = refNode.prefix;
3336
+ var uri = refNode.namespaceURI;
3337
+
3338
+ if(uri && prefix == null){
3339
+ //console.log(prefix)
3340
+ var prefix = refNode.lookupPrefix(uri);
3341
+ if(prefix == null){
3342
+ //isHTML = true;
3343
+ var visibleNamespaces=[
3344
+ {namespace:uri,prefix:null}
3345
+ //{namespace:uri,prefix:''}
3346
+ ]
3347
+ }
3348
+ }
3349
+ serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
3350
+ //console.log('###',this.nodeType,uri,prefix,buf.join(''))
3236
3351
  return buf.join('');
3237
3352
  }
3238
- Node.prototype.toString =function(){
3239
- return XMLSerializer.prototype.serializeToString(this);
3240
- }
3241
- function serializeToString(node,buf){
3353
+ function needNamespaceDefine(node,isHTML, visibleNamespaces) {
3354
+ var prefix = node.prefix||'';
3355
+ var uri = node.namespaceURI;
3356
+ if (!prefix && !uri){
3357
+ return false;
3358
+ }
3359
+ if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
3360
+ || uri == 'http://www.w3.org/2000/xmlns/'){
3361
+ return false;
3362
+ }
3363
+
3364
+ var i = visibleNamespaces.length
3365
+ //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
3366
+ while (i--) {
3367
+ var ns = visibleNamespaces[i];
3368
+ // get namespace prefix
3369
+ //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
3370
+ if (ns.prefix == prefix){
3371
+ return ns.namespace != uri;
3372
+ }
3373
+ }
3374
+ //console.log(isHTML,uri,prefix=='')
3375
+ //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
3376
+ // return false;
3377
+ //}
3378
+ //node.flag = '11111'
3379
+ //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
3380
+ return true;
3381
+ }
3382
+ function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
3383
+ if(nodeFilter){
3384
+ node = nodeFilter(node);
3385
+ if(node){
3386
+ if(typeof node == 'string'){
3387
+ buf.push(node);
3388
+ return;
3389
+ }
3390
+ }else{
3391
+ return;
3392
+ }
3393
+ //buf.sort.apply(attrs, attributeSorter);
3394
+ }
3242
3395
  switch(node.nodeType){
3243
3396
  case ELEMENT_NODE:
3397
+ if (!visibleNamespaces) visibleNamespaces = [];
3398
+ var startVisibleNamespaces = visibleNamespaces.length;
3244
3399
  var attrs = node.attributes;
3245
3400
  var len = attrs.length;
3246
3401
  var child = node.firstChild;
3247
3402
  var nodeName = node.tagName;
3248
- var isHTML = htmlns === node.namespaceURI
3403
+
3404
+ isHTML = (htmlns === node.namespaceURI) ||isHTML
3249
3405
  buf.push('<',nodeName);
3406
+
3407
+
3408
+
3250
3409
  for(var i=0;i<len;i++){
3251
- serializeToString(attrs.item(i),buf,isHTML);
3410
+ // add namespaces for attributes
3411
+ var attr = attrs.item(i);
3412
+ if (attr.prefix == 'xmlns') {
3413
+ visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
3414
+ }else if(attr.nodeName == 'xmlns'){
3415
+ visibleNamespaces.push({ prefix: '', namespace: attr.value });
3416
+ }
3252
3417
  }
3418
+ for(var i=0;i<len;i++){
3419
+ var attr = attrs.item(i);
3420
+ if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
3421
+ var prefix = attr.prefix||'';
3422
+ var uri = attr.namespaceURI;
3423
+ var ns = prefix ? ' xmlns:' + prefix : " xmlns";
3424
+ buf.push(ns, '="' , uri , '"');
3425
+ visibleNamespaces.push({ prefix: prefix, namespace:uri });
3426
+ }
3427
+ serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
3428
+ }
3429
+ // add namespace for current node
3430
+ if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
3431
+ var prefix = node.prefix||'';
3432
+ var uri = node.namespaceURI;
3433
+ var ns = prefix ? ' xmlns:' + prefix : " xmlns";
3434
+ buf.push(ns, '="' , uri , '"');
3435
+ visibleNamespaces.push({ prefix: prefix, namespace:uri });
3436
+ }
3437
+
3253
3438
  if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
3254
3439
  buf.push('>');
3255
3440
  //if is cdata child node
3256
3441
  if(isHTML && /^script$/i.test(nodeName)){
3257
- if(child){
3258
- buf.push(child.data);
3442
+ while(child){
3443
+ if(child.data){
3444
+ buf.push(child.data);
3445
+ }else{
3446
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
3447
+ }
3448
+ child = child.nextSibling;
3259
3449
  }
3260
- }else{
3450
+ }else
3451
+ {
3261
3452
  while(child){
3262
- serializeToString(child,buf);
3453
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
3263
3454
  child = child.nextSibling;
3264
3455
  }
3265
3456
  }
@@ -3267,12 +3458,14 @@ function serializeToString(node,buf){
3267
3458
  }else{
3268
3459
  buf.push('/>');
3269
3460
  }
3461
+ // remove added visible namespaces
3462
+ //visibleNamespaces.length = startVisibleNamespaces;
3270
3463
  return;
3271
3464
  case DOCUMENT_NODE:
3272
3465
  case DOCUMENT_FRAGMENT_NODE:
3273
3466
  var child = node.firstChild;
3274
3467
  while(child){
3275
- serializeToString(child,buf);
3468
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
3276
3469
  child = child.nextSibling;
3277
3470
  }
3278
3471
  return;
@@ -3417,8 +3610,8 @@ try{
3417
3610
  },
3418
3611
  set:function(data){
3419
3612
  switch(this.nodeType){
3420
- case 1:
3421
- case 11:
3613
+ case ELEMENT_NODE:
3614
+ case DOCUMENT_FRAGMENT_NODE:
3422
3615
  while(this.firstChild){
3423
3616
  this.removeChild(this.firstChild);
3424
3617
  }
@@ -3429,7 +3622,7 @@ try{
3429
3622
  default:
3430
3623
  //TODO:
3431
3624
  this.data = data;
3432
- this.value = value;
3625
+ this.value = data;
3433
3626
  this.nodeValue = data;
3434
3627
  }
3435
3628
  }
@@ -3437,8 +3630,8 @@ try{
3437
3630
 
3438
3631
  function getTextContent(node){
3439
3632
  switch(node.nodeType){
3440
- case 1:
3441
- case 11:
3633
+ case ELEMENT_NODE:
3634
+ case DOCUMENT_FRAGMENT_NODE:
3442
3635
  var buf = [];
3443
3636
  node = node.firstChild;
3444
3637
  while(node){
@@ -3460,31 +3653,31 @@ try{
3460
3653
  }catch(e){//ie8
3461
3654
  }
3462
3655
 
3463
- if(typeof require == 'function'){
3656
+ //if(typeof require == 'function'){
3464
3657
  exports.DOMImplementation = DOMImplementation;
3465
3658
  exports.XMLSerializer = XMLSerializer;
3466
- }
3659
+ //}
3467
3660
 
3468
- },{}],9:[function(require,module,exports){
3661
+ },{}],7:[function(require,module,exports){
3469
3662
  //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
3470
3663
  //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
3471
3664
  //[5] Name ::= NameStartChar (NameChar)*
3472
3665
  var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
3473
- var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\u00B7\u0300-\u036F\\ux203F-\u2040]");
3666
+ var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
3474
3667
  var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
3475
3668
  //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
3476
3669
  //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
3477
3670
 
3478
- //S_TAG, S_ATTR, S_EQ, S_V
3479
- //S_ATTR_S, S_E, S_S, S_C
3671
+ //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
3672
+ //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
3480
3673
  var S_TAG = 0;//tag name offerring
3481
3674
  var S_ATTR = 1;//attr name offerring
3482
- var S_ATTR_S=2;//attr name end and space offer
3675
+ var S_ATTR_SPACE=2;//attr name end and space offer
3483
3676
  var S_EQ = 3;//=space?
3484
- var S_V = 4;//attr value(no quot value only)
3485
- var S_E = 5;//attr value end and no space(quot end)
3486
- var S_S = 6;//(attr value end || tag end ) && (space offer)
3487
- var S_C = 7;//closed el<el />
3677
+ var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
3678
+ var S_ATTR_END = 5;//attr value end and no space(quot end)
3679
+ var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
3680
+ var S_TAG_CLOSE = 7;//closed el<el />
3488
3681
 
3489
3682
  function XMLReader(){
3490
3683
 
@@ -3501,7 +3694,7 @@ XMLReader.prototype = {
3501
3694
  }
3502
3695
  }
3503
3696
  function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
3504
- function fixedFromCharCode(code) {
3697
+ function fixedFromCharCode(code) {
3505
3698
  // String.prototype.fromCharCode does not supports
3506
3699
  // > 2 bytes unicode chars directly
3507
3700
  if (code > 0xffff) {
@@ -3526,95 +3719,126 @@ function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
3526
3719
  }
3527
3720
  }
3528
3721
  function appendText(end){//has some bugs
3529
- var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
3530
- locator&&position(start);
3531
- domBuilder.characters(xt,0,end-start);
3532
- start = end
3722
+ if(end>start){
3723
+ var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
3724
+ locator&&position(start);
3725
+ domBuilder.characters(xt,0,end-start);
3726
+ start = end
3727
+ }
3533
3728
  }
3534
- function position(start,m){
3535
- while(start>=endPos && (m = linePattern.exec(source))){
3536
- startPos = m.index;
3537
- endPos = startPos + m[0].length;
3729
+ function position(p,m){
3730
+ while(p>=lineEnd && (m = linePattern.exec(source))){
3731
+ lineStart = m.index;
3732
+ lineEnd = lineStart + m[0].length;
3538
3733
  locator.lineNumber++;
3539
3734
  //console.log('line++:',locator,startPos,endPos)
3540
3735
  }
3541
- locator.columnNumber = start-startPos+1;
3736
+ locator.columnNumber = p-lineStart+1;
3542
3737
  }
3543
- var startPos = 0;
3544
- var endPos = 0;
3545
- var linePattern = /.+(?:\r\n?|\n)|.*$/g
3738
+ var lineStart = 0;
3739
+ var lineEnd = 0;
3740
+ var linePattern = /.*(?:\r\n?|\n)|.*$/g
3546
3741
  var locator = domBuilder.locator;
3547
3742
 
3548
3743
  var parseStack = [{currentNSMap:defaultNSMapCopy}]
3549
3744
  var closeMap = {};
3550
3745
  var start = 0;
3551
3746
  while(true){
3552
- var i = source.indexOf('<',start);
3553
- if(i<0){
3554
- if(!source.substr(start).match(/^\s*$/)){
3555
- var doc = domBuilder.document;
3556
- var text = doc.createTextNode(source.substr(start));
3557
- doc.appendChild(text);
3558
- domBuilder.currentElement = text;
3559
- }
3560
- return;
3561
- }
3562
- if(i>start){
3563
- appendText(i);
3564
- }
3565
- switch(source.charAt(i+1)){
3566
- case '/':
3567
- var end = source.indexOf('>',i+3);
3568
- var tagName = source.substring(i+2,end);
3569
- var config = parseStack.pop();
3570
- var localNSMap = config.localNSMap;
3571
-
3572
- if(config.tagName != tagName){
3573
- errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
3574
- }
3575
- domBuilder.endElement(config.uri,config.localName,tagName);
3576
- if(localNSMap){
3577
- for(var prefix in localNSMap){
3578
- domBuilder.endPrefixMapping(prefix) ;
3747
+ try{
3748
+ var tagStart = source.indexOf('<',start);
3749
+ if(tagStart<0){
3750
+ if(!source.substr(start).match(/^\s*$/)){
3751
+ var doc = domBuilder.doc;
3752
+ var text = doc.createTextNode(source.substr(start));
3753
+ doc.appendChild(text);
3754
+ domBuilder.currentElement = text;
3579
3755
  }
3756
+ return;
3580
3757
  }
3581
- end++;
3582
- break;
3583
- // end elment
3584
- case '?':// <?...?>
3585
- locator&&position(i);
3586
- end = parseInstruction(source,i,domBuilder);
3587
- break;
3588
- case '!':// <!doctype,<![CDATA,<!--
3589
- locator&&position(i);
3590
- end = parseDCC(source,i,domBuilder,errorHandler);
3591
- break;
3592
- default:
3593
- try{
3594
- locator&&position(i);
3758
+ if(tagStart>start){
3759
+ appendText(tagStart);
3760
+ }
3761
+ switch(source.charAt(tagStart+1)){
3762
+ case '/':
3763
+ var end = source.indexOf('>',tagStart+3);
3764
+ var tagName = source.substring(tagStart+2,end);
3765
+ var config = parseStack.pop();
3766
+ if(end<0){
3767
+
3768
+ tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
3769
+ //console.error('#@@@@@@'+tagName)
3770
+ errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
3771
+ end = tagStart+1+tagName.length;
3772
+ }else if(tagName.match(/\s</)){
3773
+ tagName = tagName.replace(/[\s<].*/,'');
3774
+ errorHandler.error("end tag name: "+tagName+' maybe not complete');
3775
+ end = tagStart+1+tagName.length;
3776
+ }
3777
+ //console.error(parseStack.length,parseStack)
3778
+ //console.error(config);
3779
+ var localNSMap = config.localNSMap;
3780
+ var endMatch = config.tagName == tagName;
3781
+ var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
3782
+ if(endIgnoreCaseMach){
3783
+ domBuilder.endElement(config.uri,config.localName,tagName);
3784
+ if(localNSMap){
3785
+ for(var prefix in localNSMap){
3786
+ domBuilder.endPrefixMapping(prefix) ;
3787
+ }
3788
+ }
3789
+ if(!endMatch){
3790
+ errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
3791
+ }
3792
+ }else{
3793
+ parseStack.push(config)
3794
+ }
3595
3795
 
3796
+ end++;
3797
+ break;
3798
+ // end elment
3799
+ case '?':// <?...?>
3800
+ locator&&position(tagStart);
3801
+ end = parseInstruction(source,tagStart,domBuilder);
3802
+ break;
3803
+ case '!':// <!doctype,<![CDATA,<!--
3804
+ locator&&position(tagStart);
3805
+ end = parseDCC(source,tagStart,domBuilder,errorHandler);
3806
+ break;
3807
+ default:
3808
+ locator&&position(tagStart);
3596
3809
  var el = new ElementAttributes();
3597
-
3810
+ var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
3598
3811
  //elStartEnd
3599
- var end = parseElementStartPart(source,i,el,entityReplacer,errorHandler);
3812
+ var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
3600
3813
  var len = el.length;
3601
- //position fixed
3602
- if(len && locator){
3603
- var backup = copyLocator(locator,{});
3604
- for(var i = 0;i<len;i++){
3605
- var a = el[i];
3606
- position(a.offset);
3607
- a.offset = copyLocator(locator,{});
3608
- }
3609
- copyLocator(backup,locator);
3610
- }
3814
+
3815
+
3611
3816
  if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
3612
3817
  el.closed = true;
3613
3818
  if(!entityMap.nbsp){
3614
3819
  errorHandler.warning('unclosed xml attribute');
3615
3820
  }
3616
3821
  }
3617
- appendElement(el,domBuilder,parseStack);
3822
+ if(locator && len){
3823
+ var locator2 = copyLocator(locator,{});
3824
+ //try{//attribute position fixed
3825
+ for(var i = 0;i<len;i++){
3826
+ var a = el[i];
3827
+ position(a.offset);
3828
+ a.locator = copyLocator(locator,{});
3829
+ }
3830
+ //}catch(e){console.error('@@@@@'+e)}
3831
+ domBuilder.locator = locator2
3832
+ if(appendElement(el,domBuilder,currentNSMap)){
3833
+ parseStack.push(el)
3834
+ }
3835
+ domBuilder.locator = locator;
3836
+ }else{
3837
+ if(appendElement(el,domBuilder,currentNSMap)){
3838
+ parseStack.push(el)
3839
+ }
3840
+ }
3841
+
3618
3842
 
3619
3843
 
3620
3844
  if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
@@ -3622,17 +3846,18 @@ function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
3622
3846
  }else{
3623
3847
  end++;
3624
3848
  }
3625
- }catch(e){
3626
- errorHandler.error('element parse error: '+e);
3627
- end = -1;
3628
3849
  }
3629
-
3850
+ }catch(e){
3851
+ errorHandler.error('element parse error: '+e)
3852
+ //errorHandler.error('element parse error: '+e);
3853
+ end = -1;
3854
+ //throw e;
3630
3855
  }
3631
- if(end<0){
3632
- //TODO: 这里有可能sax回退,有位置错误风险
3633
- appendText(i+1);
3634
- }else{
3856
+ if(end>start){
3635
3857
  start = end;
3858
+ }else{
3859
+ //TODO: 这里有可能sax回退,有位置错误风险
3860
+ appendText(Math.max(tagStart,start)+1);
3636
3861
  }
3637
3862
  }
3638
3863
  }
@@ -3640,14 +3865,13 @@ function copyLocator(f,t){
3640
3865
  t.lineNumber = f.lineNumber;
3641
3866
  t.columnNumber = f.columnNumber;
3642
3867
  return t;
3643
-
3644
3868
  }
3645
3869
 
3646
3870
  /**
3647
3871
  * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
3648
3872
  * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
3649
3873
  */
3650
- function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3874
+ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
3651
3875
  var attrName;
3652
3876
  var value;
3653
3877
  var p = ++start;
@@ -3659,7 +3883,7 @@ function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3659
3883
  if(s === S_ATTR){//attrName
3660
3884
  attrName = source.slice(start,p);
3661
3885
  s = S_EQ;
3662
- }else if(s === S_ATTR_S){
3886
+ }else if(s === S_ATTR_SPACE){
3663
3887
  s = S_EQ;
3664
3888
  }else{
3665
3889
  //fatalError: equal must after attrName or space after attrName
@@ -3668,25 +3892,30 @@ function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3668
3892
  break;
3669
3893
  case '\'':
3670
3894
  case '"':
3671
- if(s === S_EQ){//equal
3895
+ if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
3896
+ ){//equal
3897
+ if(s === S_ATTR){
3898
+ errorHandler.warning('attribute value must after "="')
3899
+ attrName = source.slice(start,p)
3900
+ }
3672
3901
  start = p+1;
3673
3902
  p = source.indexOf(c,start)
3674
3903
  if(p>0){
3675
3904
  value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3676
3905
  el.add(attrName,value,start-1);
3677
- s = S_E;
3906
+ s = S_ATTR_END;
3678
3907
  }else{
3679
3908
  //fatalError: no end quot match
3680
3909
  throw new Error('attribute value no end \''+c+'\' match');
3681
3910
  }
3682
- }else if(s == S_V){
3911
+ }else if(s == S_ATTR_NOQUOT_VALUE){
3683
3912
  value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3684
3913
  //console.log(attrName,value,start,p)
3685
3914
  el.add(attrName,value,start);
3686
3915
  //console.dir(el)
3687
3916
  errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
3688
3917
  start = p+1;
3689
- s = S_E
3918
+ s = S_ATTR_END
3690
3919
  }else{
3691
3920
  //fatalError: no equal before
3692
3921
  throw new Error('attribute value must after "="');
@@ -3696,14 +3925,14 @@ function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3696
3925
  switch(s){
3697
3926
  case S_TAG:
3698
3927
  el.setTagName(source.slice(start,p));
3699
- case S_E:
3700
- case S_S:
3701
- case S_C:
3702
- s = S_C;
3928
+ case S_ATTR_END:
3929
+ case S_TAG_SPACE:
3930
+ case S_TAG_CLOSE:
3931
+ s =S_TAG_CLOSE;
3703
3932
  el.closed = true;
3704
- case S_V:
3933
+ case S_ATTR_NOQUOT_VALUE:
3705
3934
  case S_ATTR:
3706
- case S_ATTR_S:
3935
+ case S_ATTR_SPACE:
3707
3936
  break;
3708
3937
  //case S_EQ:
3709
3938
  default:
@@ -3713,30 +3942,36 @@ function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3713
3942
  case ''://end document
3714
3943
  //throw new Error('unexpected end of input')
3715
3944
  errorHandler.error('unexpected end of input');
3945
+ if(s == S_TAG){
3946
+ el.setTagName(source.slice(start,p));
3947
+ }
3948
+ return p;
3716
3949
  case '>':
3717
3950
  switch(s){
3718
3951
  case S_TAG:
3719
3952
  el.setTagName(source.slice(start,p));
3720
- case S_E:
3721
- case S_S:
3722
- case S_C:
3953
+ case S_ATTR_END:
3954
+ case S_TAG_SPACE:
3955
+ case S_TAG_CLOSE:
3723
3956
  break;//normal
3724
- case S_V://Compatible state
3957
+ case S_ATTR_NOQUOT_VALUE://Compatible state
3725
3958
  case S_ATTR:
3726
3959
  value = source.slice(start,p);
3727
3960
  if(value.slice(-1) === '/'){
3728
3961
  el.closed = true;
3729
3962
  value = value.slice(0,-1)
3730
3963
  }
3731
- case S_ATTR_S:
3732
- if(s === S_ATTR_S){
3964
+ case S_ATTR_SPACE:
3965
+ if(s === S_ATTR_SPACE){
3733
3966
  value = attrName;
3734
3967
  }
3735
- if(s == S_V){
3968
+ if(s == S_ATTR_NOQUOT_VALUE){
3736
3969
  errorHandler.warning('attribute "'+value+'" missed quot(")!!');
3737
3970
  el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
3738
3971
  }else{
3739
- errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
3972
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
3973
+ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
3974
+ }
3740
3975
  el.add(value,value,start)
3741
3976
  }
3742
3977
  break;
@@ -3753,64 +3988,68 @@ function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3753
3988
  switch(s){
3754
3989
  case S_TAG:
3755
3990
  el.setTagName(source.slice(start,p));//tagName
3756
- s = S_S;
3991
+ s = S_TAG_SPACE;
3757
3992
  break;
3758
3993
  case S_ATTR:
3759
3994
  attrName = source.slice(start,p)
3760
- s = S_ATTR_S;
3995
+ s = S_ATTR_SPACE;
3761
3996
  break;
3762
- case S_V:
3997
+ case S_ATTR_NOQUOT_VALUE:
3763
3998
  var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3764
3999
  errorHandler.warning('attribute "'+value+'" missed quot(")!!');
3765
4000
  el.add(attrName,value,start)
3766
- case S_E:
3767
- s = S_S;
4001
+ case S_ATTR_END:
4002
+ s = S_TAG_SPACE;
3768
4003
  break;
3769
- //case S_S:
4004
+ //case S_TAG_SPACE:
3770
4005
  //case S_EQ:
3771
- //case S_ATTR_S:
4006
+ //case S_ATTR_SPACE:
3772
4007
  // void();break;
3773
- //case S_C:
4008
+ //case S_TAG_CLOSE:
3774
4009
  //ignore warning
3775
4010
  }
3776
4011
  }else{//not space
3777
- //S_TAG, S_ATTR, S_EQ, S_V
3778
- //S_ATTR_S, S_E, S_S, S_C
4012
+ //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
4013
+ //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
3779
4014
  switch(s){
3780
4015
  //case S_TAG:void();break;
3781
4016
  //case S_ATTR:void();break;
3782
- //case S_V:void();break;
3783
- case S_ATTR_S:
3784
- errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead!!')
4017
+ //case S_ATTR_NOQUOT_VALUE:void();break;
4018
+ case S_ATTR_SPACE:
4019
+ var tagName = el.tagName;
4020
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
4021
+ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
4022
+ }
3785
4023
  el.add(attrName,attrName,start);
3786
4024
  start = p;
3787
4025
  s = S_ATTR;
3788
4026
  break;
3789
- case S_E:
4027
+ case S_ATTR_END:
3790
4028
  errorHandler.warning('attribute space is required"'+attrName+'"!!')
3791
- case S_S:
4029
+ case S_TAG_SPACE:
3792
4030
  s = S_ATTR;
3793
4031
  start = p;
3794
4032
  break;
3795
4033
  case S_EQ:
3796
- s = S_V;
4034
+ s = S_ATTR_NOQUOT_VALUE;
3797
4035
  start = p;
3798
4036
  break;
3799
- case S_C:
4037
+ case S_TAG_CLOSE:
3800
4038
  throw new Error("elements closed character '/' and '>' must be connected to");
3801
4039
  }
3802
4040
  }
3803
- }
4041
+ }//end outer switch
4042
+ //console.log('p++',p)
3804
4043
  p++;
3805
4044
  }
3806
4045
  }
3807
4046
  /**
3808
- * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
4047
+ * @return true if has new namespace define
3809
4048
  */
3810
- function appendElement(el,domBuilder,parseStack){
4049
+ function appendElement(el,domBuilder,currentNSMap){
3811
4050
  var tagName = el.tagName;
3812
4051
  var localNSMap = null;
3813
- var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
4052
+ //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
3814
4053
  var i = el.length;
3815
4054
  while(i--){
3816
4055
  var a = el[i];
@@ -3849,7 +4088,7 @@ function appendElement(el,domBuilder,parseStack){
3849
4088
  if(prefix === 'xml'){
3850
4089
  a.uri = 'http://www.w3.org/XML/1998/namespace';
3851
4090
  }if(prefix !== 'xmlns'){
3852
- a.uri = currentNSMap[prefix]
4091
+ a.uri = currentNSMap[prefix || '']
3853
4092
 
3854
4093
  //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
3855
4094
  }
@@ -3878,7 +4117,8 @@ function appendElement(el,domBuilder,parseStack){
3878
4117
  }else{
3879
4118
  el.currentNSMap = currentNSMap;
3880
4119
  el.localNSMap = localNSMap;
3881
- parseStack.push(el);
4120
+ //parseStack.push(el);
4121
+ return true;
3882
4122
  }
3883
4123
  }
3884
4124
  function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
@@ -3908,7 +4148,11 @@ function fixSelfClosed(source,elStartEnd,tagName,closeMap){
3908
4148
  var pos = closeMap[tagName];
3909
4149
  if(pos == null){
3910
4150
  //console.log(tagName)
3911
- pos = closeMap[tagName] = source.lastIndexOf('</'+tagName+'>')
4151
+ pos = source.lastIndexOf('</'+tagName+'>')
4152
+ if(pos<elStartEnd){//忘记闭合
4153
+ pos = source.lastIndexOf('</'+tagName)
4154
+ }
4155
+ closeMap[tagName] =pos
3912
4156
  }
3913
4157
  return pos<elStartEnd;
3914
4158
  //}
@@ -3999,7 +4243,7 @@ ElementAttributes.prototype = {
3999
4243
  },
4000
4244
  length:0,
4001
4245
  getLocalName:function(i){return this[i].localName},
4002
- getOffset:function(i){return this[i].offset},
4246
+ getLocator:function(i){return this[i].locator},
4003
4247
  getQName:function(i){return this[i].qName},
4004
4248
  getURI:function(i){return this[i].uri},
4005
4249
  getValue:function(i){return this[i].value}
@@ -4046,10 +4290,8 @@ function split(source,start){
4046
4290
  }
4047
4291
  }
4048
4292
 
4049
- if(typeof require == 'function'){
4050
- exports.XMLReader = XMLReader;
4051
- }
4293
+ exports.XMLReader = XMLReader;
4052
4294
 
4053
4295
 
4054
4296
  },{}]},{},[1])(1)
4055
- });
4297
+ });