plist 2.0.1 → 3.0.2

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){
2
- (function (Buffer){
3
-
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 r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2
+ (function (Buffer){(function (){
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') {
@@ -201,401 +216,503 @@ function parsePlistXML (node) {
201
216
  }
202
217
  }
203
218
 
204
- }).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
- }
240
-
241
- function b64ToByteArray (b64) {
242
- var i, j, l, tmp, placeHolders, arr
243
-
244
- if (b64.length % 4 > 0) {
245
- throw new Error('Invalid string. Length must be a multiple of 4')
246
- }
219
+ }).call(this)}).call(this,require("buffer").Buffer)
220
+ },{"buffer":3,"xmldom":5}],2:[function(require,module,exports){
221
+ 'use strict'
247
222
 
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
223
+ exports.byteLength = byteLength
224
+ exports.toByteArray = toByteArray
225
+ exports.fromByteArray = fromByteArray
255
226
 
256
- // base64 is 4/3 + up to two characters of the original data
257
- arr = new Arr(b64.length * 3 / 4 - placeHolders)
227
+ var lookup = []
228
+ var revLookup = []
229
+ var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
258
230
 
259
- // if there are placeholders, only get up to the last complete 4 chars
260
- l = placeHolders > 0 ? b64.length - 4 : b64.length
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
+ }
261
236
 
262
- var L = 0
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
263
241
 
264
- function push (v) {
265
- arr[L++] = v
266
- }
242
+ function getLens (b64) {
243
+ var len = b64.length
267
244
 
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
- }
245
+ if (len % 4 > 0) {
246
+ throw new Error('Invalid string. Length must be a multiple of 4')
247
+ }
274
248
 
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
- }
249
+ // Trim off extra bytes after placeholder bytes are found
250
+ // See: https://github.com/beatgammit/base64-js/issues/42
251
+ var validLen = b64.indexOf('=')
252
+ if (validLen === -1) validLen = len
283
253
 
284
- return arr
285
- }
254
+ var placeHoldersLen = validLen === len
255
+ ? 0
256
+ : 4 - (validLen % 4)
286
257
 
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
258
+ return [validLen, placeHoldersLen]
259
+ }
292
260
 
293
- function encode (num) {
294
- return lookup.charAt(num)
295
- }
261
+ // base64 is 4/3 + up to two characters of the original data
262
+ function byteLength (b64) {
263
+ var lens = getLens(b64)
264
+ var validLen = lens[0]
265
+ var placeHoldersLen = lens[1]
266
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
267
+ }
296
268
 
297
- function tripletToBase64 (num) {
298
- return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
299
- }
269
+ function _byteLength (b64, validLen, placeHoldersLen) {
270
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
271
+ }
300
272
 
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
- }
273
+ function toByteArray (b64) {
274
+ var tmp
275
+ var lens = getLens(b64)
276
+ var validLen = lens[0]
277
+ var placeHoldersLen = lens[1]
306
278
 
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
- }
279
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
323
280
 
324
- return output
325
- }
281
+ var curByte = 0
282
+
283
+ // if there are placeholders, only get up to the last complete 4 chars
284
+ var len = placeHoldersLen > 0
285
+ ? validLen - 4
286
+ : validLen
326
287
 
327
- exports.toByteArray = b64ToByteArray
328
- exports.fromByteArray = uint8ToBase64
329
- }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
288
+ var i
289
+ for (i = 0; i < len; i += 4) {
290
+ tmp =
291
+ (revLookup[b64.charCodeAt(i)] << 18) |
292
+ (revLookup[b64.charCodeAt(i + 1)] << 12) |
293
+ (revLookup[b64.charCodeAt(i + 2)] << 6) |
294
+ revLookup[b64.charCodeAt(i + 3)]
295
+ arr[curByte++] = (tmp >> 16) & 0xFF
296
+ arr[curByte++] = (tmp >> 8) & 0xFF
297
+ arr[curByte++] = tmp & 0xFF
298
+ }
299
+
300
+ if (placeHoldersLen === 2) {
301
+ tmp =
302
+ (revLookup[b64.charCodeAt(i)] << 2) |
303
+ (revLookup[b64.charCodeAt(i + 1)] >> 4)
304
+ arr[curByte++] = tmp & 0xFF
305
+ }
306
+
307
+ if (placeHoldersLen === 1) {
308
+ tmp =
309
+ (revLookup[b64.charCodeAt(i)] << 10) |
310
+ (revLookup[b64.charCodeAt(i + 1)] << 4) |
311
+ (revLookup[b64.charCodeAt(i + 2)] >> 2)
312
+ arr[curByte++] = (tmp >> 8) & 0xFF
313
+ arr[curByte++] = tmp & 0xFF
314
+ }
315
+
316
+ return arr
317
+ }
318
+
319
+ function tripletToBase64 (num) {
320
+ return lookup[num >> 18 & 0x3F] +
321
+ lookup[num >> 12 & 0x3F] +
322
+ lookup[num >> 6 & 0x3F] +
323
+ lookup[num & 0x3F]
324
+ }
325
+
326
+ function encodeChunk (uint8, start, end) {
327
+ var tmp
328
+ var output = []
329
+ for (var i = start; i < end; i += 3) {
330
+ tmp =
331
+ ((uint8[i] << 16) & 0xFF0000) +
332
+ ((uint8[i + 1] << 8) & 0xFF00) +
333
+ (uint8[i + 2] & 0xFF)
334
+ output.push(tripletToBase64(tmp))
335
+ }
336
+ return output.join('')
337
+ }
338
+
339
+ function fromByteArray (uint8) {
340
+ var tmp
341
+ var len = uint8.length
342
+ var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
343
+ var parts = []
344
+ var maxChunkLength = 16383 // must be multiple of 3
345
+
346
+ // go through the array every three bytes, we'll deal with trailing stuff later
347
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
348
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
349
+ }
350
+
351
+ // pad the end with zeros, but make sure to not forget the extra bytes
352
+ if (extraBytes === 1) {
353
+ tmp = uint8[len - 1]
354
+ parts.push(
355
+ lookup[tmp >> 2] +
356
+ lookup[(tmp << 4) & 0x3F] +
357
+ '=='
358
+ )
359
+ } else if (extraBytes === 2) {
360
+ tmp = (uint8[len - 2] << 8) + uint8[len - 1]
361
+ parts.push(
362
+ lookup[tmp >> 10] +
363
+ lookup[(tmp >> 4) & 0x3F] +
364
+ lookup[(tmp << 2) & 0x3F] +
365
+ '='
366
+ )
367
+ }
368
+
369
+ return parts.join('')
370
+ }
330
371
 
331
372
  },{}],3:[function(require,module,exports){
332
- (function (global){
373
+ (function (Buffer){(function (){
333
374
  /*!
334
375
  * The buffer module from node.js, for the browser.
335
376
  *
336
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
377
+ * @author Feross Aboukhadijeh <https://feross.org>
337
378
  * @license MIT
338
379
  */
339
380
  /* eslint-disable no-proto */
340
381
 
382
+ 'use strict'
383
+
341
384
  var base64 = require('base64-js')
342
385
  var ieee754 = require('ieee754')
343
- var isArray = require('is-array')
344
386
 
345
387
  exports.Buffer = Buffer
346
388
  exports.SlowBuffer = SlowBuffer
347
389
  exports.INSPECT_MAX_BYTES = 50
348
- Buffer.poolSize = 8192 // not used by this implementation
349
390
 
350
- var rootParent = {}
391
+ var K_MAX_LENGTH = 0x7fffffff
392
+ exports.kMaxLength = K_MAX_LENGTH
351
393
 
352
394
  /**
353
395
  * If `Buffer.TYPED_ARRAY_SUPPORT`:
354
396
  * === true Use Uint8Array implementation (fastest)
355
- * === false Use Object implementation (most compatible, even IE6)
397
+ * === false Print warning and recommend using `buffer` v4.x which has an Object
398
+ * implementation (most compatible, even IE6)
356
399
  *
357
400
  * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
358
401
  * Opera 11.6+, iOS 4.2+.
359
402
  *
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.
403
+ * We report that the browser does not support typed arrays if the are not subclassable
404
+ * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
405
+ * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
406
+ * for __proto__ and has a buggy typed array implementation.
378
407
  */
379
- Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
380
- ? global.TYPED_ARRAY_SUPPORT
381
- : typedArraySupport()
408
+ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
409
+
410
+ if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
411
+ typeof console.error === 'function') {
412
+ console.error(
413
+ 'This browser lacks typed array (Uint8Array) support which is required by ' +
414
+ '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
415
+ )
416
+ }
382
417
 
383
418
  function typedArraySupport () {
384
- function Bar () {}
419
+ // Can typed array instances can be augmented?
385
420
  try {
386
421
  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`
422
+ arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
423
+ return arr.foo() === 42
393
424
  } catch (e) {
394
425
  return false
395
426
  }
396
427
  }
397
428
 
398
- function kMaxLength () {
399
- return Buffer.TYPED_ARRAY_SUPPORT
400
- ? 0x7fffffff
401
- : 0x3fffffff
429
+ Object.defineProperty(Buffer.prototype, 'parent', {
430
+ enumerable: true,
431
+ get: function () {
432
+ if (!Buffer.isBuffer(this)) return undefined
433
+ return this.buffer
434
+ }
435
+ })
436
+
437
+ Object.defineProperty(Buffer.prototype, 'offset', {
438
+ enumerable: true,
439
+ get: function () {
440
+ if (!Buffer.isBuffer(this)) return undefined
441
+ return this.byteOffset
442
+ }
443
+ })
444
+
445
+ function createBuffer (length) {
446
+ if (length > K_MAX_LENGTH) {
447
+ throw new RangeError('The value "' + length + '" is invalid for option "size"')
448
+ }
449
+ // Return an augmented `Uint8Array` instance
450
+ var buf = new Uint8Array(length)
451
+ buf.__proto__ = Buffer.prototype
452
+ return buf
402
453
  }
403
454
 
404
455
  /**
405
- * Class: Buffer
406
- * =============
407
- *
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.
456
+ * The Buffer constructor returns instances of `Uint8Array` that have their
457
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
458
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
459
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
460
+ * returns a single octet.
412
461
  *
413
- * By augmenting the instances, we can avoid modifying the `Uint8Array`
414
- * prototype.
462
+ * The `Uint8Array` prototype remains unmodified.
415
463
  */
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
464
 
465
+ function Buffer (arg, encodingOrOffset, length) {
426
466
  // Common case.
427
467
  if (typeof arg === 'number') {
428
- return fromNumber(this, arg)
468
+ if (typeof encodingOrOffset === 'string') {
469
+ throw new TypeError(
470
+ 'The "string" argument must be of type string. Received type number'
471
+ )
472
+ }
473
+ return allocUnsafe(arg)
429
474
  }
475
+ return from(arg, encodingOrOffset, length)
476
+ }
430
477
 
431
- // Slightly less common case.
432
- if (typeof arg === 'string') {
433
- return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
478
+ // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
479
+ if (typeof Symbol !== 'undefined' && Symbol.species != null &&
480
+ Buffer[Symbol.species] === Buffer) {
481
+ Object.defineProperty(Buffer, Symbol.species, {
482
+ value: null,
483
+ configurable: true,
484
+ enumerable: false,
485
+ writable: false
486
+ })
487
+ }
488
+
489
+ Buffer.poolSize = 8192 // not used by this implementation
490
+
491
+ function from (value, encodingOrOffset, length) {
492
+ if (typeof value === 'string') {
493
+ return fromString(value, encodingOrOffset)
434
494
  }
435
495
 
436
- // Unusual.
437
- return fromObject(this, arg)
438
- }
496
+ if (ArrayBuffer.isView(value)) {
497
+ return fromArrayLike(value)
498
+ }
439
499
 
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
- }
500
+ if (value == null) {
501
+ throw TypeError(
502
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
503
+ 'or Array-like Object. Received type ' + (typeof value)
504
+ )
446
505
  }
447
- return that
448
- }
449
506
 
450
- function fromString (that, string, encoding) {
451
- if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
507
+ if (isInstance(value, ArrayBuffer) ||
508
+ (value && isInstance(value.buffer, ArrayBuffer))) {
509
+ return fromArrayBuffer(value, encodingOrOffset, length)
510
+ }
452
511
 
453
- // Assumption: byteLength() return value is always < kMaxLength.
454
- var length = byteLength(string, encoding) | 0
455
- that = allocate(that, length)
512
+ if (typeof value === 'number') {
513
+ throw new TypeError(
514
+ 'The "value" argument must not be of type number. Received type number'
515
+ )
516
+ }
456
517
 
457
- that.write(string, encoding)
458
- return that
459
- }
518
+ var valueOf = value.valueOf && value.valueOf()
519
+ if (valueOf != null && valueOf !== value) {
520
+ return Buffer.from(valueOf, encodingOrOffset, length)
521
+ }
460
522
 
461
- function fromObject (that, object) {
462
- if (Buffer.isBuffer(object)) return fromBuffer(that, object)
523
+ var b = fromObject(value)
524
+ if (b) return b
463
525
 
464
- if (isArray(object)) return fromArray(that, object)
526
+ if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
527
+ typeof value[Symbol.toPrimitive] === 'function') {
528
+ return Buffer.from(
529
+ value[Symbol.toPrimitive]('string'), encodingOrOffset, length
530
+ )
531
+ }
532
+
533
+ throw new TypeError(
534
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
535
+ 'or Array-like Object. Received type ' + (typeof value)
536
+ )
537
+ }
465
538
 
466
- if (object == null) {
467
- throw new TypeError('must start with number, buffer, array or string')
539
+ /**
540
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
541
+ * if value is a number.
542
+ * Buffer.from(str[, encoding])
543
+ * Buffer.from(array)
544
+ * Buffer.from(buffer)
545
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
546
+ **/
547
+ Buffer.from = function (value, encodingOrOffset, length) {
548
+ return from(value, encodingOrOffset, length)
549
+ }
550
+
551
+ // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
552
+ // https://github.com/feross/buffer/pull/148
553
+ Buffer.prototype.__proto__ = Uint8Array.prototype
554
+ Buffer.__proto__ = Uint8Array
555
+
556
+ function assertSize (size) {
557
+ if (typeof size !== 'number') {
558
+ throw new TypeError('"size" argument must be of type number')
559
+ } else if (size < 0) {
560
+ throw new RangeError('The value "' + size + '" is invalid for option "size"')
468
561
  }
562
+ }
469
563
 
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
- }
564
+ function alloc (size, fill, encoding) {
565
+ assertSize(size)
566
+ if (size <= 0) {
567
+ return createBuffer(size)
568
+ }
569
+ if (fill !== undefined) {
570
+ // Only pay attention to encoding if it's a string. This
571
+ // prevents accidentally sending in a number that would
572
+ // be interpretted as a start offset.
573
+ return typeof encoding === 'string'
574
+ ? createBuffer(size).fill(fill, encoding)
575
+ : createBuffer(size).fill(fill)
477
576
  }
577
+ return createBuffer(size)
578
+ }
478
579
 
479
- if (object.length) return fromArrayLike(that, object)
580
+ /**
581
+ * Creates a new filled Buffer instance.
582
+ * alloc(size[, fill[, encoding]])
583
+ **/
584
+ Buffer.alloc = function (size, fill, encoding) {
585
+ return alloc(size, fill, encoding)
586
+ }
480
587
 
481
- return fromJsonObject(that, object)
588
+ function allocUnsafe (size) {
589
+ assertSize(size)
590
+ return createBuffer(size < 0 ? 0 : checked(size) | 0)
482
591
  }
483
592
 
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
593
+ /**
594
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
595
+ * */
596
+ Buffer.allocUnsafe = function (size) {
597
+ return allocUnsafe(size)
598
+ }
599
+ /**
600
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
601
+ */
602
+ Buffer.allocUnsafeSlow = function (size) {
603
+ return allocUnsafe(size)
489
604
  }
490
605
 
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
606
+ function fromString (string, encoding) {
607
+ if (typeof encoding !== 'string' || encoding === '') {
608
+ encoding = 'utf8'
496
609
  }
497
- return that
498
- }
499
610
 
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
611
+ if (!Buffer.isEncoding(encoding)) {
612
+ throw new TypeError('Unknown encoding: ' + encoding)
509
613
  }
510
- return that
511
- }
512
614
 
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))
615
+ var length = byteLength(string, encoding) | 0
616
+ var buf = createBuffer(length)
617
+
618
+ var actual = buf.write(string, encoding)
619
+
620
+ if (actual !== length) {
621
+ // Writing a hex string, for example, that contains invalid characters will
622
+ // cause everything after the first invalid character to be ignored. (e.g.
623
+ // 'abxxcd' will be treated as 'ab')
624
+ buf = buf.slice(0, actual)
521
625
  }
522
- return that
626
+
627
+ return buf
523
628
  }
524
629
 
525
- function fromArrayLike (that, array) {
526
- var length = checked(array.length) | 0
527
- that = allocate(that, length)
630
+ function fromArrayLike (array) {
631
+ var length = array.length < 0 ? 0 : checked(array.length) | 0
632
+ var buf = createBuffer(length)
528
633
  for (var i = 0; i < length; i += 1) {
529
- that[i] = array[i] & 255
634
+ buf[i] = array[i] & 255
530
635
  }
531
- return that
636
+ return buf
532
637
  }
533
638
 
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
639
+ function fromArrayBuffer (array, byteOffset, length) {
640
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
641
+ throw new RangeError('"offset" is outside of buffer bounds')
642
+ }
539
643
 
540
- if (object.type === 'Buffer' && isArray(object.data)) {
541
- array = object.data
542
- length = checked(array.length) | 0
644
+ if (array.byteLength < byteOffset + (length || 0)) {
645
+ throw new RangeError('"length" is outside of buffer bounds')
543
646
  }
544
- that = allocate(that, length)
545
647
 
546
- for (var i = 0; i < length; i += 1) {
547
- that[i] = array[i] & 255
648
+ var buf
649
+ if (byteOffset === undefined && length === undefined) {
650
+ buf = new Uint8Array(array)
651
+ } else if (length === undefined) {
652
+ buf = new Uint8Array(array, byteOffset)
653
+ } else {
654
+ buf = new Uint8Array(array, byteOffset, length)
548
655
  }
549
- return that
550
- }
551
656
 
552
- if (Buffer.TYPED_ARRAY_SUPPORT) {
553
- Buffer.prototype.__proto__ = Uint8Array.prototype
554
- Buffer.__proto__ = Uint8Array
657
+ // Return an augmented `Uint8Array` instance
658
+ buf.__proto__ = Buffer.prototype
659
+ return buf
555
660
  }
556
661
 
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
662
+ function fromObject (obj) {
663
+ if (Buffer.isBuffer(obj)) {
664
+ var len = checked(obj.length) | 0
665
+ var buf = createBuffer(len)
666
+
667
+ if (buf.length === 0) {
668
+ return buf
669
+ }
670
+
671
+ obj.copy(buf, 0, 0, len)
672
+ return buf
566
673
  }
567
674
 
568
- var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
569
- if (fromPool) that.parent = rootParent
675
+ if (obj.length !== undefined) {
676
+ if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
677
+ return createBuffer(0)
678
+ }
679
+ return fromArrayLike(obj)
680
+ }
570
681
 
571
- return that
682
+ if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
683
+ return fromArrayLike(obj.data)
684
+ }
572
685
  }
573
686
 
574
687
  function checked (length) {
575
- // Note: cannot use `length < kMaxLength` here because that fails when
688
+ // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
576
689
  // length is NaN (which is otherwise coerced to zero.)
577
- if (length >= kMaxLength()) {
690
+ if (length >= K_MAX_LENGTH) {
578
691
  throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
579
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
692
+ 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
580
693
  }
581
694
  return length | 0
582
695
  }
583
696
 
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
697
+ function SlowBuffer (length) {
698
+ if (+length != length) { // eslint-disable-line eqeqeq
699
+ length = 0
700
+ }
701
+ return Buffer.alloc(+length)
590
702
  }
591
703
 
592
704
  Buffer.isBuffer = function isBuffer (b) {
593
- return !!(b != null && b._isBuffer)
705
+ return b != null && b._isBuffer === true &&
706
+ b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
594
707
  }
595
708
 
596
709
  Buffer.compare = function compare (a, b) {
710
+ if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
711
+ if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
597
712
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
598
- throw new TypeError('Arguments must be Buffers')
713
+ throw new TypeError(
714
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
715
+ )
599
716
  }
600
717
 
601
718
  if (a === b) return 0
@@ -603,17 +720,12 @@ Buffer.compare = function compare (a, b) {
603
720
  var x = a.length
604
721
  var y = b.length
605
722
 
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]
723
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
724
+ if (a[i] !== b[i]) {
725
+ x = a[i]
726
+ y = b[i]
727
+ break
728
+ }
617
729
  }
618
730
 
619
731
  if (x < y) return -1
@@ -627,9 +739,9 @@ Buffer.isEncoding = function isEncoding (encoding) {
627
739
  case 'utf8':
628
740
  case 'utf-8':
629
741
  case 'ascii':
742
+ case 'latin1':
630
743
  case 'binary':
631
744
  case 'base64':
632
- case 'raw':
633
745
  case 'ucs2':
634
746
  case 'ucs-2':
635
747
  case 'utf16le':
@@ -641,45 +753,63 @@ Buffer.isEncoding = function isEncoding (encoding) {
641
753
  }
642
754
 
643
755
  Buffer.concat = function concat (list, length) {
644
- if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
756
+ if (!Array.isArray(list)) {
757
+ throw new TypeError('"list" argument must be an Array of Buffers')
758
+ }
645
759
 
646
760
  if (list.length === 0) {
647
- return new Buffer(0)
761
+ return Buffer.alloc(0)
648
762
  }
649
763
 
650
764
  var i
651
765
  if (length === undefined) {
652
766
  length = 0
653
- for (i = 0; i < list.length; i++) {
767
+ for (i = 0; i < list.length; ++i) {
654
768
  length += list[i].length
655
769
  }
656
770
  }
657
771
 
658
- var buf = new Buffer(length)
772
+ var buffer = Buffer.allocUnsafe(length)
659
773
  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
774
+ for (i = 0; i < list.length; ++i) {
775
+ var buf = list[i]
776
+ if (isInstance(buf, Uint8Array)) {
777
+ buf = Buffer.from(buf)
778
+ }
779
+ if (!Buffer.isBuffer(buf)) {
780
+ throw new TypeError('"list" argument must be an Array of Buffers')
781
+ }
782
+ buf.copy(buffer, pos)
783
+ pos += buf.length
664
784
  }
665
- return buf
785
+ return buffer
666
786
  }
667
787
 
668
788
  function byteLength (string, encoding) {
669
- if (typeof string !== 'string') string = '' + string
789
+ if (Buffer.isBuffer(string)) {
790
+ return string.length
791
+ }
792
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
793
+ return string.byteLength
794
+ }
795
+ if (typeof string !== 'string') {
796
+ throw new TypeError(
797
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
798
+ 'Received type ' + typeof string
799
+ )
800
+ }
670
801
 
671
802
  var len = string.length
672
- if (len === 0) return 0
803
+ var mustMatch = (arguments.length > 2 && arguments[2] === true)
804
+ if (!mustMatch && len === 0) return 0
673
805
 
674
806
  // Use a for loop to avoid recursion
675
807
  var loweredCase = false
676
808
  for (;;) {
677
809
  switch (encoding) {
678
810
  case 'ascii':
811
+ case 'latin1':
679
812
  case 'binary':
680
- // Deprecated
681
- case 'raw':
682
- case 'raws':
683
813
  return len
684
814
  case 'utf8':
685
815
  case 'utf-8':
@@ -694,7 +824,9 @@ function byteLength (string, encoding) {
694
824
  case 'base64':
695
825
  return base64ToBytes(string).length
696
826
  default:
697
- if (loweredCase) return utf8ToBytes(string).length // assume utf8
827
+ if (loweredCase) {
828
+ return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
829
+ }
698
830
  encoding = ('' + encoding).toLowerCase()
699
831
  loweredCase = true
700
832
  }
@@ -702,20 +834,42 @@ function byteLength (string, encoding) {
702
834
  }
703
835
  Buffer.byteLength = byteLength
704
836
 
705
- // pre-set for values that may exist in the future
706
- Buffer.prototype.length = undefined
707
- Buffer.prototype.parent = undefined
708
-
709
837
  function slowToString (encoding, start, end) {
710
838
  var loweredCase = false
711
839
 
712
- start = start | 0
713
- end = end === undefined || end === Infinity ? this.length : end | 0
840
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
841
+ // property of a typed array.
842
+
843
+ // This behaves neither like String nor Uint8Array in that we set start/end
844
+ // to their upper/lower bounds if the value passed is out of range.
845
+ // undefined is handled specially as per ECMA-262 6th Edition,
846
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
847
+ if (start === undefined || start < 0) {
848
+ start = 0
849
+ }
850
+ // Return early if start > this.length. Done here to prevent potential uint32
851
+ // coercion fail below.
852
+ if (start > this.length) {
853
+ return ''
854
+ }
855
+
856
+ if (end === undefined || end > this.length) {
857
+ end = this.length
858
+ }
859
+
860
+ if (end <= 0) {
861
+ return ''
862
+ }
863
+
864
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
865
+ end >>>= 0
866
+ start >>>= 0
867
+
868
+ if (end <= start) {
869
+ return ''
870
+ }
714
871
 
715
872
  if (!encoding) encoding = 'utf8'
716
- if (start < 0) start = 0
717
- if (end > this.length) end = this.length
718
- if (end <= start) return ''
719
873
 
720
874
  while (true) {
721
875
  switch (encoding) {
@@ -729,8 +883,9 @@ function slowToString (encoding, start, end) {
729
883
  case 'ascii':
730
884
  return asciiSlice(this, start, end)
731
885
 
886
+ case 'latin1':
732
887
  case 'binary':
733
- return binarySlice(this, start, end)
888
+ return latin1Slice(this, start, end)
734
889
 
735
890
  case 'base64':
736
891
  return base64Slice(this, start, end)
@@ -749,13 +904,66 @@ function slowToString (encoding, start, end) {
749
904
  }
750
905
  }
751
906
 
907
+ // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
908
+ // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
909
+ // reliably in a browserify context because there could be multiple different
910
+ // copies of the 'buffer' package in use. This method works even for Buffer
911
+ // instances that were created from another copy of the `buffer` package.
912
+ // See: https://github.com/feross/buffer/issues/154
913
+ Buffer.prototype._isBuffer = true
914
+
915
+ function swap (b, n, m) {
916
+ var i = b[n]
917
+ b[n] = b[m]
918
+ b[m] = i
919
+ }
920
+
921
+ Buffer.prototype.swap16 = function swap16 () {
922
+ var len = this.length
923
+ if (len % 2 !== 0) {
924
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
925
+ }
926
+ for (var i = 0; i < len; i += 2) {
927
+ swap(this, i, i + 1)
928
+ }
929
+ return this
930
+ }
931
+
932
+ Buffer.prototype.swap32 = function swap32 () {
933
+ var len = this.length
934
+ if (len % 4 !== 0) {
935
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
936
+ }
937
+ for (var i = 0; i < len; i += 4) {
938
+ swap(this, i, i + 3)
939
+ swap(this, i + 1, i + 2)
940
+ }
941
+ return this
942
+ }
943
+
944
+ Buffer.prototype.swap64 = function swap64 () {
945
+ var len = this.length
946
+ if (len % 8 !== 0) {
947
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
948
+ }
949
+ for (var i = 0; i < len; i += 8) {
950
+ swap(this, i, i + 7)
951
+ swap(this, i + 1, i + 6)
952
+ swap(this, i + 2, i + 5)
953
+ swap(this, i + 3, i + 4)
954
+ }
955
+ return this
956
+ }
957
+
752
958
  Buffer.prototype.toString = function toString () {
753
- var length = this.length | 0
959
+ var length = this.length
754
960
  if (length === 0) return ''
755
961
  if (arguments.length === 0) return utf8Slice(this, 0, length)
756
962
  return slowToString.apply(this, arguments)
757
963
  }
758
964
 
965
+ Buffer.prototype.toLocaleString = Buffer.prototype.toString
966
+
759
967
  Buffer.prototype.equals = function equals (b) {
760
968
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
761
969
  if (this === b) return true
@@ -765,70 +973,207 @@ Buffer.prototype.equals = function equals (b) {
765
973
  Buffer.prototype.inspect = function inspect () {
766
974
  var str = ''
767
975
  var max = exports.INSPECT_MAX_BYTES
768
- if (this.length > 0) {
769
- str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
770
- if (this.length > max) str += ' ... '
771
- }
976
+ str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
977
+ if (this.length > max) str += ' ... '
772
978
  return '<Buffer ' + str + '>'
773
979
  }
774
980
 
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
- }
981
+ Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
982
+ if (isInstance(target, Uint8Array)) {
983
+ target = Buffer.from(target, target.offset, target.byteLength)
984
+ }
985
+ if (!Buffer.isBuffer(target)) {
986
+ throw new TypeError(
987
+ 'The "target" argument must be one of type Buffer or Uint8Array. ' +
988
+ 'Received type ' + (typeof target)
989
+ )
990
+ }
991
+
992
+ if (start === undefined) {
993
+ start = 0
994
+ }
995
+ if (end === undefined) {
996
+ end = target ? target.length : 0
997
+ }
998
+ if (thisStart === undefined) {
999
+ thisStart = 0
1000
+ }
1001
+ if (thisEnd === undefined) {
1002
+ thisEnd = this.length
1003
+ }
1004
+
1005
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1006
+ throw new RangeError('out of range index')
1007
+ }
1008
+
1009
+ if (thisStart >= thisEnd && start >= end) {
1010
+ return 0
1011
+ }
1012
+ if (thisStart >= thisEnd) {
1013
+ return -1
1014
+ }
1015
+ if (start >= end) {
1016
+ return 1
1017
+ }
1018
+
1019
+ start >>>= 0
1020
+ end >>>= 0
1021
+ thisStart >>>= 0
1022
+ thisEnd >>>= 0
1023
+
1024
+ if (this === target) return 0
1025
+
1026
+ var x = thisEnd - thisStart
1027
+ var y = end - start
1028
+ var len = Math.min(x, y)
1029
+
1030
+ var thisCopy = this.slice(thisStart, thisEnd)
1031
+ var targetCopy = target.slice(start, end)
1032
+
1033
+ for (var i = 0; i < len; ++i) {
1034
+ if (thisCopy[i] !== targetCopy[i]) {
1035
+ x = thisCopy[i]
1036
+ y = targetCopy[i]
1037
+ break
1038
+ }
1039
+ }
780
1040
 
781
- Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
782
- if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
783
- else if (byteOffset < -0x80000000) byteOffset = -0x80000000
784
- byteOffset >>= 0
1041
+ if (x < y) return -1
1042
+ if (y < x) return 1
1043
+ return 0
1044
+ }
785
1045
 
786
- if (this.length === 0) return -1
787
- if (byteOffset >= this.length) return -1
1046
+ // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1047
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1048
+ //
1049
+ // Arguments:
1050
+ // - buffer - a Buffer to search
1051
+ // - val - a string, Buffer, or number
1052
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
1053
+ // - encoding - an optional encoding, relevant is val is a string
1054
+ // - dir - true for indexOf, false for lastIndexOf
1055
+ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1056
+ // Empty buffer means no match
1057
+ if (buffer.length === 0) return -1
1058
+
1059
+ // Normalize byteOffset
1060
+ if (typeof byteOffset === 'string') {
1061
+ encoding = byteOffset
1062
+ byteOffset = 0
1063
+ } else if (byteOffset > 0x7fffffff) {
1064
+ byteOffset = 0x7fffffff
1065
+ } else if (byteOffset < -0x80000000) {
1066
+ byteOffset = -0x80000000
1067
+ }
1068
+ byteOffset = +byteOffset // Coerce to Number.
1069
+ if (numberIsNaN(byteOffset)) {
1070
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1071
+ byteOffset = dir ? 0 : (buffer.length - 1)
1072
+ }
788
1073
 
789
- // Negative offsets start from the end of the buffer
790
- if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
1074
+ // Normalize byteOffset: negative offsets start from the end of the buffer
1075
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1076
+ if (byteOffset >= buffer.length) {
1077
+ if (dir) return -1
1078
+ else byteOffset = buffer.length - 1
1079
+ } else if (byteOffset < 0) {
1080
+ if (dir) byteOffset = 0
1081
+ else return -1
1082
+ }
791
1083
 
1084
+ // Normalize val
792
1085
  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)
1086
+ val = Buffer.from(val, encoding)
795
1087
  }
1088
+
1089
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
796
1090
  if (Buffer.isBuffer(val)) {
797
- return arrayIndexOf(this, val, byteOffset)
1091
+ // Special case: looking for empty string/buffer always fails
1092
+ if (val.length === 0) {
1093
+ return -1
1094
+ }
1095
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1096
+ } else if (typeof val === 'number') {
1097
+ val = val & 0xFF // Search for a byte value [0-255]
1098
+ if (typeof Uint8Array.prototype.indexOf === 'function') {
1099
+ if (dir) {
1100
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1101
+ } else {
1102
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1103
+ }
1104
+ }
1105
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
798
1106
  }
799
- if (typeof val === 'number') {
800
- if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
801
- return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
1107
+
1108
+ throw new TypeError('val must be string, number or Buffer')
1109
+ }
1110
+
1111
+ function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1112
+ var indexSize = 1
1113
+ var arrLength = arr.length
1114
+ var valLength = val.length
1115
+
1116
+ if (encoding !== undefined) {
1117
+ encoding = String(encoding).toLowerCase()
1118
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1119
+ encoding === 'utf16le' || encoding === 'utf-16le') {
1120
+ if (arr.length < 2 || val.length < 2) {
1121
+ return -1
1122
+ }
1123
+ indexSize = 2
1124
+ arrLength /= 2
1125
+ valLength /= 2
1126
+ byteOffset /= 2
1127
+ }
1128
+ }
1129
+
1130
+ function read (buf, i) {
1131
+ if (indexSize === 1) {
1132
+ return buf[i]
1133
+ } else {
1134
+ return buf.readUInt16BE(i * indexSize)
802
1135
  }
803
- return arrayIndexOf(this, [ val ], byteOffset)
804
1136
  }
805
1137
 
806
- function arrayIndexOf (arr, val, byteOffset) {
1138
+ var i
1139
+ if (dir) {
807
1140
  var foundIndex = -1
808
- for (var i = 0; byteOffset + i < arr.length; i++) {
809
- if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
1141
+ for (i = byteOffset; i < arrLength; i++) {
1142
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
810
1143
  if (foundIndex === -1) foundIndex = i
811
- if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
1144
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
812
1145
  } else {
1146
+ if (foundIndex !== -1) i -= i - foundIndex
813
1147
  foundIndex = -1
814
1148
  }
815
1149
  }
816
- return -1
1150
+ } else {
1151
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1152
+ for (i = byteOffset; i >= 0; i--) {
1153
+ var found = true
1154
+ for (var j = 0; j < valLength; j++) {
1155
+ if (read(arr, i + j) !== read(val, j)) {
1156
+ found = false
1157
+ break
1158
+ }
1159
+ }
1160
+ if (found) return i
1161
+ }
817
1162
  }
818
1163
 
819
- throw new TypeError('val must be string, number or Buffer')
1164
+ return -1
1165
+ }
1166
+
1167
+ Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1168
+ return this.indexOf(val, byteOffset, encoding) !== -1
820
1169
  }
821
1170
 
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)
1171
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1172
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
826
1173
  }
827
1174
 
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)
1175
+ Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1176
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
832
1177
  }
833
1178
 
834
1179
  function hexWrite (buf, string, offset, length) {
@@ -843,16 +1188,14 @@ function hexWrite (buf, string, offset, length) {
843
1188
  }
844
1189
  }
845
1190
 
846
- // must be an even number of digits
847
1191
  var strLen = string.length
848
- if (strLen % 2 !== 0) throw new Error('Invalid hex string')
849
1192
 
850
1193
  if (length > strLen / 2) {
851
1194
  length = strLen / 2
852
1195
  }
853
- for (var i = 0; i < length; i++) {
1196
+ for (var i = 0; i < length; ++i) {
854
1197
  var parsed = parseInt(string.substr(i * 2, 2), 16)
855
- if (isNaN(parsed)) throw new Error('Invalid hex string')
1198
+ if (numberIsNaN(parsed)) return i
856
1199
  buf[offset + i] = parsed
857
1200
  }
858
1201
  return i
@@ -866,7 +1209,7 @@ function asciiWrite (buf, string, offset, length) {
866
1209
  return blitBuffer(asciiToBytes(string), buf, offset, length)
867
1210
  }
868
1211
 
869
- function binaryWrite (buf, string, offset, length) {
1212
+ function latin1Write (buf, string, offset, length) {
870
1213
  return asciiWrite(buf, string, offset, length)
871
1214
  }
872
1215
 
@@ -891,27 +1234,25 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
891
1234
  offset = 0
892
1235
  // Buffer#write(string, offset[, length][, encoding])
893
1236
  } else if (isFinite(offset)) {
894
- offset = offset | 0
1237
+ offset = offset >>> 0
895
1238
  if (isFinite(length)) {
896
- length = length | 0
1239
+ length = length >>> 0
897
1240
  if (encoding === undefined) encoding = 'utf8'
898
1241
  } else {
899
1242
  encoding = length
900
1243
  length = undefined
901
1244
  }
902
- // legacy write(string, encoding, offset, length) - remove in v0.13
903
1245
  } else {
904
- var swap = encoding
905
- encoding = offset
906
- offset = length | 0
907
- length = swap
1246
+ throw new Error(
1247
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1248
+ )
908
1249
  }
909
1250
 
910
1251
  var remaining = this.length - offset
911
1252
  if (length === undefined || length > remaining) length = remaining
912
1253
 
913
1254
  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
914
- throw new RangeError('attempt to write outside buffer bounds')
1255
+ throw new RangeError('Attempt to write outside buffer bounds')
915
1256
  }
916
1257
 
917
1258
  if (!encoding) encoding = 'utf8'
@@ -929,8 +1270,9 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
929
1270
  case 'ascii':
930
1271
  return asciiWrite(this, string, offset, length)
931
1272
 
1273
+ case 'latin1':
932
1274
  case 'binary':
933
- return binaryWrite(this, string, offset, length)
1275
+ return latin1Write(this, string, offset, length)
934
1276
 
935
1277
  case 'base64':
936
1278
  // Warning: maxLength not taken into account in base64Write
@@ -975,8 +1317,8 @@ function utf8Slice (buf, start, end) {
975
1317
  var codePoint = null
976
1318
  var bytesPerSequence = (firstByte > 0xEF) ? 4
977
1319
  : (firstByte > 0xDF) ? 3
978
- : (firstByte > 0xBF) ? 2
979
- : 1
1320
+ : (firstByte > 0xBF) ? 2
1321
+ : 1
980
1322
 
981
1323
  if (i + bytesPerSequence <= end) {
982
1324
  var secondByte, thirdByte, fourthByte, tempCodePoint
@@ -1065,17 +1407,17 @@ function asciiSlice (buf, start, end) {
1065
1407
  var ret = ''
1066
1408
  end = Math.min(buf.length, end)
1067
1409
 
1068
- for (var i = start; i < end; i++) {
1410
+ for (var i = start; i < end; ++i) {
1069
1411
  ret += String.fromCharCode(buf[i] & 0x7F)
1070
1412
  }
1071
1413
  return ret
1072
1414
  }
1073
1415
 
1074
- function binarySlice (buf, start, end) {
1416
+ function latin1Slice (buf, start, end) {
1075
1417
  var ret = ''
1076
1418
  end = Math.min(buf.length, end)
1077
1419
 
1078
- for (var i = start; i < end; i++) {
1420
+ for (var i = start; i < end; ++i) {
1079
1421
  ret += String.fromCharCode(buf[i])
1080
1422
  }
1081
1423
  return ret
@@ -1088,7 +1430,7 @@ function hexSlice (buf, start, end) {
1088
1430
  if (!end || end < 0 || end > len) end = len
1089
1431
 
1090
1432
  var out = ''
1091
- for (var i = start; i < end; i++) {
1433
+ for (var i = start; i < end; ++i) {
1092
1434
  out += toHex(buf[i])
1093
1435
  }
1094
1436
  return out
@@ -1098,7 +1440,7 @@ function utf16leSlice (buf, start, end) {
1098
1440
  var bytes = buf.slice(start, end)
1099
1441
  var res = ''
1100
1442
  for (var i = 0; i < bytes.length; i += 2) {
1101
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1443
+ res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1102
1444
  }
1103
1445
  return res
1104
1446
  }
@@ -1124,19 +1466,9 @@ Buffer.prototype.slice = function slice (start, end) {
1124
1466
 
1125
1467
  if (end < start) end = start
1126
1468
 
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
-
1469
+ var newBuf = this.subarray(start, end)
1470
+ // Return an augmented `Uint8Array` instance
1471
+ newBuf.__proto__ = Buffer.prototype
1140
1472
  return newBuf
1141
1473
  }
1142
1474
 
@@ -1149,8 +1481,8 @@ function checkOffset (offset, ext, length) {
1149
1481
  }
1150
1482
 
1151
1483
  Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1152
- offset = offset | 0
1153
- byteLength = byteLength | 0
1484
+ offset = offset >>> 0
1485
+ byteLength = byteLength >>> 0
1154
1486
  if (!noAssert) checkOffset(offset, byteLength, this.length)
1155
1487
 
1156
1488
  var val = this[offset]
@@ -1164,8 +1496,8 @@ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert)
1164
1496
  }
1165
1497
 
1166
1498
  Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1167
- offset = offset | 0
1168
- byteLength = byteLength | 0
1499
+ offset = offset >>> 0
1500
+ byteLength = byteLength >>> 0
1169
1501
  if (!noAssert) {
1170
1502
  checkOffset(offset, byteLength, this.length)
1171
1503
  }
@@ -1180,21 +1512,25 @@ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert)
1180
1512
  }
1181
1513
 
1182
1514
  Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1515
+ offset = offset >>> 0
1183
1516
  if (!noAssert) checkOffset(offset, 1, this.length)
1184
1517
  return this[offset]
1185
1518
  }
1186
1519
 
1187
1520
  Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1521
+ offset = offset >>> 0
1188
1522
  if (!noAssert) checkOffset(offset, 2, this.length)
1189
1523
  return this[offset] | (this[offset + 1] << 8)
1190
1524
  }
1191
1525
 
1192
1526
  Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1527
+ offset = offset >>> 0
1193
1528
  if (!noAssert) checkOffset(offset, 2, this.length)
1194
1529
  return (this[offset] << 8) | this[offset + 1]
1195
1530
  }
1196
1531
 
1197
1532
  Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1533
+ offset = offset >>> 0
1198
1534
  if (!noAssert) checkOffset(offset, 4, this.length)
1199
1535
 
1200
1536
  return ((this[offset]) |
@@ -1204,6 +1540,7 @@ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1204
1540
  }
1205
1541
 
1206
1542
  Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1543
+ offset = offset >>> 0
1207
1544
  if (!noAssert) checkOffset(offset, 4, this.length)
1208
1545
 
1209
1546
  return (this[offset] * 0x1000000) +
@@ -1213,8 +1550,8 @@ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1213
1550
  }
1214
1551
 
1215
1552
  Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1216
- offset = offset | 0
1217
- byteLength = byteLength | 0
1553
+ offset = offset >>> 0
1554
+ byteLength = byteLength >>> 0
1218
1555
  if (!noAssert) checkOffset(offset, byteLength, this.length)
1219
1556
 
1220
1557
  var val = this[offset]
@@ -1231,8 +1568,8 @@ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1231
1568
  }
1232
1569
 
1233
1570
  Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1234
- offset = offset | 0
1235
- byteLength = byteLength | 0
1571
+ offset = offset >>> 0
1572
+ byteLength = byteLength >>> 0
1236
1573
  if (!noAssert) checkOffset(offset, byteLength, this.length)
1237
1574
 
1238
1575
  var i = byteLength
@@ -1249,24 +1586,28 @@ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1249
1586
  }
1250
1587
 
1251
1588
  Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1589
+ offset = offset >>> 0
1252
1590
  if (!noAssert) checkOffset(offset, 1, this.length)
1253
1591
  if (!(this[offset] & 0x80)) return (this[offset])
1254
1592
  return ((0xff - this[offset] + 1) * -1)
1255
1593
  }
1256
1594
 
1257
1595
  Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1596
+ offset = offset >>> 0
1258
1597
  if (!noAssert) checkOffset(offset, 2, this.length)
1259
1598
  var val = this[offset] | (this[offset + 1] << 8)
1260
1599
  return (val & 0x8000) ? val | 0xFFFF0000 : val
1261
1600
  }
1262
1601
 
1263
1602
  Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1603
+ offset = offset >>> 0
1264
1604
  if (!noAssert) checkOffset(offset, 2, this.length)
1265
1605
  var val = this[offset + 1] | (this[offset] << 8)
1266
1606
  return (val & 0x8000) ? val | 0xFFFF0000 : val
1267
1607
  }
1268
1608
 
1269
1609
  Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1610
+ offset = offset >>> 0
1270
1611
  if (!noAssert) checkOffset(offset, 4, this.length)
1271
1612
 
1272
1613
  return (this[offset]) |
@@ -1276,6 +1617,7 @@ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1276
1617
  }
1277
1618
 
1278
1619
  Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1620
+ offset = offset >>> 0
1279
1621
  if (!noAssert) checkOffset(offset, 4, this.length)
1280
1622
 
1281
1623
  return (this[offset] << 24) |
@@ -1285,36 +1627,43 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1285
1627
  }
1286
1628
 
1287
1629
  Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1630
+ offset = offset >>> 0
1288
1631
  if (!noAssert) checkOffset(offset, 4, this.length)
1289
1632
  return ieee754.read(this, offset, true, 23, 4)
1290
1633
  }
1291
1634
 
1292
1635
  Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1636
+ offset = offset >>> 0
1293
1637
  if (!noAssert) checkOffset(offset, 4, this.length)
1294
1638
  return ieee754.read(this, offset, false, 23, 4)
1295
1639
  }
1296
1640
 
1297
1641
  Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1642
+ offset = offset >>> 0
1298
1643
  if (!noAssert) checkOffset(offset, 8, this.length)
1299
1644
  return ieee754.read(this, offset, true, 52, 8)
1300
1645
  }
1301
1646
 
1302
1647
  Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1648
+ offset = offset >>> 0
1303
1649
  if (!noAssert) checkOffset(offset, 8, this.length)
1304
1650
  return ieee754.read(this, offset, false, 52, 8)
1305
1651
  }
1306
1652
 
1307
1653
  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')
1654
+ if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1655
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1656
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
1311
1657
  }
1312
1658
 
1313
1659
  Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1314
1660
  value = +value
1315
- offset = offset | 0
1316
- byteLength = byteLength | 0
1317
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1661
+ offset = offset >>> 0
1662
+ byteLength = byteLength >>> 0
1663
+ if (!noAssert) {
1664
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
1665
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
1666
+ }
1318
1667
 
1319
1668
  var mul = 1
1320
1669
  var i = 0
@@ -1328,9 +1677,12 @@ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength,
1328
1677
 
1329
1678
  Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1330
1679
  value = +value
1331
- offset = offset | 0
1332
- byteLength = byteLength | 0
1333
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1680
+ offset = offset >>> 0
1681
+ byteLength = byteLength >>> 0
1682
+ if (!noAssert) {
1683
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
1684
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
1685
+ }
1334
1686
 
1335
1687
  var i = byteLength - 1
1336
1688
  var mul = 1
@@ -1344,98 +1696,69 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength,
1344
1696
 
1345
1697
  Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1346
1698
  value = +value
1347
- offset = offset | 0
1699
+ offset = offset >>> 0
1348
1700
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1349
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1350
1701
  this[offset] = (value & 0xff)
1351
1702
  return offset + 1
1352
1703
  }
1353
1704
 
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
1705
  Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1363
1706
  value = +value
1364
- offset = offset | 0
1707
+ offset = offset >>> 0
1365
1708
  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
- }
1709
+ this[offset] = (value & 0xff)
1710
+ this[offset + 1] = (value >>> 8)
1372
1711
  return offset + 2
1373
1712
  }
1374
1713
 
1375
1714
  Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1376
1715
  value = +value
1377
- offset = offset | 0
1716
+ offset = offset >>> 0
1378
1717
  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
- }
1718
+ this[offset] = (value >>> 8)
1719
+ this[offset + 1] = (value & 0xff)
1385
1720
  return offset + 2
1386
1721
  }
1387
1722
 
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
1723
  Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1396
1724
  value = +value
1397
- offset = offset | 0
1725
+ offset = offset >>> 0
1398
1726
  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
- }
1727
+ this[offset + 3] = (value >>> 24)
1728
+ this[offset + 2] = (value >>> 16)
1729
+ this[offset + 1] = (value >>> 8)
1730
+ this[offset] = (value & 0xff)
1407
1731
  return offset + 4
1408
1732
  }
1409
1733
 
1410
1734
  Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1411
1735
  value = +value
1412
- offset = offset | 0
1736
+ offset = offset >>> 0
1413
1737
  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
- }
1738
+ this[offset] = (value >>> 24)
1739
+ this[offset + 1] = (value >>> 16)
1740
+ this[offset + 2] = (value >>> 8)
1741
+ this[offset + 3] = (value & 0xff)
1422
1742
  return offset + 4
1423
1743
  }
1424
1744
 
1425
1745
  Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1426
1746
  value = +value
1427
- offset = offset | 0
1747
+ offset = offset >>> 0
1428
1748
  if (!noAssert) {
1429
- var limit = Math.pow(2, 8 * byteLength - 1)
1749
+ var limit = Math.pow(2, (8 * byteLength) - 1)
1430
1750
 
1431
1751
  checkInt(this, value, offset, byteLength, limit - 1, -limit)
1432
1752
  }
1433
1753
 
1434
1754
  var i = 0
1435
1755
  var mul = 1
1436
- var sub = value < 0 ? 1 : 0
1756
+ var sub = 0
1437
1757
  this[offset] = value & 0xFF
1438
1758
  while (++i < byteLength && (mul *= 0x100)) {
1759
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1760
+ sub = 1
1761
+ }
1439
1762
  this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1440
1763
  }
1441
1764
 
@@ -1444,18 +1767,21 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no
1444
1767
 
1445
1768
  Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1446
1769
  value = +value
1447
- offset = offset | 0
1770
+ offset = offset >>> 0
1448
1771
  if (!noAssert) {
1449
- var limit = Math.pow(2, 8 * byteLength - 1)
1772
+ var limit = Math.pow(2, (8 * byteLength) - 1)
1450
1773
 
1451
1774
  checkInt(this, value, offset, byteLength, limit - 1, -limit)
1452
1775
  }
1453
1776
 
1454
1777
  var i = byteLength - 1
1455
1778
  var mul = 1
1456
- var sub = value < 0 ? 1 : 0
1779
+ var sub = 0
1457
1780
  this[offset + i] = value & 0xFF
1458
1781
  while (--i >= 0 && (mul *= 0x100)) {
1782
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1783
+ sub = 1
1784
+ }
1459
1785
  this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1460
1786
  }
1461
1787
 
@@ -1464,9 +1790,8 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no
1464
1790
 
1465
1791
  Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1466
1792
  value = +value
1467
- offset = offset | 0
1793
+ offset = offset >>> 0
1468
1794
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1469
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1470
1795
  if (value < 0) value = 0xff + value + 1
1471
1796
  this[offset] = (value & 0xff)
1472
1797
  return offset + 1
@@ -1474,68 +1799,53 @@ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1474
1799
 
1475
1800
  Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1476
1801
  value = +value
1477
- offset = offset | 0
1802
+ offset = offset >>> 0
1478
1803
  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
- }
1804
+ this[offset] = (value & 0xff)
1805
+ this[offset + 1] = (value >>> 8)
1485
1806
  return offset + 2
1486
1807
  }
1487
1808
 
1488
1809
  Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1489
1810
  value = +value
1490
- offset = offset | 0
1811
+ offset = offset >>> 0
1491
1812
  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
- }
1813
+ this[offset] = (value >>> 8)
1814
+ this[offset + 1] = (value & 0xff)
1498
1815
  return offset + 2
1499
1816
  }
1500
1817
 
1501
1818
  Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1502
1819
  value = +value
1503
- offset = offset | 0
1820
+ offset = offset >>> 0
1504
1821
  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
- }
1822
+ this[offset] = (value & 0xff)
1823
+ this[offset + 1] = (value >>> 8)
1824
+ this[offset + 2] = (value >>> 16)
1825
+ this[offset + 3] = (value >>> 24)
1513
1826
  return offset + 4
1514
1827
  }
1515
1828
 
1516
1829
  Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1517
1830
  value = +value
1518
- offset = offset | 0
1831
+ offset = offset >>> 0
1519
1832
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1520
1833
  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
- }
1834
+ this[offset] = (value >>> 24)
1835
+ this[offset + 1] = (value >>> 16)
1836
+ this[offset + 2] = (value >>> 8)
1837
+ this[offset + 3] = (value & 0xff)
1529
1838
  return offset + 4
1530
1839
  }
1531
1840
 
1532
1841
  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')
1842
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
1843
+ if (offset < 0) throw new RangeError('Index out of range')
1536
1844
  }
1537
1845
 
1538
1846
  function writeFloat (buf, value, offset, littleEndian, noAssert) {
1847
+ value = +value
1848
+ offset = offset >>> 0
1539
1849
  if (!noAssert) {
1540
1850
  checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1541
1851
  }
@@ -1552,6 +1862,8 @@ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert)
1552
1862
  }
1553
1863
 
1554
1864
  function writeDouble (buf, value, offset, littleEndian, noAssert) {
1865
+ value = +value
1866
+ offset = offset >>> 0
1555
1867
  if (!noAssert) {
1556
1868
  checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1557
1869
  }
@@ -1569,6 +1881,7 @@ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert
1569
1881
 
1570
1882
  // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1571
1883
  Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1884
+ if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
1572
1885
  if (!start) start = 0
1573
1886
  if (!end && end !== 0) end = this.length
1574
1887
  if (targetStart >= target.length) targetStart = target.length
@@ -1583,7 +1896,7 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1583
1896
  if (targetStart < 0) {
1584
1897
  throw new RangeError('targetStart out of bounds')
1585
1898
  }
1586
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1899
+ if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
1587
1900
  if (end < 0) throw new RangeError('sourceEnd out of bounds')
1588
1901
 
1589
1902
  // Are we oob?
@@ -1593,152 +1906,105 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1593
1906
  }
1594
1907
 
1595
1908
  var len = end - start
1596
- var i
1597
1909
 
1598
- if (this === target && start < targetStart && targetStart < end) {
1910
+ if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
1911
+ // Use built-in when available, missing from IE11
1912
+ this.copyWithin(targetStart, start, end)
1913
+ } else if (this === target && start < targetStart && targetStart < end) {
1599
1914
  // 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++) {
1915
+ for (var i = len - 1; i >= 0; --i) {
1606
1916
  target[i + targetStart] = this[i + start]
1607
1917
  }
1608
1918
  } else {
1609
- target._set(this.subarray(start, start + len), targetStart)
1919
+ Uint8Array.prototype.set.call(
1920
+ target,
1921
+ this.subarray(start, end),
1922
+ targetStart
1923
+ )
1610
1924
  }
1611
1925
 
1612
1926
  return len
1613
1927
  }
1614
1928
 
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
1929
+ // Usage:
1930
+ // buffer.fill(number[, offset[, end]])
1931
+ // buffer.fill(buffer[, offset[, end]])
1932
+ // buffer.fill(string[, offset[, end]][, encoding])
1933
+ Buffer.prototype.fill = function fill (val, start, end, encoding) {
1934
+ // Handle string cases:
1935
+ if (typeof val === 'string') {
1936
+ if (typeof start === 'string') {
1937
+ encoding = start
1938
+ start = 0
1939
+ end = this.length
1940
+ } else if (typeof end === 'string') {
1941
+ encoding = end
1942
+ end = this.length
1943
+ }
1944
+ if (encoding !== undefined && typeof encoding !== 'string') {
1945
+ throw new TypeError('encoding must be a string')
1946
+ }
1947
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1948
+ throw new TypeError('Unknown encoding: ' + encoding)
1949
+ }
1950
+ if (val.length === 1) {
1951
+ var code = val.charCodeAt(0)
1952
+ if ((encoding === 'utf8' && code < 128) ||
1953
+ encoding === 'latin1') {
1954
+ // Fast path: If `val` fits into a single byte, use that numeric value.
1955
+ val = code
1956
+ }
1957
+ }
1958
+ } else if (typeof val === 'number') {
1959
+ val = val & 255
1960
+ }
1620
1961
 
1621
- if (end < start) throw new RangeError('end < start')
1962
+ // Invalid ranges are not set to a default, so can range check early.
1963
+ if (start < 0 || this.length < start || this.length < end) {
1964
+ throw new RangeError('Out of range index')
1965
+ }
1966
+
1967
+ if (end <= start) {
1968
+ return this
1969
+ }
1622
1970
 
1623
- // Fill 0 bytes; we're done
1624
- if (end === start) return
1625
- if (this.length === 0) return
1971
+ start = start >>> 0
1972
+ end = end === undefined ? this.length : end >>> 0
1626
1973
 
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')
1974
+ if (!val) val = 0
1629
1975
 
1630
1976
  var i
1631
- if (typeof value === 'number') {
1632
- for (i = start; i < end; i++) {
1633
- this[i] = value
1977
+ if (typeof val === 'number') {
1978
+ for (i = start; i < end; ++i) {
1979
+ this[i] = val
1634
1980
  }
1635
1981
  } else {
1636
- var bytes = utf8ToBytes(value.toString())
1982
+ var bytes = Buffer.isBuffer(val)
1983
+ ? val
1984
+ : Buffer.from(val, encoding)
1637
1985
  var len = bytes.length
1638
- for (i = start; i < end; i++) {
1639
- this[i] = bytes[i % len]
1986
+ if (len === 0) {
1987
+ throw new TypeError('The value "' + val +
1988
+ '" is invalid for argument "value"')
1989
+ }
1990
+ for (i = 0; i < end - start; ++i) {
1991
+ this[i + start] = bytes[i % len]
1640
1992
  }
1641
1993
  }
1642
1994
 
1643
1995
  return this
1644
1996
  }
1645
1997
 
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
1998
  // HELPER FUNCTIONS
1667
1999
  // ================
1668
2000
 
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
2001
+ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
1738
2002
 
1739
2003
  function base64clean (str) {
2004
+ // Node takes equal signs as end of the Base64 encoding
2005
+ str = str.split('=')[0]
1740
2006
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
1741
- str = stringtrim(str).replace(INVALID_BASE64_RE, '')
2007
+ str = str.trim().replace(INVALID_BASE64_RE, '')
1742
2008
  // Node converts strings with length < 2 to ''
1743
2009
  if (str.length < 2) return ''
1744
2010
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
@@ -1748,11 +2014,6 @@ function base64clean (str) {
1748
2014
  return str
1749
2015
  }
1750
2016
 
1751
- function stringtrim (str) {
1752
- if (str.trim) return str.trim()
1753
- return str.replace(/^\s+|\s+$/g, '')
1754
- }
1755
-
1756
2017
  function toHex (n) {
1757
2018
  if (n < 16) return '0' + n.toString(16)
1758
2019
  return n.toString(16)
@@ -1765,7 +2026,7 @@ function utf8ToBytes (string, units) {
1765
2026
  var leadSurrogate = null
1766
2027
  var bytes = []
1767
2028
 
1768
- for (var i = 0; i < length; i++) {
2029
+ for (var i = 0; i < length; ++i) {
1769
2030
  codePoint = string.charCodeAt(i)
1770
2031
 
1771
2032
  // is surrogate component
@@ -1797,7 +2058,7 @@ function utf8ToBytes (string, units) {
1797
2058
  }
1798
2059
 
1799
2060
  // valid surrogate pair
1800
- codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
2061
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
1801
2062
  } else if (leadSurrogate) {
1802
2063
  // valid bmp char, but last char was a lead
1803
2064
  if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
@@ -1840,7 +2101,7 @@ function utf8ToBytes (string, units) {
1840
2101
 
1841
2102
  function asciiToBytes (str) {
1842
2103
  var byteArray = []
1843
- for (var i = 0; i < str.length; i++) {
2104
+ for (var i = 0; i < str.length; ++i) {
1844
2105
  // Node's code seems to be doing this and not & 0x7F..
1845
2106
  byteArray.push(str.charCodeAt(i) & 0xFF)
1846
2107
  }
@@ -1850,7 +2111,7 @@ function asciiToBytes (str) {
1850
2111
  function utf16leToBytes (str, units) {
1851
2112
  var c, hi, lo
1852
2113
  var byteArray = []
1853
- for (var i = 0; i < str.length; i++) {
2114
+ for (var i = 0; i < str.length; ++i) {
1854
2115
  if ((units -= 2) < 0) break
1855
2116
 
1856
2117
  c = str.charCodeAt(i)
@@ -1868,18 +2129,32 @@ function base64ToBytes (str) {
1868
2129
  }
1869
2130
 
1870
2131
  function blitBuffer (src, dst, offset, length) {
1871
- for (var i = 0; i < length; i++) {
2132
+ for (var i = 0; i < length; ++i) {
1872
2133
  if ((i + offset >= dst.length) || (i >= src.length)) break
1873
2134
  dst[i + offset] = src[i]
1874
2135
  }
1875
2136
  return i
1876
2137
  }
1877
2138
 
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){
2139
+ // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
2140
+ // the `instanceof` check but they should be treated as of that type.
2141
+ // See: https://github.com/feross/buffer/issues/166
2142
+ function isInstance (obj, type) {
2143
+ return obj instanceof type ||
2144
+ (obj != null && obj.constructor != null && obj.constructor.name != null &&
2145
+ obj.constructor.name === type.name)
2146
+ }
2147
+ function numberIsNaN (obj) {
2148
+ // For IE11 support
2149
+ return obj !== obj // eslint-disable-line no-self-compare
2150
+ }
2151
+
2152
+ }).call(this)}).call(this,require("buffer").Buffer)
2153
+ },{"base64-js":2,"buffer":3,"ieee754":4}],4:[function(require,module,exports){
2154
+ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
1880
2155
  exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1881
2156
  var e, m
1882
- var eLen = nBytes * 8 - mLen - 1
2157
+ var eLen = (nBytes * 8) - mLen - 1
1883
2158
  var eMax = (1 << eLen) - 1
1884
2159
  var eBias = eMax >> 1
1885
2160
  var nBits = -7
@@ -1892,12 +2167,12 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1892
2167
  e = s & ((1 << (-nBits)) - 1)
1893
2168
  s >>= (-nBits)
1894
2169
  nBits += eLen
1895
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2170
+ for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
1896
2171
 
1897
2172
  m = e & ((1 << (-nBits)) - 1)
1898
2173
  e >>= (-nBits)
1899
2174
  nBits += mLen
1900
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2175
+ for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
1901
2176
 
1902
2177
  if (e === 0) {
1903
2178
  e = 1 - eBias
@@ -1912,7 +2187,7 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1912
2187
 
1913
2188
  exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1914
2189
  var e, m, c
1915
- var eLen = nBytes * 8 - mLen - 1
2190
+ var eLen = (nBytes * 8) - mLen - 1
1916
2191
  var eMax = (1 << eLen) - 1
1917
2192
  var eBias = eMax >> 1
1918
2193
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
@@ -1945,7 +2220,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1945
2220
  m = 0
1946
2221
  e = eMax
1947
2222
  } else if (e + eBias >= 1) {
1948
- m = (value * c - 1) * Math.pow(2, mLen)
2223
+ m = ((value * c) - 1) * Math.pow(2, mLen)
1949
2224
  e = e + eBias
1950
2225
  } else {
1951
2226
  m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
@@ -1960,379 +2235,264 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1960
2235
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
1961
2236
 
1962
2237
  buffer[offset + i - d] |= s * 128
1963
- }
1964
-
1965
- },{}],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
- }
2238
+ }
2031
2239
 
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
- }
2240
+ },{}],5:[function(require,module,exports){
2241
+ function DOMParser(options){
2242
+ this.options = options ||{locator:{}};
2243
+ }
2244
+
2245
+ DOMParser.prototype.parseFromString = function(source,mimeType){
2246
+ var options = this.options;
2247
+ var sax = new XMLReader();
2248
+ var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
2249
+ var errorHandler = options.errorHandler;
2250
+ var locator = options.locator;
2251
+ var defaultNSMap = options.xmlns||{};
2252
+ var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
2253
+ var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
2254
+ if(locator){
2255
+ domBuilder.setDocumentLocator(locator)
2256
+ }
2046
2257
 
2047
- return deprecated;
2258
+ sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
2259
+ sax.domBuilder = options.domBuilder || domBuilder;
2260
+ if(isHTML){
2261
+ defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
2262
+ }
2263
+ defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
2264
+ if(source && typeof source === 'string'){
2265
+ sax.parse(source,defaultNSMap,entityMap);
2266
+ }else{
2267
+ sax.errorHandler.error("invalid doc source");
2268
+ }
2269
+ return domBuilder.doc;
2270
+ }
2271
+ function buildErrorHandler(errorImpl,domBuilder,locator){
2272
+ if(!errorImpl){
2273
+ if(domBuilder instanceof DOMHandler){
2274
+ return domBuilder;
2275
+ }
2276
+ errorImpl = domBuilder ;
2277
+ }
2278
+ var errorHandler = {}
2279
+ var isCallback = errorImpl instanceof Function;
2280
+ locator = locator||{}
2281
+ function build(key){
2282
+ var fn = errorImpl[key];
2283
+ if(!fn && isCallback){
2284
+ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
2285
+ }
2286
+ errorHandler[key] = fn && function(msg){
2287
+ fn('[xmldom '+key+']\t'+msg+_locator(locator));
2288
+ }||function(){};
2289
+ }
2290
+ build('warning');
2291
+ build('error');
2292
+ build('fatalError');
2293
+ return errorHandler;
2048
2294
  }
2049
2295
 
2296
+ //console.log('#\n\n\n\n\n\n\n####')
2050
2297
  /**
2051
- * Checks `localStorage` for boolean values for the given `name`.
2298
+ * +ContentHandler+ErrorHandler
2299
+ * +LexicalHandler+EntityResolver2
2300
+ * -DeclHandler-DTDHandler
2052
2301
  *
2053
- * @param {String} name
2054
- * @returns {Boolean}
2055
- * @api private
2302
+ * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
2303
+ * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
2304
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
2305
+ */
2306
+ function DOMHandler() {
2307
+ this.cdata = false;
2308
+ }
2309
+ function position(locator,node){
2310
+ node.lineNumber = locator.lineNumber;
2311
+ node.columnNumber = locator.columnNumber;
2312
+ }
2313
+ /**
2314
+ * @see org.xml.sax.ContentHandler#startDocument
2315
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
2056
2316
  */
2317
+ DOMHandler.prototype = {
2318
+ startDocument : function() {
2319
+ this.doc = new DOMImplementation().createDocument(null, null, null);
2320
+ if (this.locator) {
2321
+ this.doc.documentURI = this.locator.systemId;
2322
+ }
2323
+ },
2324
+ startElement:function(namespaceURI, localName, qName, attrs) {
2325
+ var doc = this.doc;
2326
+ var el = doc.createElementNS(namespaceURI, qName||localName);
2327
+ var len = attrs.length;
2328
+ appendElement(this, el);
2329
+ this.currentElement = el;
2330
+
2331
+ this.locator && position(this.locator,el)
2332
+ for (var i = 0 ; i < len; i++) {
2333
+ var namespaceURI = attrs.getURI(i);
2334
+ var value = attrs.getValue(i);
2335
+ var qName = attrs.getQName(i);
2336
+ var attr = doc.createAttributeNS(namespaceURI, qName);
2337
+ this.locator &&position(attrs.getLocator(i),attr);
2338
+ attr.value = attr.nodeValue = value;
2339
+ el.setAttributeNode(attr)
2340
+ }
2341
+ },
2342
+ endElement:function(namespaceURI, localName, qName) {
2343
+ var current = this.currentElement
2344
+ var tagName = current.tagName;
2345
+ this.currentElement = current.parentNode;
2346
+ },
2347
+ startPrefixMapping:function(prefix, uri) {
2348
+ },
2349
+ endPrefixMapping:function(prefix) {
2350
+ },
2351
+ processingInstruction:function(target, data) {
2352
+ var ins = this.doc.createProcessingInstruction(target, data);
2353
+ this.locator && position(this.locator,ins)
2354
+ appendElement(this, ins);
2355
+ },
2356
+ ignorableWhitespace:function(ch, start, length) {
2357
+ },
2358
+ characters:function(chars, start, length) {
2359
+ chars = _toString.apply(this,arguments)
2360
+ //console.log(chars)
2361
+ if(chars){
2362
+ if (this.cdata) {
2363
+ var charNode = this.doc.createCDATASection(chars);
2364
+ } else {
2365
+ var charNode = this.doc.createTextNode(chars);
2366
+ }
2367
+ if(this.currentElement){
2368
+ this.currentElement.appendChild(charNode);
2369
+ }else if(/^\s*$/.test(chars)){
2370
+ this.doc.appendChild(charNode);
2371
+ //process xml
2372
+ }
2373
+ this.locator && position(this.locator,charNode)
2374
+ }
2375
+ },
2376
+ skippedEntity:function(name) {
2377
+ },
2378
+ endDocument:function() {
2379
+ this.doc.normalize();
2380
+ },
2381
+ setDocumentLocator:function (locator) {
2382
+ if(this.locator = locator){// && !('lineNumber' in locator)){
2383
+ locator.lineNumber = 0;
2384
+ }
2385
+ },
2386
+ //LexicalHandler
2387
+ comment:function(chars, start, length) {
2388
+ chars = _toString.apply(this,arguments)
2389
+ var comm = this.doc.createComment(chars);
2390
+ this.locator && position(this.locator,comm)
2391
+ appendElement(this, comm);
2392
+ },
2057
2393
 
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';
2394
+ startCDATA:function() {
2395
+ //used in characters() methods
2396
+ this.cdata = true;
2397
+ },
2398
+ endCDATA:function() {
2399
+ this.cdata = false;
2400
+ },
2401
+
2402
+ startDTD:function(name, publicId, systemId) {
2403
+ var impl = this.doc.implementation;
2404
+ if (impl && impl.createDocumentType) {
2405
+ var dt = impl.createDocumentType(name, publicId, systemId);
2406
+ this.locator && position(this.locator,dt)
2407
+ appendElement(this, dt);
2408
+ }
2409
+ },
2410
+ /**
2411
+ * @see org.xml.sax.ErrorHandler
2412
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
2413
+ */
2414
+ warning:function(error) {
2415
+ console.warn('[xmldom warning]\t'+error,_locator(this.locator));
2416
+ },
2417
+ error:function(error) {
2418
+ console.error('[xmldom error]\t'+error,_locator(this.locator));
2419
+ },
2420
+ fatalError:function(error) {
2421
+ throw new ParseError(error, this.locator);
2422
+ }
2423
+ }
2424
+ function _locator(l){
2425
+ if(l){
2426
+ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
2427
+ }
2428
+ }
2429
+ function _toString(chars,start,length){
2430
+ if(typeof chars == 'string'){
2431
+ return chars.substr(start,length)
2432
+ }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
2433
+ if(chars.length >= start+length || start){
2434
+ return new java.lang.String(chars,start,length)+'';
2435
+ }
2436
+ return chars;
2437
+ }
2068
2438
  }
2069
2439
 
2070
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2071
- },{}],7:[function(require,module,exports){
2072
- function DOMParser(options){
2073
- this.options = options ||{locator:{}};
2074
-
2075
- }
2076
- DOMParser.prototype.parseFromString = function(source,mimeType){
2077
- var options = this.options;
2078
- var sax = new XMLReader();
2079
- var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
2080
- var errorHandler = options.errorHandler;
2081
- var locator = options.locator;
2082
- var defaultNSMap = options.xmlns||{};
2083
- var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
2084
- if(locator){
2085
- domBuilder.setDocumentLocator(locator)
2086
- }
2087
-
2088
- sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
2089
- sax.domBuilder = options.domBuilder || domBuilder;
2090
- if(/\/x?html?$/.test(mimeType)){
2091
- entityMap.nbsp = '\xa0';
2092
- entityMap.copy = '\xa9';
2093
- defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
2094
- }
2095
- if(source){
2096
- sax.parse(source,defaultNSMap,entityMap);
2097
- }else{
2098
- sax.errorHandler.error("invalid document source");
2099
- }
2100
- return domBuilder.document;
2101
- }
2102
- function buildErrorHandler(errorImpl,domBuilder,locator){
2103
- if(!errorImpl){
2104
- if(domBuilder instanceof DOMHandler){
2105
- return domBuilder;
2106
- }
2107
- errorImpl = domBuilder ;
2108
- }
2109
- var errorHandler = {}
2110
- var isCallback = errorImpl instanceof Function;
2111
- locator = locator||{}
2112
- function build(key){
2113
- 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
- }
2125
- }
2126
- errorHandler[key] = fn && function(msg){
2127
- fn(msg+_locator(locator));
2128
- }||function(){};
2129
- }
2130
- build('warning','warn');
2131
- build('error','warn','warning');
2132
- build('fatalError','warn','warning','error');
2133
- return errorHandler;
2134
- }
2135
- /**
2136
- * +ContentHandler+ErrorHandler
2137
- * +LexicalHandler+EntityResolver2
2138
- * -DeclHandler-DTDHandler
2139
- *
2140
- * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
2141
- * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
2142
- * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
2143
- */
2144
- function DOMHandler() {
2145
- this.cdata = false;
2146
- }
2147
- function position(locator,node){
2148
- node.lineNumber = locator.lineNumber;
2149
- node.columnNumber = locator.columnNumber;
2150
- }
2151
- /**
2152
- * @see org.xml.sax.ContentHandler#startDocument
2153
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
2154
- */
2155
- DOMHandler.prototype = {
2156
- startDocument : function() {
2157
- this.document = new DOMImplementation().createDocument(null, null, null);
2158
- if (this.locator) {
2159
- this.document.documentURI = this.locator.systemId;
2160
- }
2161
- },
2162
- startElement:function(namespaceURI, localName, qName, attrs) {
2163
- var doc = this.document;
2164
- var el = doc.createElementNS(namespaceURI, qName||localName);
2165
- var len = attrs.length;
2166
- appendElement(this, el);
2167
- this.currentElement = el;
2168
-
2169
- this.locator && position(this.locator,el)
2170
- for (var i = 0 ; i < len; i++) {
2171
- var namespaceURI = attrs.getURI(i);
2172
- var value = attrs.getValue(i);
2173
- var qName = attrs.getQName(i);
2174
- var attr = doc.createAttributeNS(namespaceURI, qName);
2175
- if( attr.getOffset){
2176
- position(attr.getOffset(1),attr)
2177
- }
2178
- attr.value = attr.nodeValue = value;
2179
- el.setAttributeNode(attr)
2180
- }
2181
- },
2182
- endElement:function(namespaceURI, localName, qName) {
2183
- var current = this.currentElement
2184
- var tagName = current.tagName;
2185
- this.currentElement = current.parentNode;
2186
- },
2187
- startPrefixMapping:function(prefix, uri) {
2188
- },
2189
- endPrefixMapping:function(prefix) {
2190
- },
2191
- processingInstruction:function(target, data) {
2192
- var ins = this.document.createProcessingInstruction(target, data);
2193
- this.locator && position(this.locator,ins)
2194
- appendElement(this, ins);
2195
- },
2196
- ignorableWhitespace:function(ch, start, length) {
2197
- },
2198
- characters:function(chars, start, length) {
2199
- chars = _toString.apply(this,arguments)
2200
- //console.log(chars)
2201
- if(this.currentElement && chars){
2202
- if (this.cdata) {
2203
- var charNode = this.document.createCDATASection(chars);
2204
- this.currentElement.appendChild(charNode);
2205
- } else {
2206
- var charNode = this.document.createTextNode(chars);
2207
- this.currentElement.appendChild(charNode);
2208
- }
2209
- this.locator && position(this.locator,charNode)
2210
- }
2211
- },
2212
- skippedEntity:function(name) {
2213
- },
2214
- endDocument:function() {
2215
- this.document.normalize();
2216
- },
2217
- setDocumentLocator:function (locator) {
2218
- if(this.locator = locator){// && !('lineNumber' in locator)){
2219
- locator.lineNumber = 0;
2220
- }
2221
- },
2222
- //LexicalHandler
2223
- comment:function(chars, start, length) {
2224
- chars = _toString.apply(this,arguments)
2225
- var comm = this.document.createComment(chars);
2226
- this.locator && position(this.locator,comm)
2227
- appendElement(this, comm);
2228
- },
2229
-
2230
- startCDATA:function() {
2231
- //used in characters() methods
2232
- this.cdata = true;
2233
- },
2234
- endCDATA:function() {
2235
- this.cdata = false;
2236
- },
2237
-
2238
- startDTD:function(name, publicId, systemId) {
2239
- var impl = this.document.implementation;
2240
- if (impl && impl.createDocumentType) {
2241
- var dt = impl.createDocumentType(name, publicId, systemId);
2242
- this.locator && position(this.locator,dt)
2243
- appendElement(this, dt);
2244
- }
2245
- },
2246
- /**
2247
- * @see org.xml.sax.ErrorHandler
2248
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
2249
- */
2250
- warning:function(error) {
2251
- console.warn(error,_locator(this.locator));
2252
- },
2253
- error:function(error) {
2254
- console.error(error,_locator(this.locator));
2255
- },
2256
- fatalError:function(error) {
2257
- console.error(error,_locator(this.locator));
2258
- throw error;
2259
- }
2260
- }
2261
- function _locator(l){
2262
- if(l){
2263
- return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
2264
- }
2265
- }
2266
- function _toString(chars,start,length){
2267
- if(typeof chars == 'string'){
2268
- return chars.substr(start,length)
2269
- }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
2270
- if(chars.length >= start+length || start){
2271
- return new java.lang.String(chars,start,length)+'';
2272
- }
2273
- return chars;
2274
- }
2275
- }
2276
-
2277
- /*
2278
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
2279
- * used method of org.xml.sax.ext.LexicalHandler:
2280
- * #comment(chars, start, length)
2281
- * #startCDATA()
2282
- * #endCDATA()
2283
- * #startDTD(name, publicId, systemId)
2284
- *
2285
- *
2286
- * IGNORED method of org.xml.sax.ext.LexicalHandler:
2287
- * #endDTD()
2288
- * #startEntity(name)
2289
- * #endEntity(name)
2290
- *
2291
- *
2292
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
2293
- * IGNORED method of org.xml.sax.ext.DeclHandler
2294
- * #attributeDecl(eName, aName, type, mode, value)
2295
- * #elementDecl(name, model)
2296
- * #externalEntityDecl(name, publicId, systemId)
2297
- * #internalEntityDecl(name, value)
2298
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
2299
- * IGNORED method of org.xml.sax.EntityResolver2
2300
- * #resolveEntity(String name,String publicId,String baseURI,String systemId)
2301
- * #resolveEntity(publicId, systemId)
2302
- * #getExternalSubset(name, baseURI)
2303
- * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
2304
- * IGNORED method of org.xml.sax.DTDHandler
2305
- * #notationDecl(name, publicId, systemId) {};
2306
- * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
2307
- */
2308
- "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
2309
- DOMHandler.prototype[key] = function(){return null}
2310
- })
2311
-
2312
- /* 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
- function appendElement (hander,node) {
2314
- if (!hander.currentElement) {
2315
- hander.document.appendChild(node);
2316
- } else {
2317
- hander.currentElement.appendChild(node);
2318
- }
2319
- }//appendChild and setAttributeNS are preformance key
2320
-
2321
- if(typeof require == 'function'){
2322
- var XMLReader = require('./sax').XMLReader;
2323
- var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
2324
- exports.XMLSerializer = require('./dom').XMLSerializer ;
2325
- exports.DOMParser = DOMParser;
2326
- }
2327
-
2328
- },{"./dom":8,"./sax":9}],8:[function(require,module,exports){
2329
2440
  /*
2330
- * DOM Level 2
2331
- * Object DOMException
2332
- * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
2333
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
2441
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
2442
+ * used method of org.xml.sax.ext.LexicalHandler:
2443
+ * #comment(chars, start, length)
2444
+ * #startCDATA()
2445
+ * #endCDATA()
2446
+ * #startDTD(name, publicId, systemId)
2447
+ *
2448
+ *
2449
+ * IGNORED method of org.xml.sax.ext.LexicalHandler:
2450
+ * #endDTD()
2451
+ * #startEntity(name)
2452
+ * #endEntity(name)
2453
+ *
2454
+ *
2455
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
2456
+ * IGNORED method of org.xml.sax.ext.DeclHandler
2457
+ * #attributeDecl(eName, aName, type, mode, value)
2458
+ * #elementDecl(name, model)
2459
+ * #externalEntityDecl(name, publicId, systemId)
2460
+ * #internalEntityDecl(name, value)
2461
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
2462
+ * IGNORED method of org.xml.sax.EntityResolver2
2463
+ * #resolveEntity(String name,String publicId,String baseURI,String systemId)
2464
+ * #resolveEntity(publicId, systemId)
2465
+ * #getExternalSubset(name, baseURI)
2466
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
2467
+ * IGNORED method of org.xml.sax.DTDHandler
2468
+ * #notationDecl(name, publicId, systemId) {};
2469
+ * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
2334
2470
  */
2335
-
2471
+ "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
2472
+ DOMHandler.prototype[key] = function(){return null}
2473
+ })
2474
+
2475
+ /* 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 */
2476
+ function appendElement (hander,node) {
2477
+ if (!hander.currentElement) {
2478
+ hander.doc.appendChild(node);
2479
+ } else {
2480
+ hander.currentElement.appendChild(node);
2481
+ }
2482
+ }//appendChild and setAttributeNS are preformance key
2483
+
2484
+ //if(typeof require == 'function'){
2485
+ var htmlEntity = require('./entities');
2486
+ var sax = require('./sax');
2487
+ var XMLReader = sax.XMLReader;
2488
+ var ParseError = sax.ParseError;
2489
+ var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
2490
+ exports.XMLSerializer = require('./dom').XMLSerializer ;
2491
+ exports.DOMParser = DOMParser;
2492
+ exports.__DOMHandler = DOMHandler;
2493
+ //}
2494
+
2495
+ },{"./dom":6,"./entities":7,"./sax":8}],6:[function(require,module,exports){
2336
2496
  function copy(src,dest){
2337
2497
  for(var p in src){
2338
2498
  dest[p] = src[p];
@@ -2344,10 +2504,6 @@ function copy(src,dest){
2344
2504
  */
2345
2505
  function _extends(Class,Super){
2346
2506
  var pt = Class.prototype;
2347
- if(Object.create){
2348
- var ppt = Object.create(Super.prototype)
2349
- pt.__proto__ = ppt;
2350
- }
2351
2507
  if(!(pt instanceof Super)){
2352
2508
  function t(){};
2353
2509
  t.prototype = Super.prototype;
@@ -2398,7 +2554,12 @@ var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((Exce
2398
2554
  var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
2399
2555
  var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
2400
2556
 
2401
-
2557
+ /**
2558
+ * DOM Level 2
2559
+ * Object DOMException
2560
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
2561
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
2562
+ */
2402
2563
  function DOMException(code, message) {
2403
2564
  if(message instanceof Error){
2404
2565
  var error = message;
@@ -2437,6 +2598,12 @@ NodeList.prototype = {
2437
2598
  */
2438
2599
  item: function(index) {
2439
2600
  return this[index] || null;
2601
+ },
2602
+ toString:function(isHTML,nodeFilter){
2603
+ for(var buf = [], i = 0;i<this.length;i++){
2604
+ serializeToString(this[i],buf,isHTML,nodeFilter);
2605
+ }
2606
+ return buf.join('');
2440
2607
  }
2441
2608
  };
2442
2609
  function LiveNodeList(node,refresh){
@@ -2492,6 +2659,7 @@ function _addNamedNode(el,list,newAttr,oldAttr){
2492
2659
  }
2493
2660
  }
2494
2661
  function _removeNamedNode(el,list,attr){
2662
+ //console.log('remove attr:'+attr)
2495
2663
  var i = _findNodeIndex(list,attr);
2496
2664
  if(i>=0){
2497
2665
  var lastIndex = list.length-1
@@ -2507,7 +2675,7 @@ function _removeNamedNode(el,list,attr){
2507
2675
  }
2508
2676
  }
2509
2677
  }else{
2510
- throw DOMException(NOT_FOUND_ERR,new Error())
2678
+ throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
2511
2679
  }
2512
2680
  }
2513
2681
  NamedNodeMap.prototype = {
@@ -2517,9 +2685,11 @@ NamedNodeMap.prototype = {
2517
2685
  // if(key.indexOf(':')>0 || key == 'xmlns'){
2518
2686
  // return null;
2519
2687
  // }
2688
+ //console.log()
2520
2689
  var i = this.length;
2521
2690
  while(i--){
2522
2691
  var attr = this[i];
2692
+ //console.log(attr.nodeName,key)
2523
2693
  if(attr.nodeName == key){
2524
2694
  return attr;
2525
2695
  }
@@ -2595,12 +2765,12 @@ DOMImplementation.prototype = {
2595
2765
  // Introduced in DOM Level 2:
2596
2766
  createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
2597
2767
  var doc = new Document();
2768
+ doc.implementation = this;
2769
+ doc.childNodes = new NodeList();
2598
2770
  doc.doctype = doctype;
2599
2771
  if(doctype){
2600
2772
  doc.appendChild(doctype);
2601
2773
  }
2602
- doc.implementation = this;
2603
- doc.childNodes = new NodeList();
2604
2774
  if(qualifiedName){
2605
2775
  var root = doc.createElementNS(namespaceURI,qualifiedName);
2606
2776
  doc.appendChild(root);
@@ -2701,7 +2871,7 @@ Node.prototype = {
2701
2871
  }
2702
2872
  }
2703
2873
  }
2704
- el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2874
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
2705
2875
  }
2706
2876
  return null;
2707
2877
  },
@@ -2716,7 +2886,7 @@ Node.prototype = {
2716
2886
  return map[prefix] ;
2717
2887
  }
2718
2888
  }
2719
- el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2889
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
2720
2890
  }
2721
2891
  return null;
2722
2892
  },
@@ -2901,7 +3071,7 @@ Document.prototype = {
2901
3071
  }
2902
3072
  return newChild;
2903
3073
  }
2904
- if(this.documentElement == null && newChild.nodeType == 1){
3074
+ if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
2905
3075
  this.documentElement = newChild;
2906
3076
  }
2907
3077
 
@@ -2921,7 +3091,7 @@ Document.prototype = {
2921
3091
  getElementById : function(id){
2922
3092
  var rtv = null;
2923
3093
  _visitNode(this.documentElement,function(node){
2924
- if(node.nodeType == 1){
3094
+ if(node.nodeType == ELEMENT_NODE){
2925
3095
  if(node.getAttribute('id') == id){
2926
3096
  rtv = node;
2927
3097
  return true;
@@ -2931,6 +3101,21 @@ Document.prototype = {
2931
3101
  return rtv;
2932
3102
  },
2933
3103
 
3104
+ getElementsByClassName: function(className) {
3105
+ var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
3106
+ return new LiveNodeList(this, function(base) {
3107
+ var ls = [];
3108
+ _visitNode(base.documentElement, function(node) {
3109
+ if(node !== base && node.nodeType == ELEMENT_NODE) {
3110
+ if(pattern.test(node.getAttribute('class'))) {
3111
+ ls.push(node);
3112
+ }
3113
+ }
3114
+ });
3115
+ return ls;
3116
+ });
3117
+ },
3118
+
2934
3119
  //document factory method:
2935
3120
  createElement : function(tagName){
2936
3121
  var node = new Element();
@@ -3070,6 +3255,7 @@ Element.prototype = {
3070
3255
  return this.attributes.setNamedItemNS(newAttr);
3071
3256
  },
3072
3257
  removeAttributeNode : function(oldAttr){
3258
+ //console.log(this == oldAttr.ownerElement)
3073
3259
  return this.attributes.removeNamedItem(oldAttr.nodeName);
3074
3260
  },
3075
3261
  //get real attribute name,and remove it by removeAttributeNode
@@ -3087,7 +3273,7 @@ Element.prototype = {
3087
3273
  },
3088
3274
  setAttributeNS : function(namespaceURI, qualifiedName, value){
3089
3275
  var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
3090
- attr.value = attr.nodeValue = value;
3276
+ attr.value = attr.nodeValue = "" + value;
3091
3277
  this.setAttributeNode(attr)
3092
3278
  },
3093
3279
  getAttributeNodeNS : function(namespaceURI, localName){
@@ -3109,11 +3295,12 @@ Element.prototype = {
3109
3295
  return new LiveNodeList(this,function(base){
3110
3296
  var ls = [];
3111
3297
  _visitNode(base,function(node){
3112
- if(node !== base && node.nodeType === ELEMENT_NODE && node.namespaceURI === namespaceURI && (localName === '*' || node.localName == localName)){
3298
+ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
3113
3299
  ls.push(node);
3114
3300
  }
3115
3301
  });
3116
3302
  return ls;
3303
+
3117
3304
  });
3118
3305
  }
3119
3306
  };
@@ -3145,10 +3332,7 @@ CharacterData.prototype = {
3145
3332
 
3146
3333
  },
3147
3334
  appendChild:function(newChild){
3148
- //if(!(newChild instanceof CharacterData)){
3149
- throw new Error(ExceptionMessage[3])
3150
- //}
3151
- return Node.prototype.appendChild.apply(this,arguments)
3335
+ throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
3152
3336
  },
3153
3337
  deleteData: function(offset, count) {
3154
3338
  this.replaceData(offset,count,"");
@@ -3230,36 +3414,132 @@ function ProcessingInstruction() {
3230
3414
  ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
3231
3415
  _extends(ProcessingInstruction,Node);
3232
3416
  function XMLSerializer(){}
3233
- XMLSerializer.prototype.serializeToString = function(node){
3417
+ XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
3418
+ return nodeSerializeToString.call(node,isHtml,nodeFilter);
3419
+ }
3420
+ Node.prototype.toString = nodeSerializeToString;
3421
+ function nodeSerializeToString(isHtml,nodeFilter){
3234
3422
  var buf = [];
3235
- serializeToString(node,buf);
3423
+ var refNode = this.nodeType == 9 && this.documentElement || this;
3424
+ var prefix = refNode.prefix;
3425
+ var uri = refNode.namespaceURI;
3426
+
3427
+ if(uri && prefix == null){
3428
+ //console.log(prefix)
3429
+ var prefix = refNode.lookupPrefix(uri);
3430
+ if(prefix == null){
3431
+ //isHTML = true;
3432
+ var visibleNamespaces=[
3433
+ {namespace:uri,prefix:null}
3434
+ //{namespace:uri,prefix:''}
3435
+ ]
3436
+ }
3437
+ }
3438
+ serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
3439
+ //console.log('###',this.nodeType,uri,prefix,buf.join(''))
3236
3440
  return buf.join('');
3237
3441
  }
3238
- Node.prototype.toString =function(){
3239
- return XMLSerializer.prototype.serializeToString(this);
3240
- }
3241
- function serializeToString(node,buf){
3442
+ function needNamespaceDefine(node,isHTML, visibleNamespaces) {
3443
+ var prefix = node.prefix||'';
3444
+ var uri = node.namespaceURI;
3445
+ if (!prefix && !uri){
3446
+ return false;
3447
+ }
3448
+ if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
3449
+ || uri == 'http://www.w3.org/2000/xmlns/'){
3450
+ return false;
3451
+ }
3452
+
3453
+ var i = visibleNamespaces.length
3454
+ //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
3455
+ while (i--) {
3456
+ var ns = visibleNamespaces[i];
3457
+ // get namespace prefix
3458
+ //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
3459
+ if (ns.prefix == prefix){
3460
+ return ns.namespace != uri;
3461
+ }
3462
+ }
3463
+ //console.log(isHTML,uri,prefix=='')
3464
+ //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
3465
+ // return false;
3466
+ //}
3467
+ //node.flag = '11111'
3468
+ //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
3469
+ return true;
3470
+ }
3471
+ function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
3472
+ if(nodeFilter){
3473
+ node = nodeFilter(node);
3474
+ if(node){
3475
+ if(typeof node == 'string'){
3476
+ buf.push(node);
3477
+ return;
3478
+ }
3479
+ }else{
3480
+ return;
3481
+ }
3482
+ //buf.sort.apply(attrs, attributeSorter);
3483
+ }
3242
3484
  switch(node.nodeType){
3243
3485
  case ELEMENT_NODE:
3486
+ if (!visibleNamespaces) visibleNamespaces = [];
3487
+ var startVisibleNamespaces = visibleNamespaces.length;
3244
3488
  var attrs = node.attributes;
3245
3489
  var len = attrs.length;
3246
3490
  var child = node.firstChild;
3247
3491
  var nodeName = node.tagName;
3248
- var isHTML = htmlns === node.namespaceURI
3492
+
3493
+ isHTML = (htmlns === node.namespaceURI) ||isHTML
3249
3494
  buf.push('<',nodeName);
3495
+
3496
+
3497
+
3250
3498
  for(var i=0;i<len;i++){
3251
- serializeToString(attrs.item(i),buf,isHTML);
3499
+ // add namespaces for attributes
3500
+ var attr = attrs.item(i);
3501
+ if (attr.prefix == 'xmlns') {
3502
+ visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
3503
+ }else if(attr.nodeName == 'xmlns'){
3504
+ visibleNamespaces.push({ prefix: '', namespace: attr.value });
3505
+ }
3506
+ }
3507
+ for(var i=0;i<len;i++){
3508
+ var attr = attrs.item(i);
3509
+ if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
3510
+ var prefix = attr.prefix||'';
3511
+ var uri = attr.namespaceURI;
3512
+ var ns = prefix ? ' xmlns:' + prefix : " xmlns";
3513
+ buf.push(ns, '="' , uri , '"');
3514
+ visibleNamespaces.push({ prefix: prefix, namespace:uri });
3515
+ }
3516
+ serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
3252
3517
  }
3518
+ // add namespace for current node
3519
+ if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
3520
+ var prefix = node.prefix||'';
3521
+ var uri = node.namespaceURI;
3522
+ var ns = prefix ? ' xmlns:' + prefix : " xmlns";
3523
+ buf.push(ns, '="' , uri , '"');
3524
+ visibleNamespaces.push({ prefix: prefix, namespace:uri });
3525
+ }
3526
+
3253
3527
  if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
3254
3528
  buf.push('>');
3255
3529
  //if is cdata child node
3256
3530
  if(isHTML && /^script$/i.test(nodeName)){
3257
- if(child){
3258
- buf.push(child.data);
3531
+ while(child){
3532
+ if(child.data){
3533
+ buf.push(child.data);
3534
+ }else{
3535
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
3536
+ }
3537
+ child = child.nextSibling;
3259
3538
  }
3260
- }else{
3539
+ }else
3540
+ {
3261
3541
  while(child){
3262
- serializeToString(child,buf);
3542
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
3263
3543
  child = child.nextSibling;
3264
3544
  }
3265
3545
  }
@@ -3267,19 +3547,39 @@ function serializeToString(node,buf){
3267
3547
  }else{
3268
3548
  buf.push('/>');
3269
3549
  }
3550
+ // remove added visible namespaces
3551
+ //visibleNamespaces.length = startVisibleNamespaces;
3270
3552
  return;
3271
3553
  case DOCUMENT_NODE:
3272
3554
  case DOCUMENT_FRAGMENT_NODE:
3273
3555
  var child = node.firstChild;
3274
3556
  while(child){
3275
- serializeToString(child,buf);
3557
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
3276
3558
  child = child.nextSibling;
3277
3559
  }
3278
3560
  return;
3279
3561
  case ATTRIBUTE_NODE:
3280
- return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
3562
+ return buf.push(' ',node.name,'="',node.value.replace(/[&"]/g,_xmlEncoder),'"');
3281
3563
  case TEXT_NODE:
3282
- return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
3564
+ /**
3565
+ * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
3566
+ * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
3567
+ * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
3568
+ * `&amp;` and `&lt;` respectively.
3569
+ * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
3570
+ * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
3571
+ * when that string is not marking the end of a CDATA section.
3572
+ *
3573
+ * In the content of elements, character data is any string of characters
3574
+ * which does not contain the start-delimiter of any markup
3575
+ * and does not include the CDATA-section-close delimiter, `]]>`.
3576
+ *
3577
+ * @see https://www.w3.org/TR/xml/#NT-CharData
3578
+ */
3579
+ return buf.push(node.data
3580
+ .replace(/[<&]/g,_xmlEncoder)
3581
+ .replace(/]]>/g, ']]&gt;')
3582
+ );
3283
3583
  case CDATA_SECTION_NODE:
3284
3584
  return buf.push( '<![CDATA[',node.data,']]>');
3285
3585
  case COMMENT_NODE:
@@ -3289,13 +3589,13 @@ function serializeToString(node,buf){
3289
3589
  var sysid = node.systemId;
3290
3590
  buf.push('<!DOCTYPE ',node.name);
3291
3591
  if(pubid){
3292
- buf.push(' PUBLIC "',pubid);
3592
+ buf.push(' PUBLIC ', pubid);
3293
3593
  if (sysid && sysid!='.') {
3294
- buf.push( '" "',sysid);
3594
+ buf.push(' ', sysid);
3295
3595
  }
3296
- buf.push('">');
3596
+ buf.push('>');
3297
3597
  }else if(sysid && sysid!='.'){
3298
- buf.push(' SYSTEM "',sysid,'">');
3598
+ buf.push(' SYSTEM ', sysid, '>');
3299
3599
  }else{
3300
3600
  var sub = node.internalSubset;
3301
3601
  if(sub){
@@ -3417,8 +3717,8 @@ try{
3417
3717
  },
3418
3718
  set:function(data){
3419
3719
  switch(this.nodeType){
3420
- case 1:
3421
- case 11:
3720
+ case ELEMENT_NODE:
3721
+ case DOCUMENT_FRAGMENT_NODE:
3422
3722
  while(this.firstChild){
3423
3723
  this.removeChild(this.firstChild);
3424
3724
  }
@@ -3429,7 +3729,7 @@ try{
3429
3729
  default:
3430
3730
  //TODO:
3431
3731
  this.data = data;
3432
- this.value = value;
3732
+ this.value = data;
3433
3733
  this.nodeValue = data;
3434
3734
  }
3435
3735
  }
@@ -3437,8 +3737,8 @@ try{
3437
3737
 
3438
3738
  function getTextContent(node){
3439
3739
  switch(node.nodeType){
3440
- case 1:
3441
- case 11:
3740
+ case ELEMENT_NODE:
3741
+ case DOCUMENT_FRAGMENT_NODE:
3442
3742
  var buf = [];
3443
3743
  node = node.firstChild;
3444
3744
  while(node){
@@ -3460,596 +3760,905 @@ try{
3460
3760
  }catch(e){//ie8
3461
3761
  }
3462
3762
 
3463
- if(typeof require == 'function'){
3763
+ //if(typeof require == 'function'){
3764
+ exports.Node = Node;
3765
+ exports.DOMException = DOMException;
3464
3766
  exports.DOMImplementation = DOMImplementation;
3465
3767
  exports.XMLSerializer = XMLSerializer;
3768
+ //}
3769
+
3770
+ },{}],7:[function(require,module,exports){
3771
+ exports.entityMap = {
3772
+ lt: '<',
3773
+ gt: '>',
3774
+ amp: '&',
3775
+ quot: '"',
3776
+ apos: "'",
3777
+ Agrave: "À",
3778
+ Aacute: "Á",
3779
+ Acirc: "Â",
3780
+ Atilde: "Ã",
3781
+ Auml: "Ä",
3782
+ Aring: "Å",
3783
+ AElig: "Æ",
3784
+ Ccedil: "Ç",
3785
+ Egrave: "È",
3786
+ Eacute: "É",
3787
+ Ecirc: "Ê",
3788
+ Euml: "Ë",
3789
+ Igrave: "Ì",
3790
+ Iacute: "Í",
3791
+ Icirc: "Î",
3792
+ Iuml: "Ï",
3793
+ ETH: "Ð",
3794
+ Ntilde: "Ñ",
3795
+ Ograve: "Ò",
3796
+ Oacute: "Ó",
3797
+ Ocirc: "Ô",
3798
+ Otilde: "Õ",
3799
+ Ouml: "Ö",
3800
+ Oslash: "Ø",
3801
+ Ugrave: "Ù",
3802
+ Uacute: "Ú",
3803
+ Ucirc: "Û",
3804
+ Uuml: "Ü",
3805
+ Yacute: "Ý",
3806
+ THORN: "Þ",
3807
+ szlig: "ß",
3808
+ agrave: "à",
3809
+ aacute: "á",
3810
+ acirc: "â",
3811
+ atilde: "ã",
3812
+ auml: "ä",
3813
+ aring: "å",
3814
+ aelig: "æ",
3815
+ ccedil: "ç",
3816
+ egrave: "è",
3817
+ eacute: "é",
3818
+ ecirc: "ê",
3819
+ euml: "ë",
3820
+ igrave: "ì",
3821
+ iacute: "í",
3822
+ icirc: "î",
3823
+ iuml: "ï",
3824
+ eth: "ð",
3825
+ ntilde: "ñ",
3826
+ ograve: "ò",
3827
+ oacute: "ó",
3828
+ ocirc: "ô",
3829
+ otilde: "õ",
3830
+ ouml: "ö",
3831
+ oslash: "ø",
3832
+ ugrave: "ù",
3833
+ uacute: "ú",
3834
+ ucirc: "û",
3835
+ uuml: "ü",
3836
+ yacute: "ý",
3837
+ thorn: "þ",
3838
+ yuml: "ÿ",
3839
+ nbsp: "\u00a0",
3840
+ iexcl: "¡",
3841
+ cent: "¢",
3842
+ pound: "£",
3843
+ curren: "¤",
3844
+ yen: "¥",
3845
+ brvbar: "¦",
3846
+ sect: "§",
3847
+ uml: "¨",
3848
+ copy: "©",
3849
+ ordf: "ª",
3850
+ laquo: "«",
3851
+ not: "¬",
3852
+ shy: "­­",
3853
+ reg: "®",
3854
+ macr: "¯",
3855
+ deg: "°",
3856
+ plusmn: "±",
3857
+ sup2: "²",
3858
+ sup3: "³",
3859
+ acute: "´",
3860
+ micro: "µ",
3861
+ para: "¶",
3862
+ middot: "·",
3863
+ cedil: "¸",
3864
+ sup1: "¹",
3865
+ ordm: "º",
3866
+ raquo: "»",
3867
+ frac14: "¼",
3868
+ frac12: "½",
3869
+ frac34: "¾",
3870
+ iquest: "¿",
3871
+ times: "×",
3872
+ divide: "÷",
3873
+ forall: "∀",
3874
+ part: "∂",
3875
+ exist: "∃",
3876
+ empty: "∅",
3877
+ nabla: "∇",
3878
+ isin: "∈",
3879
+ notin: "∉",
3880
+ ni: "∋",
3881
+ prod: "∏",
3882
+ sum: "∑",
3883
+ minus: "−",
3884
+ lowast: "∗",
3885
+ radic: "√",
3886
+ prop: "∝",
3887
+ infin: "∞",
3888
+ ang: "∠",
3889
+ and: "∧",
3890
+ or: "∨",
3891
+ cap: "∩",
3892
+ cup: "∪",
3893
+ 'int': "∫",
3894
+ there4: "∴",
3895
+ sim: "∼",
3896
+ cong: "≅",
3897
+ asymp: "≈",
3898
+ ne: "≠",
3899
+ equiv: "≡",
3900
+ le: "≤",
3901
+ ge: "≥",
3902
+ sub: "⊂",
3903
+ sup: "⊃",
3904
+ nsub: "⊄",
3905
+ sube: "⊆",
3906
+ supe: "⊇",
3907
+ oplus: "⊕",
3908
+ otimes: "⊗",
3909
+ perp: "⊥",
3910
+ sdot: "⋅",
3911
+ Alpha: "Α",
3912
+ Beta: "Β",
3913
+ Gamma: "Γ",
3914
+ Delta: "Δ",
3915
+ Epsilon: "Ε",
3916
+ Zeta: "Ζ",
3917
+ Eta: "Η",
3918
+ Theta: "Θ",
3919
+ Iota: "Ι",
3920
+ Kappa: "Κ",
3921
+ Lambda: "Λ",
3922
+ Mu: "Μ",
3923
+ Nu: "Ν",
3924
+ Xi: "Ξ",
3925
+ Omicron: "Ο",
3926
+ Pi: "Π",
3927
+ Rho: "Ρ",
3928
+ Sigma: "Σ",
3929
+ Tau: "Τ",
3930
+ Upsilon: "Υ",
3931
+ Phi: "Φ",
3932
+ Chi: "Χ",
3933
+ Psi: "Ψ",
3934
+ Omega: "Ω",
3935
+ alpha: "α",
3936
+ beta: "β",
3937
+ gamma: "γ",
3938
+ delta: "δ",
3939
+ epsilon: "ε",
3940
+ zeta: "ζ",
3941
+ eta: "η",
3942
+ theta: "θ",
3943
+ iota: "ι",
3944
+ kappa: "κ",
3945
+ lambda: "λ",
3946
+ mu: "μ",
3947
+ nu: "ν",
3948
+ xi: "ξ",
3949
+ omicron: "ο",
3950
+ pi: "π",
3951
+ rho: "ρ",
3952
+ sigmaf: "ς",
3953
+ sigma: "σ",
3954
+ tau: "τ",
3955
+ upsilon: "υ",
3956
+ phi: "φ",
3957
+ chi: "χ",
3958
+ psi: "ψ",
3959
+ omega: "ω",
3960
+ thetasym: "ϑ",
3961
+ upsih: "ϒ",
3962
+ piv: "ϖ",
3963
+ OElig: "Œ",
3964
+ oelig: "œ",
3965
+ Scaron: "Š",
3966
+ scaron: "š",
3967
+ Yuml: "Ÿ",
3968
+ fnof: "ƒ",
3969
+ circ: "ˆ",
3970
+ tilde: "˜",
3971
+ ensp: " ",
3972
+ emsp: " ",
3973
+ thinsp: " ",
3974
+ zwnj: "‌",
3975
+ zwj: "‍",
3976
+ lrm: "‎",
3977
+ rlm: "‏",
3978
+ ndash: "–",
3979
+ mdash: "—",
3980
+ lsquo: "‘",
3981
+ rsquo: "’",
3982
+ sbquo: "‚",
3983
+ ldquo: "“",
3984
+ rdquo: "”",
3985
+ bdquo: "„",
3986
+ dagger: "†",
3987
+ Dagger: "‡",
3988
+ bull: "•",
3989
+ hellip: "…",
3990
+ permil: "‰",
3991
+ prime: "′",
3992
+ Prime: "″",
3993
+ lsaquo: "‹",
3994
+ rsaquo: "›",
3995
+ oline: "‾",
3996
+ euro: "€",
3997
+ trade: "™",
3998
+ larr: "←",
3999
+ uarr: "↑",
4000
+ rarr: "→",
4001
+ darr: "↓",
4002
+ harr: "↔",
4003
+ crarr: "↵",
4004
+ lceil: "⌈",
4005
+ rceil: "⌉",
4006
+ lfloor: "⌊",
4007
+ rfloor: "⌋",
4008
+ loz: "◊",
4009
+ spades: "♠",
4010
+ clubs: "♣",
4011
+ hearts: "♥",
4012
+ diams: "♦"
4013
+ };
4014
+
4015
+ },{}],8:[function(require,module,exports){
4016
+ //[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]
4017
+ //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
4018
+ //[5] Name ::= NameStartChar (NameChar)*
4019
+ 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
4020
+ var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
4021
+ var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
4022
+ //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
4023
+ //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(',')
4024
+
4025
+ //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
4026
+ //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
4027
+ var S_TAG = 0;//tag name offerring
4028
+ var S_ATTR = 1;//attr name offerring
4029
+ var S_ATTR_SPACE=2;//attr name end and space offer
4030
+ var S_EQ = 3;//=space?
4031
+ var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
4032
+ var S_ATTR_END = 5;//attr value end and no space(quot end)
4033
+ var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
4034
+ var S_TAG_CLOSE = 7;//closed el<el />
4035
+
4036
+ /**
4037
+ * Creates an error that will not be caught by XMLReader aka the SAX parser.
4038
+ *
4039
+ * @param {string} message
4040
+ * @param {any?} locator Optional, can provide details about the location in the source
4041
+ * @constructor
4042
+ */
4043
+ function ParseError(message, locator) {
4044
+ this.message = message
4045
+ this.locator = locator
4046
+ if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
4047
+ }
4048
+ ParseError.prototype = new Error();
4049
+ ParseError.prototype.name = ParseError.name
4050
+
4051
+ function XMLReader(){
4052
+
4053
+ }
4054
+
4055
+ XMLReader.prototype = {
4056
+ parse:function(source,defaultNSMap,entityMap){
4057
+ var domBuilder = this.domBuilder;
4058
+ domBuilder.startDocument();
4059
+ _copy(defaultNSMap ,defaultNSMap = {})
4060
+ parse(source,defaultNSMap,entityMap,
4061
+ domBuilder,this.errorHandler);
4062
+ domBuilder.endDocument();
4063
+ }
4064
+ }
4065
+ function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
4066
+ function fixedFromCharCode(code) {
4067
+ // String.prototype.fromCharCode does not supports
4068
+ // > 2 bytes unicode chars directly
4069
+ if (code > 0xffff) {
4070
+ code -= 0x10000;
4071
+ var surrogate1 = 0xd800 + (code >> 10)
4072
+ , surrogate2 = 0xdc00 + (code & 0x3ff);
4073
+
4074
+ return String.fromCharCode(surrogate1, surrogate2);
4075
+ } else {
4076
+ return String.fromCharCode(code);
4077
+ }
4078
+ }
4079
+ function entityReplacer(a){
4080
+ var k = a.slice(1,-1);
4081
+ if(k in entityMap){
4082
+ return entityMap[k];
4083
+ }else if(k.charAt(0) === '#'){
4084
+ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
4085
+ }else{
4086
+ errorHandler.error('entity not found:'+a);
4087
+ return a;
4088
+ }
4089
+ }
4090
+ function appendText(end){//has some bugs
4091
+ if(end>start){
4092
+ var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
4093
+ locator&&position(start);
4094
+ domBuilder.characters(xt,0,end-start);
4095
+ start = end
4096
+ }
4097
+ }
4098
+ function position(p,m){
4099
+ while(p>=lineEnd && (m = linePattern.exec(source))){
4100
+ lineStart = m.index;
4101
+ lineEnd = lineStart + m[0].length;
4102
+ locator.lineNumber++;
4103
+ //console.log('line++:',locator,startPos,endPos)
4104
+ }
4105
+ locator.columnNumber = p-lineStart+1;
4106
+ }
4107
+ var lineStart = 0;
4108
+ var lineEnd = 0;
4109
+ var linePattern = /.*(?:\r\n?|\n)|.*$/g
4110
+ var locator = domBuilder.locator;
4111
+
4112
+ var parseStack = [{currentNSMap:defaultNSMapCopy}]
4113
+ var closeMap = {};
4114
+ var start = 0;
4115
+ while(true){
4116
+ try{
4117
+ var tagStart = source.indexOf('<',start);
4118
+ if(tagStart<0){
4119
+ if(!source.substr(start).match(/^\s*$/)){
4120
+ var doc = domBuilder.doc;
4121
+ var text = doc.createTextNode(source.substr(start));
4122
+ doc.appendChild(text);
4123
+ domBuilder.currentElement = text;
4124
+ }
4125
+ return;
4126
+ }
4127
+ if(tagStart>start){
4128
+ appendText(tagStart);
4129
+ }
4130
+ switch(source.charAt(tagStart+1)){
4131
+ case '/':
4132
+ var end = source.indexOf('>',tagStart+3);
4133
+ var tagName = source.substring(tagStart+2,end);
4134
+ var config = parseStack.pop();
4135
+ if(end<0){
4136
+
4137
+ tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
4138
+ //console.error('#@@@@@@'+tagName)
4139
+ errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
4140
+ end = tagStart+1+tagName.length;
4141
+ }else if(tagName.match(/\s</)){
4142
+ tagName = tagName.replace(/[\s<].*/,'');
4143
+ errorHandler.error("end tag name: "+tagName+' maybe not complete');
4144
+ end = tagStart+1+tagName.length;
4145
+ }
4146
+ //console.error(parseStack.length,parseStack)
4147
+ //console.error(config);
4148
+ var localNSMap = config.localNSMap;
4149
+ var endMatch = config.tagName == tagName;
4150
+ var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
4151
+ if(endIgnoreCaseMach){
4152
+ domBuilder.endElement(config.uri,config.localName,tagName);
4153
+ if(localNSMap){
4154
+ for(var prefix in localNSMap){
4155
+ domBuilder.endPrefixMapping(prefix) ;
4156
+ }
4157
+ }
4158
+ if(!endMatch){
4159
+ errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
4160
+ }
4161
+ }else{
4162
+ parseStack.push(config)
4163
+ }
4164
+
4165
+ end++;
4166
+ break;
4167
+ // end elment
4168
+ case '?':// <?...?>
4169
+ locator&&position(tagStart);
4170
+ end = parseInstruction(source,tagStart,domBuilder);
4171
+ break;
4172
+ case '!':// <!doctype,<![CDATA,<!--
4173
+ locator&&position(tagStart);
4174
+ end = parseDCC(source,tagStart,domBuilder,errorHandler);
4175
+ break;
4176
+ default:
4177
+ locator&&position(tagStart);
4178
+ var el = new ElementAttributes();
4179
+ var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
4180
+ //elStartEnd
4181
+ var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
4182
+ var len = el.length;
4183
+
4184
+
4185
+ if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
4186
+ el.closed = true;
4187
+ if(!entityMap.nbsp){
4188
+ errorHandler.warning('unclosed xml attribute');
4189
+ }
4190
+ }
4191
+ if(locator && len){
4192
+ var locator2 = copyLocator(locator,{});
4193
+ //try{//attribute position fixed
4194
+ for(var i = 0;i<len;i++){
4195
+ var a = el[i];
4196
+ position(a.offset);
4197
+ a.locator = copyLocator(locator,{});
4198
+ }
4199
+ //}catch(e){console.error('@@@@@'+e)}
4200
+ domBuilder.locator = locator2
4201
+ if(appendElement(el,domBuilder,currentNSMap)){
4202
+ parseStack.push(el)
4203
+ }
4204
+ domBuilder.locator = locator;
4205
+ }else{
4206
+ if(appendElement(el,domBuilder,currentNSMap)){
4207
+ parseStack.push(el)
4208
+ }
4209
+ }
4210
+
4211
+
4212
+
4213
+ if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
4214
+ end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
4215
+ }else{
4216
+ end++;
4217
+ }
4218
+ }
4219
+ }catch(e){
4220
+ if (e instanceof ParseError) {
4221
+ throw e;
4222
+ }
4223
+ errorHandler.error('element parse error: '+e)
4224
+ end = -1;
4225
+ }
4226
+ if(end>start){
4227
+ start = end;
4228
+ }else{
4229
+ //TODO: 这里有可能sax回退,有位置错误风险
4230
+ appendText(Math.max(tagStart,start)+1);
4231
+ }
4232
+ }
4233
+ }
4234
+ function copyLocator(f,t){
4235
+ t.lineNumber = f.lineNumber;
4236
+ t.columnNumber = f.columnNumber;
4237
+ return t;
4238
+ }
4239
+
4240
+ /**
4241
+ * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
4242
+ * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
4243
+ */
4244
+ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
4245
+
4246
+ /**
4247
+ * @param {string} qname
4248
+ * @param {string} value
4249
+ * @param {number} startIndex
4250
+ */
4251
+ function addAttribute(qname, value, startIndex) {
4252
+ if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined')
4253
+ el.addValue(qname, value, startIndex)
4254
+ }
4255
+ var attrName;
4256
+ var value;
4257
+ var p = ++start;
4258
+ var s = S_TAG;//status
4259
+ while(true){
4260
+ var c = source.charAt(p);
4261
+ switch(c){
4262
+ case '=':
4263
+ if(s === S_ATTR){//attrName
4264
+ attrName = source.slice(start,p);
4265
+ s = S_EQ;
4266
+ }else if(s === S_ATTR_SPACE){
4267
+ s = S_EQ;
4268
+ }else{
4269
+ //fatalError: equal must after attrName or space after attrName
4270
+ throw new Error('attribute equal must after attrName'); // No known test case
4271
+ }
4272
+ break;
4273
+ case '\'':
4274
+ case '"':
4275
+ if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
4276
+ ){//equal
4277
+ if(s === S_ATTR){
4278
+ errorHandler.warning('attribute value must after "="')
4279
+ attrName = source.slice(start,p)
4280
+ }
4281
+ start = p+1;
4282
+ p = source.indexOf(c,start)
4283
+ if(p>0){
4284
+ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
4285
+ addAttribute(attrName, value, start-1);
4286
+ s = S_ATTR_END;
4287
+ }else{
4288
+ //fatalError: no end quot match
4289
+ throw new Error('attribute value no end \''+c+'\' match');
4290
+ }
4291
+ }else if(s == S_ATTR_NOQUOT_VALUE){
4292
+ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
4293
+ //console.log(attrName,value,start,p)
4294
+ addAttribute(attrName, value, start);
4295
+ //console.dir(el)
4296
+ errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
4297
+ start = p+1;
4298
+ s = S_ATTR_END
4299
+ }else{
4300
+ //fatalError: no equal before
4301
+ throw new Error('attribute value must after "="'); // No known test case
4302
+ }
4303
+ break;
4304
+ case '/':
4305
+ switch(s){
4306
+ case S_TAG:
4307
+ el.setTagName(source.slice(start,p));
4308
+ case S_ATTR_END:
4309
+ case S_TAG_SPACE:
4310
+ case S_TAG_CLOSE:
4311
+ s =S_TAG_CLOSE;
4312
+ el.closed = true;
4313
+ case S_ATTR_NOQUOT_VALUE:
4314
+ case S_ATTR:
4315
+ case S_ATTR_SPACE:
4316
+ break;
4317
+ //case S_EQ:
4318
+ default:
4319
+ throw new Error("attribute invalid close char('/')") // No known test case
4320
+ }
4321
+ break;
4322
+ case ''://end document
4323
+ errorHandler.error('unexpected end of input');
4324
+ if(s == S_TAG){
4325
+ el.setTagName(source.slice(start,p));
4326
+ }
4327
+ return p;
4328
+ case '>':
4329
+ switch(s){
4330
+ case S_TAG:
4331
+ el.setTagName(source.slice(start,p));
4332
+ case S_ATTR_END:
4333
+ case S_TAG_SPACE:
4334
+ case S_TAG_CLOSE:
4335
+ break;//normal
4336
+ case S_ATTR_NOQUOT_VALUE://Compatible state
4337
+ case S_ATTR:
4338
+ value = source.slice(start,p);
4339
+ if(value.slice(-1) === '/'){
4340
+ el.closed = true;
4341
+ value = value.slice(0,-1)
4342
+ }
4343
+ case S_ATTR_SPACE:
4344
+ if(s === S_ATTR_SPACE){
4345
+ value = attrName;
4346
+ }
4347
+ if(s == S_ATTR_NOQUOT_VALUE){
4348
+ errorHandler.warning('attribute "'+value+'" missed quot(")!');
4349
+ addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start)
4350
+ }else{
4351
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
4352
+ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
4353
+ }
4354
+ addAttribute(value, value, start)
4355
+ }
4356
+ break;
4357
+ case S_EQ:
4358
+ throw new Error('attribute value missed!!');
4359
+ }
4360
+ // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
4361
+ return p;
4362
+ /*xml space '\x20' | #x9 | #xD | #xA; */
4363
+ case '\u0080':
4364
+ c = ' ';
4365
+ default:
4366
+ if(c<= ' '){//space
4367
+ switch(s){
4368
+ case S_TAG:
4369
+ el.setTagName(source.slice(start,p));//tagName
4370
+ s = S_TAG_SPACE;
4371
+ break;
4372
+ case S_ATTR:
4373
+ attrName = source.slice(start,p)
4374
+ s = S_ATTR_SPACE;
4375
+ break;
4376
+ case S_ATTR_NOQUOT_VALUE:
4377
+ var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
4378
+ errorHandler.warning('attribute "'+value+'" missed quot(")!!');
4379
+ addAttribute(attrName, value, start)
4380
+ case S_ATTR_END:
4381
+ s = S_TAG_SPACE;
4382
+ break;
4383
+ //case S_TAG_SPACE:
4384
+ //case S_EQ:
4385
+ //case S_ATTR_SPACE:
4386
+ // void();break;
4387
+ //case S_TAG_CLOSE:
4388
+ //ignore warning
4389
+ }
4390
+ }else{//not space
4391
+ //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
4392
+ //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
4393
+ switch(s){
4394
+ //case S_TAG:void();break;
4395
+ //case S_ATTR:void();break;
4396
+ //case S_ATTR_NOQUOT_VALUE:void();break;
4397
+ case S_ATTR_SPACE:
4398
+ var tagName = el.tagName;
4399
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
4400
+ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
4401
+ }
4402
+ addAttribute(attrName, attrName, start);
4403
+ start = p;
4404
+ s = S_ATTR;
4405
+ break;
4406
+ case S_ATTR_END:
4407
+ errorHandler.warning('attribute space is required"'+attrName+'"!!')
4408
+ case S_TAG_SPACE:
4409
+ s = S_ATTR;
4410
+ start = p;
4411
+ break;
4412
+ case S_EQ:
4413
+ s = S_ATTR_NOQUOT_VALUE;
4414
+ start = p;
4415
+ break;
4416
+ case S_TAG_CLOSE:
4417
+ throw new Error("elements closed character '/' and '>' must be connected to");
4418
+ }
4419
+ }
4420
+ }//end outer switch
4421
+ //console.log('p++',p)
4422
+ p++;
4423
+ }
4424
+ }
4425
+ /**
4426
+ * @return true if has new namespace define
4427
+ */
4428
+ function appendElement(el,domBuilder,currentNSMap){
4429
+ var tagName = el.tagName;
4430
+ var localNSMap = null;
4431
+ //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
4432
+ var i = el.length;
4433
+ while(i--){
4434
+ var a = el[i];
4435
+ var qName = a.qName;
4436
+ var value = a.value;
4437
+ var nsp = qName.indexOf(':');
4438
+ if(nsp>0){
4439
+ var prefix = a.prefix = qName.slice(0,nsp);
4440
+ var localName = qName.slice(nsp+1);
4441
+ var nsPrefix = prefix === 'xmlns' && localName
4442
+ }else{
4443
+ localName = qName;
4444
+ prefix = null
4445
+ nsPrefix = qName === 'xmlns' && ''
4446
+ }
4447
+ //can not set prefix,because prefix !== ''
4448
+ a.localName = localName ;
4449
+ //prefix == null for no ns prefix attribute
4450
+ if(nsPrefix !== false){//hack!!
4451
+ if(localNSMap == null){
4452
+ localNSMap = {}
4453
+ //console.log(currentNSMap,0)
4454
+ _copy(currentNSMap,currentNSMap={})
4455
+ //console.log(currentNSMap,1)
4456
+ }
4457
+ currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
4458
+ a.uri = 'http://www.w3.org/2000/xmlns/'
4459
+ domBuilder.startPrefixMapping(nsPrefix, value)
4460
+ }
4461
+ }
4462
+ var i = el.length;
4463
+ while(i--){
4464
+ a = el[i];
4465
+ var prefix = a.prefix;
4466
+ if(prefix){//no prefix attribute has no namespace
4467
+ if(prefix === 'xml'){
4468
+ a.uri = 'http://www.w3.org/XML/1998/namespace';
4469
+ }if(prefix !== 'xmlns'){
4470
+ a.uri = currentNSMap[prefix || '']
4471
+
4472
+ //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
4473
+ }
4474
+ }
4475
+ }
4476
+ var nsp = tagName.indexOf(':');
4477
+ if(nsp>0){
4478
+ prefix = el.prefix = tagName.slice(0,nsp);
4479
+ localName = el.localName = tagName.slice(nsp+1);
4480
+ }else{
4481
+ prefix = null;//important!!
4482
+ localName = el.localName = tagName;
4483
+ }
4484
+ //no prefix element has default namespace
4485
+ var ns = el.uri = currentNSMap[prefix || ''];
4486
+ domBuilder.startElement(ns,localName,tagName,el);
4487
+ //endPrefixMapping and startPrefixMapping have not any help for dom builder
4488
+ //localNSMap = null
4489
+ if(el.closed){
4490
+ domBuilder.endElement(ns,localName,tagName);
4491
+ if(localNSMap){
4492
+ for(prefix in localNSMap){
4493
+ domBuilder.endPrefixMapping(prefix)
4494
+ }
4495
+ }
4496
+ }else{
4497
+ el.currentNSMap = currentNSMap;
4498
+ el.localNSMap = localNSMap;
4499
+ //parseStack.push(el);
4500
+ return true;
4501
+ }
4502
+ }
4503
+ function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
4504
+ if(/^(?:script|textarea)$/i.test(tagName)){
4505
+ var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
4506
+ var text = source.substring(elStartEnd+1,elEndStart);
4507
+ if(/[&<]/.test(text)){
4508
+ if(/^script$/i.test(tagName)){
4509
+ //if(!/\]\]>/.test(text)){
4510
+ //lexHandler.startCDATA();
4511
+ domBuilder.characters(text,0,text.length);
4512
+ //lexHandler.endCDATA();
4513
+ return elEndStart;
4514
+ //}
4515
+ }//}else{//text area
4516
+ text = text.replace(/&#?\w+;/g,entityReplacer);
4517
+ domBuilder.characters(text,0,text.length);
4518
+ return elEndStart;
4519
+ //}
4520
+
4521
+ }
4522
+ }
4523
+ return elStartEnd+1;
4524
+ }
4525
+ function fixSelfClosed(source,elStartEnd,tagName,closeMap){
4526
+ //if(tagName in closeMap){
4527
+ var pos = closeMap[tagName];
4528
+ if(pos == null){
4529
+ //console.log(tagName)
4530
+ pos = source.lastIndexOf('</'+tagName+'>')
4531
+ if(pos<elStartEnd){//忘记闭合
4532
+ pos = source.lastIndexOf('</'+tagName)
4533
+ }
4534
+ closeMap[tagName] =pos
4535
+ }
4536
+ return pos<elStartEnd;
4537
+ //}
4538
+ }
4539
+ function _copy(source,target){
4540
+ for(var n in source){target[n] = source[n]}
4541
+ }
4542
+ function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
4543
+ var next= source.charAt(start+2)
4544
+ switch(next){
4545
+ case '-':
4546
+ if(source.charAt(start + 3) === '-'){
4547
+ var end = source.indexOf('-->',start+4);
4548
+ //append comment source.substring(4,end)//<!--
4549
+ if(end>start){
4550
+ domBuilder.comment(source,start+4,end-start-4);
4551
+ return end+3;
4552
+ }else{
4553
+ errorHandler.error("Unclosed comment");
4554
+ return -1;
4555
+ }
4556
+ }else{
4557
+ //error
4558
+ return -1;
4559
+ }
4560
+ default:
4561
+ if(source.substr(start+3,6) == 'CDATA['){
4562
+ var end = source.indexOf(']]>',start+9);
4563
+ domBuilder.startCDATA();
4564
+ domBuilder.characters(source,start+9,end-start-9);
4565
+ domBuilder.endCDATA()
4566
+ return end+3;
4567
+ }
4568
+ //<!DOCTYPE
4569
+ //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
4570
+ var matchs = split(source,start);
4571
+ var len = matchs.length;
4572
+ if(len>1 && /!doctype/i.test(matchs[0][0])){
4573
+ var name = matchs[1][0];
4574
+ var pubid = false;
4575
+ var sysid = false;
4576
+ if(len>3){
4577
+ if(/^public$/i.test(matchs[2][0])){
4578
+ pubid = matchs[3][0];
4579
+ sysid = len>4 && matchs[4][0];
4580
+ }else if(/^system$/i.test(matchs[2][0])){
4581
+ sysid = matchs[3][0];
4582
+ }
4583
+ }
4584
+ var lastMatch = matchs[len-1]
4585
+ domBuilder.startDTD(name, pubid, sysid);
4586
+ domBuilder.endDTD();
4587
+
4588
+ return lastMatch.index+lastMatch[0].length
4589
+ }
4590
+ }
4591
+ return -1;
4592
+ }
4593
+
4594
+
4595
+
4596
+ function parseInstruction(source,start,domBuilder){
4597
+ var end = source.indexOf('?>',start);
4598
+ if(end){
4599
+ var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
4600
+ if(match){
4601
+ var len = match[0].length;
4602
+ domBuilder.processingInstruction(match[1], match[2]) ;
4603
+ return end+2;
4604
+ }else{//error
4605
+ return -1;
4606
+ }
4607
+ }
4608
+ return -1;
4609
+ }
4610
+
4611
+ function ElementAttributes(){
4612
+ this.attributeNames = {}
4613
+ }
4614
+ ElementAttributes.prototype = {
4615
+ setTagName:function(tagName){
4616
+ if(!tagNamePattern.test(tagName)){
4617
+ throw new Error('invalid tagName:'+tagName)
4618
+ }
4619
+ this.tagName = tagName
4620
+ },
4621
+ addValue:function(qName, value, offset) {
4622
+ if(!tagNamePattern.test(qName)){
4623
+ throw new Error('invalid attribute:'+qName)
4624
+ }
4625
+ this.attributeNames[qName] = this.length;
4626
+ this[this.length++] = {qName:qName,value:value,offset:offset}
4627
+ },
4628
+ length:0,
4629
+ getLocalName:function(i){return this[i].localName},
4630
+ getLocator:function(i){return this[i].locator},
4631
+ getQName:function(i){return this[i].qName},
4632
+ getURI:function(i){return this[i].uri},
4633
+ getValue:function(i){return this[i].value}
4634
+ // ,getIndex:function(uri, localName)){
4635
+ // if(localName){
4636
+ //
4637
+ // }else{
4638
+ // var qName = uri
4639
+ // }
4640
+ // },
4641
+ // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
4642
+ // getType:function(uri,localName){}
4643
+ // getType:function(i){},
4644
+ }
4645
+
4646
+
4647
+
4648
+ function split(source,start){
4649
+ var match;
4650
+ var buf = [];
4651
+ var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
4652
+ reg.lastIndex = start;
4653
+ reg.exec(source);//skip <
4654
+ while(match = reg.exec(source)){
4655
+ buf.push(match);
4656
+ if(match[1])return buf;
4657
+ }
3466
4658
  }
3467
4659
 
3468
- },{}],9:[function(require,module,exports){
3469
- //[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
- //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
3471
- //[5] Name ::= NameStartChar (NameChar)*
3472
- 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]");
3474
- var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
3475
- //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
3476
- //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
-
3478
- //S_TAG, S_ATTR, S_EQ, S_V
3479
- //S_ATTR_S, S_E, S_S, S_C
3480
- var S_TAG = 0;//tag name offerring
3481
- var S_ATTR = 1;//attr name offerring
3482
- var S_ATTR_S=2;//attr name end and space offer
3483
- 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 />
3488
-
3489
- function XMLReader(){
3490
-
3491
- }
3492
-
3493
- XMLReader.prototype = {
3494
- parse:function(source,defaultNSMap,entityMap){
3495
- var domBuilder = this.domBuilder;
3496
- domBuilder.startDocument();
3497
- _copy(defaultNSMap ,defaultNSMap = {})
3498
- parse(source,defaultNSMap,entityMap,
3499
- domBuilder,this.errorHandler);
3500
- domBuilder.endDocument();
3501
- }
3502
- }
3503
- function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
3504
- function fixedFromCharCode(code) {
3505
- // String.prototype.fromCharCode does not supports
3506
- // > 2 bytes unicode chars directly
3507
- if (code > 0xffff) {
3508
- code -= 0x10000;
3509
- var surrogate1 = 0xd800 + (code >> 10)
3510
- , surrogate2 = 0xdc00 + (code & 0x3ff);
3511
-
3512
- return String.fromCharCode(surrogate1, surrogate2);
3513
- } else {
3514
- return String.fromCharCode(code);
3515
- }
3516
- }
3517
- function entityReplacer(a){
3518
- var k = a.slice(1,-1);
3519
- if(k in entityMap){
3520
- return entityMap[k];
3521
- }else if(k.charAt(0) === '#'){
3522
- return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
3523
- }else{
3524
- errorHandler.error('entity not found:'+a);
3525
- return a;
3526
- }
3527
- }
3528
- 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
3533
- }
3534
- function position(start,m){
3535
- while(start>=endPos && (m = linePattern.exec(source))){
3536
- startPos = m.index;
3537
- endPos = startPos + m[0].length;
3538
- locator.lineNumber++;
3539
- //console.log('line++:',locator,startPos,endPos)
3540
- }
3541
- locator.columnNumber = start-startPos+1;
3542
- }
3543
- var startPos = 0;
3544
- var endPos = 0;
3545
- var linePattern = /.+(?:\r\n?|\n)|.*$/g
3546
- var locator = domBuilder.locator;
3547
-
3548
- var parseStack = [{currentNSMap:defaultNSMapCopy}]
3549
- var closeMap = {};
3550
- var start = 0;
3551
- 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) ;
3579
- }
3580
- }
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);
3595
-
3596
- var el = new ElementAttributes();
3597
-
3598
- //elStartEnd
3599
- var end = parseElementStartPart(source,i,el,entityReplacer,errorHandler);
3600
- 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
- }
3611
- if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
3612
- el.closed = true;
3613
- if(!entityMap.nbsp){
3614
- errorHandler.warning('unclosed xml attribute');
3615
- }
3616
- }
3617
- appendElement(el,domBuilder,parseStack);
3618
-
3619
-
3620
- if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
3621
- end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
3622
- }else{
3623
- end++;
3624
- }
3625
- }catch(e){
3626
- errorHandler.error('element parse error: '+e);
3627
- end = -1;
3628
- }
3629
-
3630
- }
3631
- if(end<0){
3632
- //TODO: 这里有可能sax回退,有位置错误风险
3633
- appendText(i+1);
3634
- }else{
3635
- start = end;
3636
- }
3637
- }
3638
- }
3639
- function copyLocator(f,t){
3640
- t.lineNumber = f.lineNumber;
3641
- t.columnNumber = f.columnNumber;
3642
- return t;
3643
-
3644
- }
3645
-
3646
- /**
3647
- * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
3648
- * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
3649
- */
3650
- function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3651
- var attrName;
3652
- var value;
3653
- var p = ++start;
3654
- var s = S_TAG;//status
3655
- while(true){
3656
- var c = source.charAt(p);
3657
- switch(c){
3658
- case '=':
3659
- if(s === S_ATTR){//attrName
3660
- attrName = source.slice(start,p);
3661
- s = S_EQ;
3662
- }else if(s === S_ATTR_S){
3663
- s = S_EQ;
3664
- }else{
3665
- //fatalError: equal must after attrName or space after attrName
3666
- throw new Error('attribute equal must after attrName');
3667
- }
3668
- break;
3669
- case '\'':
3670
- case '"':
3671
- if(s === S_EQ){//equal
3672
- start = p+1;
3673
- p = source.indexOf(c,start)
3674
- if(p>0){
3675
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3676
- el.add(attrName,value,start-1);
3677
- s = S_E;
3678
- }else{
3679
- //fatalError: no end quot match
3680
- throw new Error('attribute value no end \''+c+'\' match');
3681
- }
3682
- }else if(s == S_V){
3683
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3684
- //console.log(attrName,value,start,p)
3685
- el.add(attrName,value,start);
3686
- //console.dir(el)
3687
- errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
3688
- start = p+1;
3689
- s = S_E
3690
- }else{
3691
- //fatalError: no equal before
3692
- throw new Error('attribute value must after "="');
3693
- }
3694
- break;
3695
- case '/':
3696
- switch(s){
3697
- case S_TAG:
3698
- el.setTagName(source.slice(start,p));
3699
- case S_E:
3700
- case S_S:
3701
- case S_C:
3702
- s = S_C;
3703
- el.closed = true;
3704
- case S_V:
3705
- case S_ATTR:
3706
- case S_ATTR_S:
3707
- break;
3708
- //case S_EQ:
3709
- default:
3710
- throw new Error("attribute invalid close char('/')")
3711
- }
3712
- break;
3713
- case ''://end document
3714
- //throw new Error('unexpected end of input')
3715
- errorHandler.error('unexpected end of input');
3716
- case '>':
3717
- switch(s){
3718
- case S_TAG:
3719
- el.setTagName(source.slice(start,p));
3720
- case S_E:
3721
- case S_S:
3722
- case S_C:
3723
- break;//normal
3724
- case S_V://Compatible state
3725
- case S_ATTR:
3726
- value = source.slice(start,p);
3727
- if(value.slice(-1) === '/'){
3728
- el.closed = true;
3729
- value = value.slice(0,-1)
3730
- }
3731
- case S_ATTR_S:
3732
- if(s === S_ATTR_S){
3733
- value = attrName;
3734
- }
3735
- if(s == S_V){
3736
- errorHandler.warning('attribute "'+value+'" missed quot(")!!');
3737
- el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
3738
- }else{
3739
- errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
3740
- el.add(value,value,start)
3741
- }
3742
- break;
3743
- case S_EQ:
3744
- throw new Error('attribute value missed!!');
3745
- }
3746
- // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
3747
- return p;
3748
- /*xml space '\x20' | #x9 | #xD | #xA; */
3749
- case '\u0080':
3750
- c = ' ';
3751
- default:
3752
- if(c<= ' '){//space
3753
- switch(s){
3754
- case S_TAG:
3755
- el.setTagName(source.slice(start,p));//tagName
3756
- s = S_S;
3757
- break;
3758
- case S_ATTR:
3759
- attrName = source.slice(start,p)
3760
- s = S_ATTR_S;
3761
- break;
3762
- case S_V:
3763
- var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3764
- errorHandler.warning('attribute "'+value+'" missed quot(")!!');
3765
- el.add(attrName,value,start)
3766
- case S_E:
3767
- s = S_S;
3768
- break;
3769
- //case S_S:
3770
- //case S_EQ:
3771
- //case S_ATTR_S:
3772
- // void();break;
3773
- //case S_C:
3774
- //ignore warning
3775
- }
3776
- }else{//not space
3777
- //S_TAG, S_ATTR, S_EQ, S_V
3778
- //S_ATTR_S, S_E, S_S, S_C
3779
- switch(s){
3780
- //case S_TAG:void();break;
3781
- //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!!')
3785
- el.add(attrName,attrName,start);
3786
- start = p;
3787
- s = S_ATTR;
3788
- break;
3789
- case S_E:
3790
- errorHandler.warning('attribute space is required"'+attrName+'"!!')
3791
- case S_S:
3792
- s = S_ATTR;
3793
- start = p;
3794
- break;
3795
- case S_EQ:
3796
- s = S_V;
3797
- start = p;
3798
- break;
3799
- case S_C:
3800
- throw new Error("elements closed character '/' and '>' must be connected to");
3801
- }
3802
- }
3803
- }
3804
- p++;
3805
- }
3806
- }
3807
- /**
3808
- * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
3809
- */
3810
- function appendElement(el,domBuilder,parseStack){
3811
- var tagName = el.tagName;
3812
- var localNSMap = null;
3813
- var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
3814
- var i = el.length;
3815
- while(i--){
3816
- var a = el[i];
3817
- var qName = a.qName;
3818
- var value = a.value;
3819
- var nsp = qName.indexOf(':');
3820
- if(nsp>0){
3821
- var prefix = a.prefix = qName.slice(0,nsp);
3822
- var localName = qName.slice(nsp+1);
3823
- var nsPrefix = prefix === 'xmlns' && localName
3824
- }else{
3825
- localName = qName;
3826
- prefix = null
3827
- nsPrefix = qName === 'xmlns' && ''
3828
- }
3829
- //can not set prefix,because prefix !== ''
3830
- a.localName = localName ;
3831
- //prefix == null for no ns prefix attribute
3832
- if(nsPrefix !== false){//hack!!
3833
- if(localNSMap == null){
3834
- localNSMap = {}
3835
- //console.log(currentNSMap,0)
3836
- _copy(currentNSMap,currentNSMap={})
3837
- //console.log(currentNSMap,1)
3838
- }
3839
- currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
3840
- a.uri = 'http://www.w3.org/2000/xmlns/'
3841
- domBuilder.startPrefixMapping(nsPrefix, value)
3842
- }
3843
- }
3844
- var i = el.length;
3845
- while(i--){
3846
- a = el[i];
3847
- var prefix = a.prefix;
3848
- if(prefix){//no prefix attribute has no namespace
3849
- if(prefix === 'xml'){
3850
- a.uri = 'http://www.w3.org/XML/1998/namespace';
3851
- }if(prefix !== 'xmlns'){
3852
- a.uri = currentNSMap[prefix]
3853
-
3854
- //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
3855
- }
3856
- }
3857
- }
3858
- var nsp = tagName.indexOf(':');
3859
- if(nsp>0){
3860
- prefix = el.prefix = tagName.slice(0,nsp);
3861
- localName = el.localName = tagName.slice(nsp+1);
3862
- }else{
3863
- prefix = null;//important!!
3864
- localName = el.localName = tagName;
3865
- }
3866
- //no prefix element has default namespace
3867
- var ns = el.uri = currentNSMap[prefix || ''];
3868
- domBuilder.startElement(ns,localName,tagName,el);
3869
- //endPrefixMapping and startPrefixMapping have not any help for dom builder
3870
- //localNSMap = null
3871
- if(el.closed){
3872
- domBuilder.endElement(ns,localName,tagName);
3873
- if(localNSMap){
3874
- for(prefix in localNSMap){
3875
- domBuilder.endPrefixMapping(prefix)
3876
- }
3877
- }
3878
- }else{
3879
- el.currentNSMap = currentNSMap;
3880
- el.localNSMap = localNSMap;
3881
- parseStack.push(el);
3882
- }
3883
- }
3884
- function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
3885
- if(/^(?:script|textarea)$/i.test(tagName)){
3886
- var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
3887
- var text = source.substring(elStartEnd+1,elEndStart);
3888
- if(/[&<]/.test(text)){
3889
- if(/^script$/i.test(tagName)){
3890
- //if(!/\]\]>/.test(text)){
3891
- //lexHandler.startCDATA();
3892
- domBuilder.characters(text,0,text.length);
3893
- //lexHandler.endCDATA();
3894
- return elEndStart;
3895
- //}
3896
- }//}else{//text area
3897
- text = text.replace(/&#?\w+;/g,entityReplacer);
3898
- domBuilder.characters(text,0,text.length);
3899
- return elEndStart;
3900
- //}
3901
-
3902
- }
3903
- }
3904
- return elStartEnd+1;
3905
- }
3906
- function fixSelfClosed(source,elStartEnd,tagName,closeMap){
3907
- //if(tagName in closeMap){
3908
- var pos = closeMap[tagName];
3909
- if(pos == null){
3910
- //console.log(tagName)
3911
- pos = closeMap[tagName] = source.lastIndexOf('</'+tagName+'>')
3912
- }
3913
- return pos<elStartEnd;
3914
- //}
3915
- }
3916
- function _copy(source,target){
3917
- for(var n in source){target[n] = source[n]}
3918
- }
3919
- function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
3920
- var next= source.charAt(start+2)
3921
- switch(next){
3922
- case '-':
3923
- if(source.charAt(start + 3) === '-'){
3924
- var end = source.indexOf('-->',start+4);
3925
- //append comment source.substring(4,end)//<!--
3926
- if(end>start){
3927
- domBuilder.comment(source,start+4,end-start-4);
3928
- return end+3;
3929
- }else{
3930
- errorHandler.error("Unclosed comment");
3931
- return -1;
3932
- }
3933
- }else{
3934
- //error
3935
- return -1;
3936
- }
3937
- default:
3938
- if(source.substr(start+3,6) == 'CDATA['){
3939
- var end = source.indexOf(']]>',start+9);
3940
- domBuilder.startCDATA();
3941
- domBuilder.characters(source,start+9,end-start-9);
3942
- domBuilder.endCDATA()
3943
- return end+3;
3944
- }
3945
- //<!DOCTYPE
3946
- //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
3947
- var matchs = split(source,start);
3948
- var len = matchs.length;
3949
- if(len>1 && /!doctype/i.test(matchs[0][0])){
3950
- var name = matchs[1][0];
3951
- var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
3952
- var sysid = len>4 && matchs[4][0];
3953
- var lastMatch = matchs[len-1]
3954
- domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
3955
- sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
3956
- domBuilder.endDTD();
3957
-
3958
- return lastMatch.index+lastMatch[0].length
3959
- }
3960
- }
3961
- return -1;
3962
- }
3963
-
3964
-
3965
-
3966
- function parseInstruction(source,start,domBuilder){
3967
- var end = source.indexOf('?>',start);
3968
- if(end){
3969
- var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
3970
- if(match){
3971
- var len = match[0].length;
3972
- domBuilder.processingInstruction(match[1], match[2]) ;
3973
- return end+2;
3974
- }else{//error
3975
- return -1;
3976
- }
3977
- }
3978
- return -1;
3979
- }
3980
-
3981
- /**
3982
- * @param source
3983
- */
3984
- function ElementAttributes(source){
3985
-
3986
- }
3987
- ElementAttributes.prototype = {
3988
- setTagName:function(tagName){
3989
- if(!tagNamePattern.test(tagName)){
3990
- throw new Error('invalid tagName:'+tagName)
3991
- }
3992
- this.tagName = tagName
3993
- },
3994
- add:function(qName,value,offset){
3995
- if(!tagNamePattern.test(qName)){
3996
- throw new Error('invalid attribute:'+qName)
3997
- }
3998
- this[this.length++] = {qName:qName,value:value,offset:offset}
3999
- },
4000
- length:0,
4001
- getLocalName:function(i){return this[i].localName},
4002
- getOffset:function(i){return this[i].offset},
4003
- getQName:function(i){return this[i].qName},
4004
- getURI:function(i){return this[i].uri},
4005
- getValue:function(i){return this[i].value}
4006
- // ,getIndex:function(uri, localName)){
4007
- // if(localName){
4008
- //
4009
- // }else{
4010
- // var qName = uri
4011
- // }
4012
- // },
4013
- // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
4014
- // getType:function(uri,localName){}
4015
- // getType:function(i){},
4016
- }
4017
-
4018
-
4019
-
4020
-
4021
- function _set_proto_(thiz,parent){
4022
- thiz.__proto__ = parent;
4023
- return thiz;
4024
- }
4025
- if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
4026
- _set_proto_ = function(thiz,parent){
4027
- function p(){};
4028
- p.prototype = parent;
4029
- p = new p();
4030
- for(parent in thiz){
4031
- p[parent] = thiz[parent];
4032
- }
4033
- return p;
4034
- }
4035
- }
4036
-
4037
- function split(source,start){
4038
- var match;
4039
- var buf = [];
4040
- var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
4041
- reg.lastIndex = start;
4042
- reg.exec(source);//skip <
4043
- while(match = reg.exec(source)){
4044
- buf.push(match);
4045
- if(match[1])return buf;
4046
- }
4047
- }
4048
-
4049
- if(typeof require == 'function'){
4050
- exports.XMLReader = XMLReader;
4051
- }
4052
-
4660
+ exports.XMLReader = XMLReader;
4661
+ exports.ParseError = ParseError;
4053
4662
 
4054
4663
  },{}]},{},[1])(1)
4055
- });
4664
+ });