plist 0.4.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3628 @@
1
+ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.plist=e()}}(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
+
4
+ /**
5
+ * Module dependencies.
6
+ */
7
+
8
+ var deprecate = require('util-deprecate');
9
+ var DOMParser = require('xmldom').DOMParser;
10
+
11
+ /**
12
+ * Module exports.
13
+ */
14
+
15
+ 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.');
20
+
21
+ /**
22
+ * We ignore raw text (usually whitespace), <!-- xml comments -->,
23
+ * and raw CDATA nodes.
24
+ *
25
+ * @param {Element} node
26
+ * @returns {Boolean}
27
+ * @api private
28
+ */
29
+
30
+ function shouldIgnoreNode (node) {
31
+ return node.nodeType === 3 // text
32
+ || node.nodeType === 8 // comment
33
+ || node.nodeType === 4; // cdata
34
+ }
35
+
36
+
37
+ /**
38
+ * Parses a Plist XML string. Returns an Object.
39
+ *
40
+ * @param {String} xml - the XML String to decode
41
+ * @returns {Mixed} the decoded value from the Plist XML
42
+ * @api public
43
+ */
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>');
49
+ }
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
+ }
58
+
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;
76
+ }
77
+ callback(error, plist);
78
+ }
79
+
80
+ /**
81
+ * Parses a Plist XML string. Returns an Object.
82
+ *
83
+ * @param {String} xml - the XML String to decode
84
+ * @param {Function} callback - callback function
85
+ * @returns {Mixed} the decoded value from the Plist XML
86
+ * @api public
87
+ * @deprecated use parse() instead
88
+ */
89
+
90
+ function parseStringSync (xml) {
91
+ 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);
97
+
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
+ return plist;
103
+ }
104
+
105
+ /**
106
+ * Convert an XML based plist document into a JSON representation.
107
+ *
108
+ * @param {Object} xml_node - current XML node in the plist
109
+ * @returns {Mixed} built up JSON object
110
+ * @api private
111
+ */
112
+
113
+ function parsePlistXML (node) {
114
+ var i, new_obj, key, val, new_arr, res, d;
115
+
116
+ if (!node)
117
+ return null;
118
+
119
+ if (node.nodeName === 'plist') {
120
+ new_arr = [];
121
+ for (i=0; i < node.childNodes.length; i++) {
122
+ // ignore comment nodes (text)
123
+ if (!shouldIgnoreNode(node.childNodes[i])) {
124
+ new_arr.push( parsePlistXML(node.childNodes[i]));
125
+ }
126
+ }
127
+ return new_arr;
128
+
129
+ } else if (node.nodeName === 'dict') {
130
+ new_obj = {};
131
+ key = null;
132
+ 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
+ }
141
+ }
142
+ }
143
+ return new_obj;
144
+
145
+ } else if (node.nodeName === 'array') {
146
+ new_arr = [];
147
+ for (i=0; i < node.childNodes.length; i++) {
148
+ // ignore comment nodes (text)
149
+ if (!shouldIgnoreNode(node.childNodes[i])) {
150
+ res = parsePlistXML(node.childNodes[i]);
151
+ if (null != res) new_arr.push(res);
152
+ }
153
+ }
154
+ return new_arr;
155
+
156
+ } else if (node.nodeName === '#text') {
157
+ // TODO: what should we do with text types? (CDATA sections)
158
+
159
+ } else if (node.nodeName === 'key') {
160
+ return node.childNodes[0].nodeValue;
161
+
162
+ } else if (node.nodeName === 'string') {
163
+ res = '';
164
+ for (d=0; d < node.childNodes.length; d++) {
165
+ res += node.childNodes[d].nodeValue;
166
+ }
167
+ return res;
168
+
169
+ } else if (node.nodeName === 'integer') {
170
+ // parse as base 10 integer
171
+ return parseInt(node.childNodes[0].nodeValue, 10);
172
+
173
+ } else if (node.nodeName === 'real') {
174
+ res = '';
175
+ for (d=0; d < node.childNodes.length; d++) {
176
+ if (node.childNodes[d].nodeType === 3) {
177
+ res += node.childNodes[d].nodeValue;
178
+ }
179
+ }
180
+ return parseFloat(res);
181
+
182
+ } else if (node.nodeName === 'data') {
183
+ 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, '');
187
+ }
188
+ }
189
+
190
+ // decode base64 data to a Buffer instance
191
+ return new Buffer(res, 'base64');
192
+
193
+ } else if (node.nodeName === 'date') {
194
+ return new Date(node.childNodes[0].nodeValue);
195
+
196
+ } else if (node.nodeName === 'true') {
197
+ return true;
198
+
199
+ } else if (node.nodeName === 'false') {
200
+ return false;
201
+ }
202
+ }
203
+
204
+ }).call(this,require("buffer").Buffer)
205
+ },{"buffer":3,"util-deprecate":5,"xmldom":6}],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 ZERO = '0'.charCodeAt(0)
216
+ var PLUS = '+'.charCodeAt(0)
217
+ var SLASH = '/'.charCodeAt(0)
218
+ var NUMBER = '0'.charCodeAt(0)
219
+ var LOWER = 'a'.charCodeAt(0)
220
+ var UPPER = 'A'.charCodeAt(0)
221
+
222
+ function decode (elt) {
223
+ var code = elt.charCodeAt(0)
224
+ if (code === PLUS)
225
+ return 62 // '+'
226
+ if (code === SLASH)
227
+ return 63 // '/'
228
+ if (code < NUMBER)
229
+ return -1 //no match
230
+ if (code < NUMBER + 10)
231
+ return code - NUMBER + 26 + 26
232
+ if (code < UPPER + 26)
233
+ return code - UPPER
234
+ if (code < LOWER + 26)
235
+ return code - LOWER + 26
236
+ }
237
+
238
+ function b64ToByteArray (b64) {
239
+ var i, j, l, tmp, placeHolders, arr
240
+
241
+ if (b64.length % 4 > 0) {
242
+ throw new Error('Invalid string. Length must be a multiple of 4')
243
+ }
244
+
245
+ // the number of equal signs (place holders)
246
+ // if there are two placeholders, than the two characters before it
247
+ // represent one byte
248
+ // if there is only one, then the three characters before it represent 2 bytes
249
+ // this is just a cheap hack to not do indexOf twice
250
+ var len = b64.length
251
+ placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
252
+
253
+ // base64 is 4/3 + up to two characters of the original data
254
+ arr = new Arr(b64.length * 3 / 4 - placeHolders)
255
+
256
+ // if there are placeholders, only get up to the last complete 4 chars
257
+ l = placeHolders > 0 ? b64.length - 4 : b64.length
258
+
259
+ var L = 0
260
+
261
+ function push (v) {
262
+ arr[L++] = v
263
+ }
264
+
265
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
266
+ tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
267
+ push((tmp & 0xFF0000) >> 16)
268
+ push((tmp & 0xFF00) >> 8)
269
+ push(tmp & 0xFF)
270
+ }
271
+
272
+ if (placeHolders === 2) {
273
+ tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
274
+ push(tmp & 0xFF)
275
+ } else if (placeHolders === 1) {
276
+ tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
277
+ push((tmp >> 8) & 0xFF)
278
+ push(tmp & 0xFF)
279
+ }
280
+
281
+ return arr
282
+ }
283
+
284
+ function uint8ToBase64 (uint8) {
285
+ var i,
286
+ extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
287
+ output = "",
288
+ temp, length
289
+
290
+ function encode (num) {
291
+ return lookup.charAt(num)
292
+ }
293
+
294
+ function tripletToBase64 (num) {
295
+ return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
296
+ }
297
+
298
+ // go through the array every three bytes, we'll deal with trailing stuff later
299
+ for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
300
+ temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
301
+ output += tripletToBase64(temp)
302
+ }
303
+
304
+ // pad the end with zeros, but make sure to not forget the extra bytes
305
+ switch (extraBytes) {
306
+ case 1:
307
+ temp = uint8[uint8.length - 1]
308
+ output += encode(temp >> 2)
309
+ output += encode((temp << 4) & 0x3F)
310
+ output += '=='
311
+ break
312
+ case 2:
313
+ temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
314
+ output += encode(temp >> 10)
315
+ output += encode((temp >> 4) & 0x3F)
316
+ output += encode((temp << 2) & 0x3F)
317
+ output += '='
318
+ break
319
+ }
320
+
321
+ return output
322
+ }
323
+
324
+ module.exports.toByteArray = b64ToByteArray
325
+ module.exports.fromByteArray = uint8ToBase64
326
+ }())
327
+
328
+ },{}],3:[function(require,module,exports){
329
+ /*!
330
+ * The buffer module from node.js, for the browser.
331
+ *
332
+ * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
333
+ * @license MIT
334
+ */
335
+
336
+ var base64 = require('base64-js')
337
+ var ieee754 = require('ieee754')
338
+
339
+ exports.Buffer = Buffer
340
+ exports.SlowBuffer = Buffer
341
+ exports.INSPECT_MAX_BYTES = 50
342
+ Buffer.poolSize = 8192
343
+
344
+ /**
345
+ * If `TYPED_ARRAY_SUPPORT`:
346
+ * === true Use Uint8Array implementation (fastest)
347
+ * === false Use Object implementation (most compatible, even IE6)
348
+ *
349
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
350
+ * Opera 11.6+, iOS 4.2+.
351
+ *
352
+ * Note:
353
+ *
354
+ * - Implementation must support adding new properties to `Uint8Array` instances.
355
+ * Firefox 4-29 lacked support, fixed in Firefox 30+.
356
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
357
+ *
358
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
359
+ *
360
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
361
+ * incorrect length in some situations.
362
+ *
363
+ * We detect these buggy browsers and set `TYPED_ARRAY_SUPPORT` to `false` so they will
364
+ * get the Object implementation, which is slower but will work correctly.
365
+ */
366
+ var TYPED_ARRAY_SUPPORT = (function () {
367
+ try {
368
+ var buf = new ArrayBuffer(0)
369
+ var arr = new Uint8Array(buf)
370
+ arr.foo = function () { return 42 }
371
+ return 42 === arr.foo() && // typed array instances can be augmented
372
+ typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
373
+ new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
374
+ } catch (e) {
375
+ return false
376
+ }
377
+ })()
378
+
379
+ /**
380
+ * Class: Buffer
381
+ * =============
382
+ *
383
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
384
+ * with function properties for all the node `Buffer` API functions. We use
385
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
386
+ * a single octet.
387
+ *
388
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
389
+ * prototype.
390
+ */
391
+ function Buffer (subject, encoding, noZero) {
392
+ if (!(this instanceof Buffer))
393
+ return new Buffer(subject, encoding, noZero)
394
+
395
+ var type = typeof subject
396
+
397
+ // Find the length
398
+ var length
399
+ if (type === 'number')
400
+ length = subject > 0 ? subject >>> 0 : 0
401
+ else if (type === 'string') {
402
+ if (encoding === 'base64')
403
+ subject = base64clean(subject)
404
+ length = Buffer.byteLength(subject, encoding)
405
+ } else if (type === 'object' && subject !== null) { // assume object is array-like
406
+ if (subject.type === 'Buffer' && isArray(subject.data))
407
+ subject = subject.data
408
+ length = +subject.length > 0 ? Math.floor(+subject.length) : 0
409
+ } else
410
+ throw new Error('First argument needs to be a number, array or string.')
411
+
412
+ var buf
413
+ if (TYPED_ARRAY_SUPPORT) {
414
+ // Preferred: Return an augmented `Uint8Array` instance for best performance
415
+ buf = Buffer._augment(new Uint8Array(length))
416
+ } else {
417
+ // Fallback: Return THIS instance of Buffer (created by `new`)
418
+ buf = this
419
+ buf.length = length
420
+ buf._isBuffer = true
421
+ }
422
+
423
+ var i
424
+ if (TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
425
+ // Speed optimization -- use set if we're copying from a typed array
426
+ buf._set(subject)
427
+ } else if (isArrayish(subject)) {
428
+ // Treat array-ish objects as a byte array
429
+ if (Buffer.isBuffer(subject)) {
430
+ for (i = 0; i < length; i++)
431
+ buf[i] = subject.readUInt8(i)
432
+ } else {
433
+ for (i = 0; i < length; i++)
434
+ buf[i] = ((subject[i] % 256) + 256) % 256
435
+ }
436
+ } else if (type === 'string') {
437
+ buf.write(subject, 0, encoding)
438
+ } else if (type === 'number' && !TYPED_ARRAY_SUPPORT && !noZero) {
439
+ for (i = 0; i < length; i++) {
440
+ buf[i] = 0
441
+ }
442
+ }
443
+
444
+ return buf
445
+ }
446
+
447
+ // STATIC METHODS
448
+ // ==============
449
+
450
+ Buffer.isEncoding = function (encoding) {
451
+ switch (String(encoding).toLowerCase()) {
452
+ case 'hex':
453
+ case 'utf8':
454
+ case 'utf-8':
455
+ case 'ascii':
456
+ case 'binary':
457
+ case 'base64':
458
+ case 'raw':
459
+ case 'ucs2':
460
+ case 'ucs-2':
461
+ case 'utf16le':
462
+ case 'utf-16le':
463
+ return true
464
+ default:
465
+ return false
466
+ }
467
+ }
468
+
469
+ Buffer.isBuffer = function (b) {
470
+ return !!(b != null && b._isBuffer)
471
+ }
472
+
473
+ Buffer.byteLength = function (str, encoding) {
474
+ var ret
475
+ str = str.toString()
476
+ switch (encoding || 'utf8') {
477
+ case 'hex':
478
+ ret = str.length / 2
479
+ break
480
+ case 'utf8':
481
+ case 'utf-8':
482
+ ret = utf8ToBytes(str).length
483
+ break
484
+ case 'ascii':
485
+ case 'binary':
486
+ case 'raw':
487
+ ret = str.length
488
+ break
489
+ case 'base64':
490
+ ret = base64ToBytes(str).length
491
+ break
492
+ case 'ucs2':
493
+ case 'ucs-2':
494
+ case 'utf16le':
495
+ case 'utf-16le':
496
+ ret = str.length * 2
497
+ break
498
+ default:
499
+ throw new Error('Unknown encoding')
500
+ }
501
+ return ret
502
+ }
503
+
504
+ Buffer.concat = function (list, totalLength) {
505
+ assert(isArray(list), 'Usage: Buffer.concat(list[, length])')
506
+
507
+ if (list.length === 0) {
508
+ return new Buffer(0)
509
+ } else if (list.length === 1) {
510
+ return list[0]
511
+ }
512
+
513
+ var i
514
+ if (totalLength === undefined) {
515
+ totalLength = 0
516
+ for (i = 0; i < list.length; i++) {
517
+ totalLength += list[i].length
518
+ }
519
+ }
520
+
521
+ var buf = new Buffer(totalLength)
522
+ var pos = 0
523
+ for (i = 0; i < list.length; i++) {
524
+ var item = list[i]
525
+ item.copy(buf, pos)
526
+ pos += item.length
527
+ }
528
+ return buf
529
+ }
530
+
531
+ Buffer.compare = function (a, b) {
532
+ assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers')
533
+ var x = a.length
534
+ var y = b.length
535
+ for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
536
+ if (i !== len) {
537
+ x = a[i]
538
+ y = b[i]
539
+ }
540
+ if (x < y) {
541
+ return -1
542
+ }
543
+ if (y < x) {
544
+ return 1
545
+ }
546
+ return 0
547
+ }
548
+
549
+ // BUFFER INSTANCE METHODS
550
+ // =======================
551
+
552
+ function hexWrite (buf, string, offset, length) {
553
+ offset = Number(offset) || 0
554
+ var remaining = buf.length - offset
555
+ if (!length) {
556
+ length = remaining
557
+ } else {
558
+ length = Number(length)
559
+ if (length > remaining) {
560
+ length = remaining
561
+ }
562
+ }
563
+
564
+ // must be an even number of digits
565
+ var strLen = string.length
566
+ assert(strLen % 2 === 0, 'Invalid hex string')
567
+
568
+ if (length > strLen / 2) {
569
+ length = strLen / 2
570
+ }
571
+ for (var i = 0; i < length; i++) {
572
+ var byte = parseInt(string.substr(i * 2, 2), 16)
573
+ assert(!isNaN(byte), 'Invalid hex string')
574
+ buf[offset + i] = byte
575
+ }
576
+ return i
577
+ }
578
+
579
+ function utf8Write (buf, string, offset, length) {
580
+ var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
581
+ return charsWritten
582
+ }
583
+
584
+ function asciiWrite (buf, string, offset, length) {
585
+ var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
586
+ return charsWritten
587
+ }
588
+
589
+ function binaryWrite (buf, string, offset, length) {
590
+ return asciiWrite(buf, string, offset, length)
591
+ }
592
+
593
+ function base64Write (buf, string, offset, length) {
594
+ var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
595
+ return charsWritten
596
+ }
597
+
598
+ function utf16leWrite (buf, string, offset, length) {
599
+ var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
600
+ return charsWritten
601
+ }
602
+
603
+ Buffer.prototype.write = function (string, offset, length, encoding) {
604
+ // Support both (string, offset, length, encoding)
605
+ // and the legacy (string, encoding, offset, length)
606
+ if (isFinite(offset)) {
607
+ if (!isFinite(length)) {
608
+ encoding = length
609
+ length = undefined
610
+ }
611
+ } else { // legacy
612
+ var swap = encoding
613
+ encoding = offset
614
+ offset = length
615
+ length = swap
616
+ }
617
+
618
+ offset = Number(offset) || 0
619
+ var remaining = this.length - offset
620
+ if (!length) {
621
+ length = remaining
622
+ } else {
623
+ length = Number(length)
624
+ if (length > remaining) {
625
+ length = remaining
626
+ }
627
+ }
628
+ encoding = String(encoding || 'utf8').toLowerCase()
629
+
630
+ var ret
631
+ switch (encoding) {
632
+ case 'hex':
633
+ ret = hexWrite(this, string, offset, length)
634
+ break
635
+ case 'utf8':
636
+ case 'utf-8':
637
+ ret = utf8Write(this, string, offset, length)
638
+ break
639
+ case 'ascii':
640
+ ret = asciiWrite(this, string, offset, length)
641
+ break
642
+ case 'binary':
643
+ ret = binaryWrite(this, string, offset, length)
644
+ break
645
+ case 'base64':
646
+ ret = base64Write(this, string, offset, length)
647
+ break
648
+ case 'ucs2':
649
+ case 'ucs-2':
650
+ case 'utf16le':
651
+ case 'utf-16le':
652
+ ret = utf16leWrite(this, string, offset, length)
653
+ break
654
+ default:
655
+ throw new Error('Unknown encoding')
656
+ }
657
+ return ret
658
+ }
659
+
660
+ Buffer.prototype.toString = function (encoding, start, end) {
661
+ var self = this
662
+
663
+ encoding = String(encoding || 'utf8').toLowerCase()
664
+ start = Number(start) || 0
665
+ end = (end === undefined) ? self.length : Number(end)
666
+
667
+ // Fastpath empty strings
668
+ if (end === start)
669
+ return ''
670
+
671
+ var ret
672
+ switch (encoding) {
673
+ case 'hex':
674
+ ret = hexSlice(self, start, end)
675
+ break
676
+ case 'utf8':
677
+ case 'utf-8':
678
+ ret = utf8Slice(self, start, end)
679
+ break
680
+ case 'ascii':
681
+ ret = asciiSlice(self, start, end)
682
+ break
683
+ case 'binary':
684
+ ret = binarySlice(self, start, end)
685
+ break
686
+ case 'base64':
687
+ ret = base64Slice(self, start, end)
688
+ break
689
+ case 'ucs2':
690
+ case 'ucs-2':
691
+ case 'utf16le':
692
+ case 'utf-16le':
693
+ ret = utf16leSlice(self, start, end)
694
+ break
695
+ default:
696
+ throw new Error('Unknown encoding')
697
+ }
698
+ return ret
699
+ }
700
+
701
+ Buffer.prototype.toJSON = function () {
702
+ return {
703
+ type: 'Buffer',
704
+ data: Array.prototype.slice.call(this._arr || this, 0)
705
+ }
706
+ }
707
+
708
+ Buffer.prototype.equals = function (b) {
709
+ assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
710
+ return Buffer.compare(this, b) === 0
711
+ }
712
+
713
+ Buffer.prototype.compare = function (b) {
714
+ assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
715
+ return Buffer.compare(this, b)
716
+ }
717
+
718
+ // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
719
+ Buffer.prototype.copy = function (target, target_start, start, end) {
720
+ var source = this
721
+
722
+ if (!start) start = 0
723
+ if (!end && end !== 0) end = this.length
724
+ if (!target_start) target_start = 0
725
+
726
+ // Copy 0 bytes; we're done
727
+ if (end === start) return
728
+ if (target.length === 0 || source.length === 0) return
729
+
730
+ // Fatal error conditions
731
+ assert(end >= start, 'sourceEnd < sourceStart')
732
+ assert(target_start >= 0 && target_start < target.length,
733
+ 'targetStart out of bounds')
734
+ assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
735
+ assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
736
+
737
+ // Are we oob?
738
+ if (end > this.length)
739
+ end = this.length
740
+ if (target.length - target_start < end - start)
741
+ end = target.length - target_start + start
742
+
743
+ var len = end - start
744
+
745
+ if (len < 100 || !TYPED_ARRAY_SUPPORT) {
746
+ for (var i = 0; i < len; i++) {
747
+ target[i + target_start] = this[i + start]
748
+ }
749
+ } else {
750
+ target._set(this.subarray(start, start + len), target_start)
751
+ }
752
+ }
753
+
754
+ function base64Slice (buf, start, end) {
755
+ if (start === 0 && end === buf.length) {
756
+ return base64.fromByteArray(buf)
757
+ } else {
758
+ return base64.fromByteArray(buf.slice(start, end))
759
+ }
760
+ }
761
+
762
+ function utf8Slice (buf, start, end) {
763
+ var res = ''
764
+ var tmp = ''
765
+ end = Math.min(buf.length, end)
766
+
767
+ for (var i = start; i < end; i++) {
768
+ if (buf[i] <= 0x7F) {
769
+ res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
770
+ tmp = ''
771
+ } else {
772
+ tmp += '%' + buf[i].toString(16)
773
+ }
774
+ }
775
+
776
+ return res + decodeUtf8Char(tmp)
777
+ }
778
+
779
+ function asciiSlice (buf, start, end) {
780
+ var ret = ''
781
+ end = Math.min(buf.length, end)
782
+
783
+ for (var i = start; i < end; i++) {
784
+ ret += String.fromCharCode(buf[i])
785
+ }
786
+ return ret
787
+ }
788
+
789
+ function binarySlice (buf, start, end) {
790
+ return asciiSlice(buf, start, end)
791
+ }
792
+
793
+ function hexSlice (buf, start, end) {
794
+ var len = buf.length
795
+
796
+ if (!start || start < 0) start = 0
797
+ if (!end || end < 0 || end > len) end = len
798
+
799
+ var out = ''
800
+ for (var i = start; i < end; i++) {
801
+ out += toHex(buf[i])
802
+ }
803
+ return out
804
+ }
805
+
806
+ function utf16leSlice (buf, start, end) {
807
+ var bytes = buf.slice(start, end)
808
+ var res = ''
809
+ for (var i = 0; i < bytes.length; i += 2) {
810
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
811
+ }
812
+ return res
813
+ }
814
+
815
+ Buffer.prototype.slice = function (start, end) {
816
+ var len = this.length
817
+ start = ~~start
818
+ end = end === undefined ? len : ~~end
819
+
820
+ if (start < 0) {
821
+ start += len;
822
+ if (start < 0)
823
+ start = 0
824
+ } else if (start > len) {
825
+ start = len
826
+ }
827
+
828
+ if (end < 0) {
829
+ end += len
830
+ if (end < 0)
831
+ end = 0
832
+ } else if (end > len) {
833
+ end = len
834
+ }
835
+
836
+ if (end < start)
837
+ end = start
838
+
839
+ if (TYPED_ARRAY_SUPPORT) {
840
+ return Buffer._augment(this.subarray(start, end))
841
+ } else {
842
+ var sliceLen = end - start
843
+ var newBuf = new Buffer(sliceLen, undefined, true)
844
+ for (var i = 0; i < sliceLen; i++) {
845
+ newBuf[i] = this[i + start]
846
+ }
847
+ return newBuf
848
+ }
849
+ }
850
+
851
+ // `get` will be removed in Node 0.13+
852
+ Buffer.prototype.get = function (offset) {
853
+ console.log('.get() is deprecated. Access using array indexes instead.')
854
+ return this.readUInt8(offset)
855
+ }
856
+
857
+ // `set` will be removed in Node 0.13+
858
+ Buffer.prototype.set = function (v, offset) {
859
+ console.log('.set() is deprecated. Access using array indexes instead.')
860
+ return this.writeUInt8(v, offset)
861
+ }
862
+
863
+ Buffer.prototype.readUInt8 = function (offset, noAssert) {
864
+ if (!noAssert) {
865
+ assert(offset !== undefined && offset !== null, 'missing offset')
866
+ assert(offset < this.length, 'Trying to read beyond buffer length')
867
+ }
868
+
869
+ if (offset >= this.length)
870
+ return
871
+
872
+ return this[offset]
873
+ }
874
+
875
+ function readUInt16 (buf, offset, littleEndian, noAssert) {
876
+ if (!noAssert) {
877
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
878
+ assert(offset !== undefined && offset !== null, 'missing offset')
879
+ assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
880
+ }
881
+
882
+ var len = buf.length
883
+ if (offset >= len)
884
+ return
885
+
886
+ var val
887
+ if (littleEndian) {
888
+ val = buf[offset]
889
+ if (offset + 1 < len)
890
+ val |= buf[offset + 1] << 8
891
+ } else {
892
+ val = buf[offset] << 8
893
+ if (offset + 1 < len)
894
+ val |= buf[offset + 1]
895
+ }
896
+ return val
897
+ }
898
+
899
+ Buffer.prototype.readUInt16LE = function (offset, noAssert) {
900
+ return readUInt16(this, offset, true, noAssert)
901
+ }
902
+
903
+ Buffer.prototype.readUInt16BE = function (offset, noAssert) {
904
+ return readUInt16(this, offset, false, noAssert)
905
+ }
906
+
907
+ function readUInt32 (buf, offset, littleEndian, noAssert) {
908
+ if (!noAssert) {
909
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
910
+ assert(offset !== undefined && offset !== null, 'missing offset')
911
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
912
+ }
913
+
914
+ var len = buf.length
915
+ if (offset >= len)
916
+ return
917
+
918
+ var val
919
+ if (littleEndian) {
920
+ if (offset + 2 < len)
921
+ val = buf[offset + 2] << 16
922
+ if (offset + 1 < len)
923
+ val |= buf[offset + 1] << 8
924
+ val |= buf[offset]
925
+ if (offset + 3 < len)
926
+ val = val + (buf[offset + 3] << 24 >>> 0)
927
+ } else {
928
+ if (offset + 1 < len)
929
+ val = buf[offset + 1] << 16
930
+ if (offset + 2 < len)
931
+ val |= buf[offset + 2] << 8
932
+ if (offset + 3 < len)
933
+ val |= buf[offset + 3]
934
+ val = val + (buf[offset] << 24 >>> 0)
935
+ }
936
+ return val
937
+ }
938
+
939
+ Buffer.prototype.readUInt32LE = function (offset, noAssert) {
940
+ return readUInt32(this, offset, true, noAssert)
941
+ }
942
+
943
+ Buffer.prototype.readUInt32BE = function (offset, noAssert) {
944
+ return readUInt32(this, offset, false, noAssert)
945
+ }
946
+
947
+ Buffer.prototype.readInt8 = function (offset, noAssert) {
948
+ if (!noAssert) {
949
+ assert(offset !== undefined && offset !== null,
950
+ 'missing offset')
951
+ assert(offset < this.length, 'Trying to read beyond buffer length')
952
+ }
953
+
954
+ if (offset >= this.length)
955
+ return
956
+
957
+ var neg = this[offset] & 0x80
958
+ if (neg)
959
+ return (0xff - this[offset] + 1) * -1
960
+ else
961
+ return this[offset]
962
+ }
963
+
964
+ function readInt16 (buf, offset, littleEndian, noAssert) {
965
+ if (!noAssert) {
966
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
967
+ assert(offset !== undefined && offset !== null, 'missing offset')
968
+ assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
969
+ }
970
+
971
+ var len = buf.length
972
+ if (offset >= len)
973
+ return
974
+
975
+ var val = readUInt16(buf, offset, littleEndian, true)
976
+ var neg = val & 0x8000
977
+ if (neg)
978
+ return (0xffff - val + 1) * -1
979
+ else
980
+ return val
981
+ }
982
+
983
+ Buffer.prototype.readInt16LE = function (offset, noAssert) {
984
+ return readInt16(this, offset, true, noAssert)
985
+ }
986
+
987
+ Buffer.prototype.readInt16BE = function (offset, noAssert) {
988
+ return readInt16(this, offset, false, noAssert)
989
+ }
990
+
991
+ function readInt32 (buf, offset, littleEndian, noAssert) {
992
+ if (!noAssert) {
993
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
994
+ assert(offset !== undefined && offset !== null, 'missing offset')
995
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
996
+ }
997
+
998
+ var len = buf.length
999
+ if (offset >= len)
1000
+ return
1001
+
1002
+ var val = readUInt32(buf, offset, littleEndian, true)
1003
+ var neg = val & 0x80000000
1004
+ if (neg)
1005
+ return (0xffffffff - val + 1) * -1
1006
+ else
1007
+ return val
1008
+ }
1009
+
1010
+ Buffer.prototype.readInt32LE = function (offset, noAssert) {
1011
+ return readInt32(this, offset, true, noAssert)
1012
+ }
1013
+
1014
+ Buffer.prototype.readInt32BE = function (offset, noAssert) {
1015
+ return readInt32(this, offset, false, noAssert)
1016
+ }
1017
+
1018
+ function readFloat (buf, offset, littleEndian, noAssert) {
1019
+ if (!noAssert) {
1020
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1021
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
1022
+ }
1023
+
1024
+ return ieee754.read(buf, offset, littleEndian, 23, 4)
1025
+ }
1026
+
1027
+ Buffer.prototype.readFloatLE = function (offset, noAssert) {
1028
+ return readFloat(this, offset, true, noAssert)
1029
+ }
1030
+
1031
+ Buffer.prototype.readFloatBE = function (offset, noAssert) {
1032
+ return readFloat(this, offset, false, noAssert)
1033
+ }
1034
+
1035
+ function readDouble (buf, offset, littleEndian, noAssert) {
1036
+ if (!noAssert) {
1037
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1038
+ assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
1039
+ }
1040
+
1041
+ return ieee754.read(buf, offset, littleEndian, 52, 8)
1042
+ }
1043
+
1044
+ Buffer.prototype.readDoubleLE = function (offset, noAssert) {
1045
+ return readDouble(this, offset, true, noAssert)
1046
+ }
1047
+
1048
+ Buffer.prototype.readDoubleBE = function (offset, noAssert) {
1049
+ return readDouble(this, offset, false, noAssert)
1050
+ }
1051
+
1052
+ Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
1053
+ if (!noAssert) {
1054
+ assert(value !== undefined && value !== null, 'missing value')
1055
+ assert(offset !== undefined && offset !== null, 'missing offset')
1056
+ assert(offset < this.length, 'trying to write beyond buffer length')
1057
+ verifuint(value, 0xff)
1058
+ }
1059
+
1060
+ if (offset >= this.length) return
1061
+
1062
+ this[offset] = value
1063
+ return offset + 1
1064
+ }
1065
+
1066
+ function writeUInt16 (buf, value, offset, littleEndian, noAssert) {
1067
+ if (!noAssert) {
1068
+ assert(value !== undefined && value !== null, 'missing value')
1069
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1070
+ assert(offset !== undefined && offset !== null, 'missing offset')
1071
+ assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
1072
+ verifuint(value, 0xffff)
1073
+ }
1074
+
1075
+ var len = buf.length
1076
+ if (offset >= len)
1077
+ return
1078
+
1079
+ for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
1080
+ buf[offset + i] =
1081
+ (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1082
+ (littleEndian ? i : 1 - i) * 8
1083
+ }
1084
+ return offset + 2
1085
+ }
1086
+
1087
+ Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
1088
+ return writeUInt16(this, value, offset, true, noAssert)
1089
+ }
1090
+
1091
+ Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
1092
+ return writeUInt16(this, value, offset, false, noAssert)
1093
+ }
1094
+
1095
+ function writeUInt32 (buf, value, offset, littleEndian, noAssert) {
1096
+ if (!noAssert) {
1097
+ assert(value !== undefined && value !== null, 'missing value')
1098
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1099
+ assert(offset !== undefined && offset !== null, 'missing offset')
1100
+ assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
1101
+ verifuint(value, 0xffffffff)
1102
+ }
1103
+
1104
+ var len = buf.length
1105
+ if (offset >= len)
1106
+ return
1107
+
1108
+ for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
1109
+ buf[offset + i] =
1110
+ (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1111
+ }
1112
+ return offset + 4
1113
+ }
1114
+
1115
+ Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
1116
+ return writeUInt32(this, value, offset, true, noAssert)
1117
+ }
1118
+
1119
+ Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
1120
+ return writeUInt32(this, value, offset, false, noAssert)
1121
+ }
1122
+
1123
+ Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
1124
+ if (!noAssert) {
1125
+ assert(value !== undefined && value !== null, 'missing value')
1126
+ assert(offset !== undefined && offset !== null, 'missing offset')
1127
+ assert(offset < this.length, 'Trying to write beyond buffer length')
1128
+ verifsint(value, 0x7f, -0x80)
1129
+ }
1130
+
1131
+ if (offset >= this.length)
1132
+ return
1133
+
1134
+ if (value >= 0)
1135
+ this.writeUInt8(value, offset, noAssert)
1136
+ else
1137
+ this.writeUInt8(0xff + value + 1, offset, noAssert)
1138
+ return offset + 1
1139
+ }
1140
+
1141
+ function writeInt16 (buf, value, offset, littleEndian, noAssert) {
1142
+ if (!noAssert) {
1143
+ assert(value !== undefined && value !== null, 'missing value')
1144
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1145
+ assert(offset !== undefined && offset !== null, 'missing offset')
1146
+ assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
1147
+ verifsint(value, 0x7fff, -0x8000)
1148
+ }
1149
+
1150
+ var len = buf.length
1151
+ if (offset >= len)
1152
+ return
1153
+
1154
+ if (value >= 0)
1155
+ writeUInt16(buf, value, offset, littleEndian, noAssert)
1156
+ else
1157
+ writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
1158
+ return offset + 2
1159
+ }
1160
+
1161
+ Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
1162
+ return writeInt16(this, value, offset, true, noAssert)
1163
+ }
1164
+
1165
+ Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
1166
+ return writeInt16(this, value, offset, false, noAssert)
1167
+ }
1168
+
1169
+ function writeInt32 (buf, value, offset, littleEndian, noAssert) {
1170
+ if (!noAssert) {
1171
+ assert(value !== undefined && value !== null, 'missing value')
1172
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1173
+ assert(offset !== undefined && offset !== null, 'missing offset')
1174
+ assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
1175
+ verifsint(value, 0x7fffffff, -0x80000000)
1176
+ }
1177
+
1178
+ var len = buf.length
1179
+ if (offset >= len)
1180
+ return
1181
+
1182
+ if (value >= 0)
1183
+ writeUInt32(buf, value, offset, littleEndian, noAssert)
1184
+ else
1185
+ writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
1186
+ return offset + 4
1187
+ }
1188
+
1189
+ Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
1190
+ return writeInt32(this, value, offset, true, noAssert)
1191
+ }
1192
+
1193
+ Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
1194
+ return writeInt32(this, value, offset, false, noAssert)
1195
+ }
1196
+
1197
+ function writeFloat (buf, value, offset, littleEndian, noAssert) {
1198
+ if (!noAssert) {
1199
+ assert(value !== undefined && value !== null, 'missing value')
1200
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1201
+ assert(offset !== undefined && offset !== null, 'missing offset')
1202
+ assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
1203
+ verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
1204
+ }
1205
+
1206
+ var len = buf.length
1207
+ if (offset >= len)
1208
+ return
1209
+
1210
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
1211
+ return offset + 4
1212
+ }
1213
+
1214
+ Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
1215
+ return writeFloat(this, value, offset, true, noAssert)
1216
+ }
1217
+
1218
+ Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
1219
+ return writeFloat(this, value, offset, false, noAssert)
1220
+ }
1221
+
1222
+ function writeDouble (buf, value, offset, littleEndian, noAssert) {
1223
+ if (!noAssert) {
1224
+ assert(value !== undefined && value !== null, 'missing value')
1225
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1226
+ assert(offset !== undefined && offset !== null, 'missing offset')
1227
+ assert(offset + 7 < buf.length,
1228
+ 'Trying to write beyond buffer length')
1229
+ verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
1230
+ }
1231
+
1232
+ var len = buf.length
1233
+ if (offset >= len)
1234
+ return
1235
+
1236
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
1237
+ return offset + 8
1238
+ }
1239
+
1240
+ Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
1241
+ return writeDouble(this, value, offset, true, noAssert)
1242
+ }
1243
+
1244
+ Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
1245
+ return writeDouble(this, value, offset, false, noAssert)
1246
+ }
1247
+
1248
+ // fill(value, start=0, end=buffer.length)
1249
+ Buffer.prototype.fill = function (value, start, end) {
1250
+ if (!value) value = 0
1251
+ if (!start) start = 0
1252
+ if (!end) end = this.length
1253
+
1254
+ assert(end >= start, 'end < start')
1255
+
1256
+ // Fill 0 bytes; we're done
1257
+ if (end === start) return
1258
+ if (this.length === 0) return
1259
+
1260
+ assert(start >= 0 && start < this.length, 'start out of bounds')
1261
+ assert(end >= 0 && end <= this.length, 'end out of bounds')
1262
+
1263
+ var i
1264
+ if (typeof value === 'number') {
1265
+ for (i = start; i < end; i++) {
1266
+ this[i] = value
1267
+ }
1268
+ } else {
1269
+ var bytes = utf8ToBytes(value.toString())
1270
+ var len = bytes.length
1271
+ for (i = start; i < end; i++) {
1272
+ this[i] = bytes[i % len]
1273
+ }
1274
+ }
1275
+
1276
+ return this
1277
+ }
1278
+
1279
+ Buffer.prototype.inspect = function () {
1280
+ var out = []
1281
+ var len = this.length
1282
+ for (var i = 0; i < len; i++) {
1283
+ out[i] = toHex(this[i])
1284
+ if (i === exports.INSPECT_MAX_BYTES) {
1285
+ out[i + 1] = '...'
1286
+ break
1287
+ }
1288
+ }
1289
+ return '<Buffer ' + out.join(' ') + '>'
1290
+ }
1291
+
1292
+ /**
1293
+ * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
1294
+ * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
1295
+ */
1296
+ Buffer.prototype.toArrayBuffer = function () {
1297
+ if (typeof Uint8Array !== 'undefined') {
1298
+ if (TYPED_ARRAY_SUPPORT) {
1299
+ return (new Buffer(this)).buffer
1300
+ } else {
1301
+ var buf = new Uint8Array(this.length)
1302
+ for (var i = 0, len = buf.length; i < len; i += 1) {
1303
+ buf[i] = this[i]
1304
+ }
1305
+ return buf.buffer
1306
+ }
1307
+ } else {
1308
+ throw new Error('Buffer.toArrayBuffer not supported in this browser')
1309
+ }
1310
+ }
1311
+
1312
+ // HELPER FUNCTIONS
1313
+ // ================
1314
+
1315
+ var BP = Buffer.prototype
1316
+
1317
+ /**
1318
+ * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
1319
+ */
1320
+ Buffer._augment = function (arr) {
1321
+ arr._isBuffer = true
1322
+
1323
+ // save reference to original Uint8Array get/set methods before overwriting
1324
+ arr._get = arr.get
1325
+ arr._set = arr.set
1326
+
1327
+ // deprecated, will be removed in node 0.13+
1328
+ arr.get = BP.get
1329
+ arr.set = BP.set
1330
+
1331
+ arr.write = BP.write
1332
+ arr.toString = BP.toString
1333
+ arr.toLocaleString = BP.toString
1334
+ arr.toJSON = BP.toJSON
1335
+ arr.equals = BP.equals
1336
+ arr.compare = BP.compare
1337
+ arr.copy = BP.copy
1338
+ arr.slice = BP.slice
1339
+ arr.readUInt8 = BP.readUInt8
1340
+ arr.readUInt16LE = BP.readUInt16LE
1341
+ arr.readUInt16BE = BP.readUInt16BE
1342
+ arr.readUInt32LE = BP.readUInt32LE
1343
+ arr.readUInt32BE = BP.readUInt32BE
1344
+ arr.readInt8 = BP.readInt8
1345
+ arr.readInt16LE = BP.readInt16LE
1346
+ arr.readInt16BE = BP.readInt16BE
1347
+ arr.readInt32LE = BP.readInt32LE
1348
+ arr.readInt32BE = BP.readInt32BE
1349
+ arr.readFloatLE = BP.readFloatLE
1350
+ arr.readFloatBE = BP.readFloatBE
1351
+ arr.readDoubleLE = BP.readDoubleLE
1352
+ arr.readDoubleBE = BP.readDoubleBE
1353
+ arr.writeUInt8 = BP.writeUInt8
1354
+ arr.writeUInt16LE = BP.writeUInt16LE
1355
+ arr.writeUInt16BE = BP.writeUInt16BE
1356
+ arr.writeUInt32LE = BP.writeUInt32LE
1357
+ arr.writeUInt32BE = BP.writeUInt32BE
1358
+ arr.writeInt8 = BP.writeInt8
1359
+ arr.writeInt16LE = BP.writeInt16LE
1360
+ arr.writeInt16BE = BP.writeInt16BE
1361
+ arr.writeInt32LE = BP.writeInt32LE
1362
+ arr.writeInt32BE = BP.writeInt32BE
1363
+ arr.writeFloatLE = BP.writeFloatLE
1364
+ arr.writeFloatBE = BP.writeFloatBE
1365
+ arr.writeDoubleLE = BP.writeDoubleLE
1366
+ arr.writeDoubleBE = BP.writeDoubleBE
1367
+ arr.fill = BP.fill
1368
+ arr.inspect = BP.inspect
1369
+ arr.toArrayBuffer = BP.toArrayBuffer
1370
+
1371
+ return arr
1372
+ }
1373
+
1374
+ var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
1375
+
1376
+ function base64clean (str) {
1377
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
1378
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '')
1379
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1380
+ while (str.length % 4 !== 0) {
1381
+ str = str + '='
1382
+ }
1383
+ return str
1384
+ }
1385
+
1386
+ function stringtrim (str) {
1387
+ if (str.trim) return str.trim()
1388
+ return str.replace(/^\s+|\s+$/g, '')
1389
+ }
1390
+
1391
+ function isArray (subject) {
1392
+ return (Array.isArray || function (subject) {
1393
+ return Object.prototype.toString.call(subject) === '[object Array]'
1394
+ })(subject)
1395
+ }
1396
+
1397
+ function isArrayish (subject) {
1398
+ return isArray(subject) || Buffer.isBuffer(subject) ||
1399
+ subject && typeof subject === 'object' &&
1400
+ typeof subject.length === 'number'
1401
+ }
1402
+
1403
+ function toHex (n) {
1404
+ if (n < 16) return '0' + n.toString(16)
1405
+ return n.toString(16)
1406
+ }
1407
+
1408
+ function utf8ToBytes (str) {
1409
+ var byteArray = []
1410
+ for (var i = 0; i < str.length; i++) {
1411
+ var b = str.charCodeAt(i)
1412
+ if (b <= 0x7F) {
1413
+ byteArray.push(b)
1414
+ } else {
1415
+ var start = i
1416
+ if (b >= 0xD800 && b <= 0xDFFF) i++
1417
+ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
1418
+ for (var j = 0; j < h.length; j++) {
1419
+ byteArray.push(parseInt(h[j], 16))
1420
+ }
1421
+ }
1422
+ }
1423
+ return byteArray
1424
+ }
1425
+
1426
+ function asciiToBytes (str) {
1427
+ var byteArray = []
1428
+ for (var i = 0; i < str.length; i++) {
1429
+ // Node's code seems to be doing this and not & 0x7F..
1430
+ byteArray.push(str.charCodeAt(i) & 0xFF)
1431
+ }
1432
+ return byteArray
1433
+ }
1434
+
1435
+ function utf16leToBytes (str) {
1436
+ var c, hi, lo
1437
+ var byteArray = []
1438
+ for (var i = 0; i < str.length; i++) {
1439
+ c = str.charCodeAt(i)
1440
+ hi = c >> 8
1441
+ lo = c % 256
1442
+ byteArray.push(lo)
1443
+ byteArray.push(hi)
1444
+ }
1445
+
1446
+ return byteArray
1447
+ }
1448
+
1449
+ function base64ToBytes (str) {
1450
+ return base64.toByteArray(str)
1451
+ }
1452
+
1453
+ function blitBuffer (src, dst, offset, length) {
1454
+ for (var i = 0; i < length; i++) {
1455
+ if ((i + offset >= dst.length) || (i >= src.length))
1456
+ break
1457
+ dst[i + offset] = src[i]
1458
+ }
1459
+ return i
1460
+ }
1461
+
1462
+ function decodeUtf8Char (str) {
1463
+ try {
1464
+ return decodeURIComponent(str)
1465
+ } catch (err) {
1466
+ return String.fromCharCode(0xFFFD) // UTF 8 invalid char
1467
+ }
1468
+ }
1469
+
1470
+ /*
1471
+ * We have to make sure that the value is a valid integer. This means that it
1472
+ * is non-negative. It has no fractional component and that it does not
1473
+ * exceed the maximum allowed value.
1474
+ */
1475
+ function verifuint (value, max) {
1476
+ assert(typeof value === 'number', 'cannot write a non-number as a number')
1477
+ assert(value >= 0, 'specified a negative value for writing an unsigned value')
1478
+ assert(value <= max, 'value is larger than maximum value for type')
1479
+ assert(Math.floor(value) === value, 'value has a fractional component')
1480
+ }
1481
+
1482
+ function verifsint (value, max, min) {
1483
+ assert(typeof value === 'number', 'cannot write a non-number as a number')
1484
+ assert(value <= max, 'value larger than maximum allowed value')
1485
+ assert(value >= min, 'value smaller than minimum allowed value')
1486
+ assert(Math.floor(value) === value, 'value has a fractional component')
1487
+ }
1488
+
1489
+ function verifIEEE754 (value, max, min) {
1490
+ assert(typeof value === 'number', 'cannot write a non-number as a number')
1491
+ assert(value <= max, 'value larger than maximum allowed value')
1492
+ assert(value >= min, 'value smaller than minimum allowed value')
1493
+ }
1494
+
1495
+ function assert (test, message) {
1496
+ if (!test) throw new Error(message || 'Failed assertion')
1497
+ }
1498
+
1499
+ },{"base64-js":2,"ieee754":4}],4:[function(require,module,exports){
1500
+ exports.read = function(buffer, offset, isLE, mLen, nBytes) {
1501
+ var e, m,
1502
+ eLen = nBytes * 8 - mLen - 1,
1503
+ eMax = (1 << eLen) - 1,
1504
+ eBias = eMax >> 1,
1505
+ nBits = -7,
1506
+ i = isLE ? (nBytes - 1) : 0,
1507
+ d = isLE ? -1 : 1,
1508
+ s = buffer[offset + i];
1509
+
1510
+ i += d;
1511
+
1512
+ e = s & ((1 << (-nBits)) - 1);
1513
+ s >>= (-nBits);
1514
+ nBits += eLen;
1515
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
1516
+
1517
+ m = e & ((1 << (-nBits)) - 1);
1518
+ e >>= (-nBits);
1519
+ nBits += mLen;
1520
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
1521
+
1522
+ if (e === 0) {
1523
+ e = 1 - eBias;
1524
+ } else if (e === eMax) {
1525
+ return m ? NaN : ((s ? -1 : 1) * Infinity);
1526
+ } else {
1527
+ m = m + Math.pow(2, mLen);
1528
+ e = e - eBias;
1529
+ }
1530
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
1531
+ };
1532
+
1533
+ exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
1534
+ var e, m, c,
1535
+ eLen = nBytes * 8 - mLen - 1,
1536
+ eMax = (1 << eLen) - 1,
1537
+ eBias = eMax >> 1,
1538
+ rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
1539
+ i = isLE ? 0 : (nBytes - 1),
1540
+ d = isLE ? 1 : -1,
1541
+ s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
1542
+
1543
+ value = Math.abs(value);
1544
+
1545
+ if (isNaN(value) || value === Infinity) {
1546
+ m = isNaN(value) ? 1 : 0;
1547
+ e = eMax;
1548
+ } else {
1549
+ e = Math.floor(Math.log(value) / Math.LN2);
1550
+ if (value * (c = Math.pow(2, -e)) < 1) {
1551
+ e--;
1552
+ c *= 2;
1553
+ }
1554
+ if (e + eBias >= 1) {
1555
+ value += rt / c;
1556
+ } else {
1557
+ value += rt * Math.pow(2, 1 - eBias);
1558
+ }
1559
+ if (value * c >= 2) {
1560
+ e++;
1561
+ c /= 2;
1562
+ }
1563
+
1564
+ if (e + eBias >= eMax) {
1565
+ m = 0;
1566
+ e = eMax;
1567
+ } else if (e + eBias >= 1) {
1568
+ m = (value * c - 1) * Math.pow(2, mLen);
1569
+ e = e + eBias;
1570
+ } else {
1571
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
1572
+ e = 0;
1573
+ }
1574
+ }
1575
+
1576
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
1577
+
1578
+ e = (e << mLen) | m;
1579
+ eLen += mLen;
1580
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
1581
+
1582
+ buffer[offset + i - d] |= s * 128;
1583
+ };
1584
+
1585
+ },{}],5:[function(require,module,exports){
1586
+ (function (global){
1587
+
1588
+ /**
1589
+ * Module exports.
1590
+ */
1591
+
1592
+ module.exports = deprecate;
1593
+
1594
+ /**
1595
+ * Mark that a method should not be used.
1596
+ * Returns a modified function which warns once by default.
1597
+ * If --no-deprecation is set, then it is a no-op.
1598
+ *
1599
+ * @param {Function} fn - the function to deprecate
1600
+ * @param {String} msg - the string to print to the console when `fn` is invoked
1601
+ * @returns {Function} a new "deprecated" version of `fn`
1602
+ * @api public
1603
+ */
1604
+
1605
+ function deprecate (fn, msg) {
1606
+ if (config('noDeprecation')) {
1607
+ return fn;
1608
+ }
1609
+
1610
+ var warned = false;
1611
+ function deprecated() {
1612
+ if (!warned) {
1613
+ if (config('throwDeprecation')) {
1614
+ throw new Error(msg);
1615
+ } else if (config('traceDeprecation')) {
1616
+ console.trace(msg);
1617
+ } else {
1618
+ console.error(msg);
1619
+ }
1620
+ warned = true;
1621
+ }
1622
+ return fn.apply(this, arguments);
1623
+ }
1624
+
1625
+ return deprecated;
1626
+ }
1627
+
1628
+ /**
1629
+ * Checks `localStorage` for boolean values for the given `name`.
1630
+ *
1631
+ * @param {String} name
1632
+ * @returns {Boolean}
1633
+ * @api private
1634
+ */
1635
+
1636
+ function config (name) {
1637
+ if (!global.localStorage) return false;
1638
+ var val = global.localStorage[name];
1639
+ if (null == val) return false;
1640
+ return String(val).toLowerCase() === 'true';
1641
+ }
1642
+
1643
+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1644
+ },{}],6:[function(require,module,exports){
1645
+ function DOMParser(options){
1646
+ this.options = options ||{locator:{}};
1647
+
1648
+ }
1649
+ DOMParser.prototype.parseFromString = function(source,mimeType){
1650
+ var options = this.options;
1651
+ var sax = new XMLReader();
1652
+ var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
1653
+ var errorHandler = options.errorHandler;
1654
+ var locator = options.locator;
1655
+ var defaultNSMap = options.xmlns||{};
1656
+ var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
1657
+ if(locator){
1658
+ domBuilder.setDocumentLocator(locator)
1659
+ }
1660
+
1661
+ sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
1662
+ sax.domBuilder = options.domBuilder || domBuilder;
1663
+ if(/\/x?html?$/.test(mimeType)){
1664
+ entityMap.nbsp = '\xa0';
1665
+ entityMap.copy = '\xa9';
1666
+ defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
1667
+ }
1668
+ if(source){
1669
+ sax.parse(source,defaultNSMap,entityMap);
1670
+ }else{
1671
+ sax.errorHandler.error("invalid document source");
1672
+ }
1673
+ return domBuilder.document;
1674
+ }
1675
+ function buildErrorHandler(errorImpl,domBuilder,locator){
1676
+ if(!errorImpl){
1677
+ if(domBuilder instanceof DOMHandler){
1678
+ return domBuilder;
1679
+ }
1680
+ errorImpl = domBuilder ;
1681
+ }
1682
+ var errorHandler = {}
1683
+ var isCallback = errorImpl instanceof Function;
1684
+ locator = locator||{}
1685
+ function build(key){
1686
+ var fn = errorImpl[key];
1687
+ if(!fn){
1688
+ if(isCallback){
1689
+ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
1690
+ }else{
1691
+ var i=arguments.length;
1692
+ while(--i){
1693
+ if(fn = errorImpl[arguments[i]]){
1694
+ break;
1695
+ }
1696
+ }
1697
+ }
1698
+ }
1699
+ errorHandler[key] = fn && function(msg){
1700
+ fn(msg+_locator(locator));
1701
+ }||function(){};
1702
+ }
1703
+ build('warning','warn');
1704
+ build('error','warn','warning');
1705
+ build('fatalError','warn','warning','error');
1706
+ return errorHandler;
1707
+ }
1708
+ /**
1709
+ * +ContentHandler+ErrorHandler
1710
+ * +LexicalHandler+EntityResolver2
1711
+ * -DeclHandler-DTDHandler
1712
+ *
1713
+ * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
1714
+ * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
1715
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
1716
+ */
1717
+ function DOMHandler() {
1718
+ this.cdata = false;
1719
+ }
1720
+ function position(locator,node){
1721
+ node.lineNumber = locator.lineNumber;
1722
+ node.columnNumber = locator.columnNumber;
1723
+ }
1724
+ /**
1725
+ * @see org.xml.sax.ContentHandler#startDocument
1726
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
1727
+ */
1728
+ DOMHandler.prototype = {
1729
+ startDocument : function() {
1730
+ this.document = new DOMImplementation().createDocument(null, null, null);
1731
+ if (this.locator) {
1732
+ this.document.documentURI = this.locator.systemId;
1733
+ }
1734
+ },
1735
+ startElement:function(namespaceURI, localName, qName, attrs) {
1736
+ var doc = this.document;
1737
+ var el = doc.createElementNS(namespaceURI, qName||localName);
1738
+ var len = attrs.length;
1739
+ appendElement(this, el);
1740
+ this.currentElement = el;
1741
+
1742
+ this.locator && position(this.locator,el)
1743
+ for (var i = 0 ; i < len; i++) {
1744
+ var namespaceURI = attrs.getURI(i);
1745
+ var value = attrs.getValue(i);
1746
+ var qName = attrs.getQName(i);
1747
+ var attr = doc.createAttributeNS(namespaceURI, qName);
1748
+ if( attr.getOffset){
1749
+ position(attr.getOffset(1),attr)
1750
+ }
1751
+ attr.value = attr.nodeValue = value;
1752
+ el.setAttributeNode(attr)
1753
+ }
1754
+ },
1755
+ endElement:function(namespaceURI, localName, qName) {
1756
+ var current = this.currentElement
1757
+ var tagName = current.tagName;
1758
+ this.currentElement = current.parentNode;
1759
+ },
1760
+ startPrefixMapping:function(prefix, uri) {
1761
+ },
1762
+ endPrefixMapping:function(prefix) {
1763
+ },
1764
+ processingInstruction:function(target, data) {
1765
+ var ins = this.document.createProcessingInstruction(target, data);
1766
+ this.locator && position(this.locator,ins)
1767
+ appendElement(this, ins);
1768
+ },
1769
+ ignorableWhitespace:function(ch, start, length) {
1770
+ },
1771
+ characters:function(chars, start, length) {
1772
+ chars = _toString.apply(this,arguments)
1773
+ //console.log(chars)
1774
+ if(this.currentElement && chars){
1775
+ if (this.cdata) {
1776
+ var charNode = this.document.createCDATASection(chars);
1777
+ this.currentElement.appendChild(charNode);
1778
+ } else {
1779
+ var charNode = this.document.createTextNode(chars);
1780
+ this.currentElement.appendChild(charNode);
1781
+ }
1782
+ this.locator && position(this.locator,charNode)
1783
+ }
1784
+ },
1785
+ skippedEntity:function(name) {
1786
+ },
1787
+ endDocument:function() {
1788
+ this.document.normalize();
1789
+ },
1790
+ setDocumentLocator:function (locator) {
1791
+ if(this.locator = locator){// && !('lineNumber' in locator)){
1792
+ locator.lineNumber = 0;
1793
+ }
1794
+ },
1795
+ //LexicalHandler
1796
+ comment:function(chars, start, length) {
1797
+ chars = _toString.apply(this,arguments)
1798
+ var comm = this.document.createComment(chars);
1799
+ this.locator && position(this.locator,comm)
1800
+ appendElement(this, comm);
1801
+ },
1802
+
1803
+ startCDATA:function() {
1804
+ //used in characters() methods
1805
+ this.cdata = true;
1806
+ },
1807
+ endCDATA:function() {
1808
+ this.cdata = false;
1809
+ },
1810
+
1811
+ startDTD:function(name, publicId, systemId) {
1812
+ var impl = this.document.implementation;
1813
+ if (impl && impl.createDocumentType) {
1814
+ var dt = impl.createDocumentType(name, publicId, systemId);
1815
+ this.locator && position(this.locator,dt)
1816
+ appendElement(this, dt);
1817
+ }
1818
+ },
1819
+ /**
1820
+ * @see org.xml.sax.ErrorHandler
1821
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
1822
+ */
1823
+ warning:function(error) {
1824
+ console.warn(error,_locator(this.locator));
1825
+ },
1826
+ error:function(error) {
1827
+ console.error(error,_locator(this.locator));
1828
+ },
1829
+ fatalError:function(error) {
1830
+ console.error(error,_locator(this.locator));
1831
+ throw error;
1832
+ }
1833
+ }
1834
+ function _locator(l){
1835
+ if(l){
1836
+ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
1837
+ }
1838
+ }
1839
+ function _toString(chars,start,length){
1840
+ if(typeof chars == 'string'){
1841
+ return chars.substr(start,length)
1842
+ }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
1843
+ if(chars.length >= start+length || start){
1844
+ return new java.lang.String(chars,start,length)+'';
1845
+ }
1846
+ return chars;
1847
+ }
1848
+ }
1849
+
1850
+ /*
1851
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
1852
+ * used method of org.xml.sax.ext.LexicalHandler:
1853
+ * #comment(chars, start, length)
1854
+ * #startCDATA()
1855
+ * #endCDATA()
1856
+ * #startDTD(name, publicId, systemId)
1857
+ *
1858
+ *
1859
+ * IGNORED method of org.xml.sax.ext.LexicalHandler:
1860
+ * #endDTD()
1861
+ * #startEntity(name)
1862
+ * #endEntity(name)
1863
+ *
1864
+ *
1865
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
1866
+ * IGNORED method of org.xml.sax.ext.DeclHandler
1867
+ * #attributeDecl(eName, aName, type, mode, value)
1868
+ * #elementDecl(name, model)
1869
+ * #externalEntityDecl(name, publicId, systemId)
1870
+ * #internalEntityDecl(name, value)
1871
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
1872
+ * IGNORED method of org.xml.sax.EntityResolver2
1873
+ * #resolveEntity(String name,String publicId,String baseURI,String systemId)
1874
+ * #resolveEntity(publicId, systemId)
1875
+ * #getExternalSubset(name, baseURI)
1876
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
1877
+ * IGNORED method of org.xml.sax.DTDHandler
1878
+ * #notationDecl(name, publicId, systemId) {};
1879
+ * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
1880
+ */
1881
+ "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
1882
+ DOMHandler.prototype[key] = function(){return null}
1883
+ })
1884
+
1885
+ /* 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 */
1886
+ function appendElement (hander,node) {
1887
+ if (!hander.currentElement) {
1888
+ hander.document.appendChild(node);
1889
+ } else {
1890
+ hander.currentElement.appendChild(node);
1891
+ }
1892
+ }//appendChild and setAttributeNS are preformance key
1893
+
1894
+ if(typeof require == 'function'){
1895
+ var XMLReader = require('./sax').XMLReader;
1896
+ var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
1897
+ exports.XMLSerializer = require('./dom').XMLSerializer ;
1898
+ exports.DOMParser = DOMParser;
1899
+ }
1900
+
1901
+ },{"./dom":7,"./sax":8}],7:[function(require,module,exports){
1902
+ /*
1903
+ * DOM Level 2
1904
+ * Object DOMException
1905
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
1906
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
1907
+ */
1908
+
1909
+ function copy(src,dest){
1910
+ for(var p in src){
1911
+ dest[p] = src[p];
1912
+ }
1913
+ }
1914
+ /**
1915
+ ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
1916
+ ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
1917
+ */
1918
+ function _extends(Class,Super){
1919
+ var pt = Class.prototype;
1920
+ if(Object.create){
1921
+ var ppt = Object.create(Super.prototype)
1922
+ pt.__proto__ = ppt;
1923
+ }
1924
+ if(!(pt instanceof Super)){
1925
+ function t(){};
1926
+ t.prototype = Super.prototype;
1927
+ t = new t();
1928
+ copy(pt,t);
1929
+ Class.prototype = pt = t;
1930
+ }
1931
+ if(pt.constructor != Class){
1932
+ if(typeof Class != 'function'){
1933
+ console.error("unknow Class:"+Class)
1934
+ }
1935
+ pt.constructor = Class
1936
+ }
1937
+ }
1938
+ var htmlns = 'http://www.w3.org/1999/xhtml' ;
1939
+ // Node Types
1940
+ var NodeType = {}
1941
+ var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
1942
+ var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
1943
+ var TEXT_NODE = NodeType.TEXT_NODE = 3;
1944
+ var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
1945
+ var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
1946
+ var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
1947
+ var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
1948
+ var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
1949
+ var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
1950
+ var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
1951
+ var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
1952
+ var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
1953
+
1954
+ // ExceptionCode
1955
+ var ExceptionCode = {}
1956
+ var ExceptionMessage = {};
1957
+ var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
1958
+ var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
1959
+ var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
1960
+ var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
1961
+ var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
1962
+ var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
1963
+ var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
1964
+ var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
1965
+ var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
1966
+ var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
1967
+ //level2
1968
+ var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
1969
+ var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
1970
+ var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
1971
+ var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
1972
+ var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
1973
+
1974
+
1975
+ function DOMException(code, message) {
1976
+ if(message instanceof Error){
1977
+ var error = message;
1978
+ }else{
1979
+ error = this;
1980
+ Error.call(this, ExceptionMessage[code]);
1981
+ this.message = ExceptionMessage[code];
1982
+ if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
1983
+ }
1984
+ error.code = code;
1985
+ if(message) this.message = this.message + ": " + message;
1986
+ return error;
1987
+ };
1988
+ DOMException.prototype = Error.prototype;
1989
+ copy(ExceptionCode,DOMException)
1990
+ /**
1991
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
1992
+ * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
1993
+ * The items in the NodeList are accessible via an integral index, starting from 0.
1994
+ */
1995
+ function NodeList() {
1996
+ };
1997
+ NodeList.prototype = {
1998
+ /**
1999
+ * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
2000
+ * @standard level1
2001
+ */
2002
+ length:0,
2003
+ /**
2004
+ * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
2005
+ * @standard level1
2006
+ * @param index unsigned long
2007
+ * Index into the collection.
2008
+ * @return Node
2009
+ * The node at the indexth position in the NodeList, or null if that is not a valid index.
2010
+ */
2011
+ item: function(index) {
2012
+ return this[index] || null;
2013
+ }
2014
+ };
2015
+ function LiveNodeList(node,refresh){
2016
+ this._node = node;
2017
+ this._refresh = refresh
2018
+ _updateLiveList(this);
2019
+ }
2020
+ function _updateLiveList(list){
2021
+ var inc = list._node._inc || list._node.ownerDocument._inc;
2022
+ if(list._inc != inc){
2023
+ var ls = list._refresh(list._node);
2024
+ //console.log(ls.length)
2025
+ __set__(list,'length',ls.length);
2026
+ copy(ls,list);
2027
+ list._inc = inc;
2028
+ }
2029
+ }
2030
+ LiveNodeList.prototype.item = function(i){
2031
+ _updateLiveList(this);
2032
+ return this[i];
2033
+ }
2034
+
2035
+ _extends(LiveNodeList,NodeList);
2036
+ /**
2037
+ *
2038
+ * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
2039
+ * NamedNodeMap objects in the DOM are live.
2040
+ * used for attributes or DocumentType entities
2041
+ */
2042
+ function NamedNodeMap() {
2043
+ };
2044
+
2045
+ function _findNodeIndex(list,node){
2046
+ var i = list.length;
2047
+ while(i--){
2048
+ if(list[i] === node){return i}
2049
+ }
2050
+ }
2051
+
2052
+ function _addNamedNode(el,list,newAttr,oldAttr){
2053
+ if(oldAttr){
2054
+ list[_findNodeIndex(list,oldAttr)] = newAttr;
2055
+ }else{
2056
+ list[list.length++] = newAttr;
2057
+ }
2058
+ if(el){
2059
+ newAttr.ownerElement = el;
2060
+ var doc = el.ownerDocument;
2061
+ if(doc){
2062
+ oldAttr && _onRemoveAttribute(doc,el,oldAttr);
2063
+ _onAddAttribute(doc,el,newAttr);
2064
+ }
2065
+ }
2066
+ }
2067
+ function _removeNamedNode(el,list,attr){
2068
+ var i = _findNodeIndex(list,attr);
2069
+ if(i>=0){
2070
+ var lastIndex = list.length-1
2071
+ while(i<lastIndex){
2072
+ list[i] = list[++i]
2073
+ }
2074
+ list.length = lastIndex;
2075
+ if(el){
2076
+ var doc = el.ownerDocument;
2077
+ if(doc){
2078
+ _onRemoveAttribute(doc,el,attr);
2079
+ attr.ownerElement = null;
2080
+ }
2081
+ }
2082
+ }else{
2083
+ throw DOMException(NOT_FOUND_ERR,new Error())
2084
+ }
2085
+ }
2086
+ NamedNodeMap.prototype = {
2087
+ length:0,
2088
+ item:NodeList.prototype.item,
2089
+ getNamedItem: function(key) {
2090
+ // if(key.indexOf(':')>0 || key == 'xmlns'){
2091
+ // return null;
2092
+ // }
2093
+ var i = this.length;
2094
+ while(i--){
2095
+ var attr = this[i];
2096
+ if(attr.nodeName == key){
2097
+ return attr;
2098
+ }
2099
+ }
2100
+ },
2101
+ setNamedItem: function(attr) {
2102
+ var el = attr.ownerElement;
2103
+ if(el && el!=this._ownerElement){
2104
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
2105
+ }
2106
+ var oldAttr = this.getNamedItem(attr.nodeName);
2107
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
2108
+ return oldAttr;
2109
+ },
2110
+ /* returns Node */
2111
+ setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
2112
+ var el = attr.ownerElement, oldAttr;
2113
+ if(el && el!=this._ownerElement){
2114
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
2115
+ }
2116
+ oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
2117
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
2118
+ return oldAttr;
2119
+ },
2120
+
2121
+ /* returns Node */
2122
+ removeNamedItem: function(key) {
2123
+ var attr = this.getNamedItem(key);
2124
+ _removeNamedNode(this._ownerElement,this,attr);
2125
+ return attr;
2126
+
2127
+
2128
+ },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
2129
+
2130
+ //for level2
2131
+ removeNamedItemNS:function(namespaceURI,localName){
2132
+ var attr = this.getNamedItemNS(namespaceURI,localName);
2133
+ _removeNamedNode(this._ownerElement,this,attr);
2134
+ return attr;
2135
+ },
2136
+ getNamedItemNS: function(namespaceURI, localName) {
2137
+ var i = this.length;
2138
+ while(i--){
2139
+ var node = this[i];
2140
+ if(node.localName == localName && node.namespaceURI == namespaceURI){
2141
+ return node;
2142
+ }
2143
+ }
2144
+ return null;
2145
+ }
2146
+ };
2147
+ /**
2148
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
2149
+ */
2150
+ function DOMImplementation(/* Object */ features) {
2151
+ this._features = {};
2152
+ if (features) {
2153
+ for (var feature in features) {
2154
+ this._features = features[feature];
2155
+ }
2156
+ }
2157
+ };
2158
+
2159
+ DOMImplementation.prototype = {
2160
+ hasFeature: function(/* string */ feature, /* string */ version) {
2161
+ var versions = this._features[feature.toLowerCase()];
2162
+ if (versions && (!version || version in versions)) {
2163
+ return true;
2164
+ } else {
2165
+ return false;
2166
+ }
2167
+ },
2168
+ // Introduced in DOM Level 2:
2169
+ createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
2170
+ var doc = new Document();
2171
+ doc.doctype = doctype;
2172
+ if(doctype){
2173
+ doc.appendChild(doctype);
2174
+ }
2175
+ doc.implementation = this;
2176
+ doc.childNodes = new NodeList();
2177
+ if(qualifiedName){
2178
+ var root = doc.createElementNS(namespaceURI,qualifiedName);
2179
+ doc.appendChild(root);
2180
+ }
2181
+ return doc;
2182
+ },
2183
+ // Introduced in DOM Level 2:
2184
+ createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
2185
+ var node = new DocumentType();
2186
+ node.name = qualifiedName;
2187
+ node.nodeName = qualifiedName;
2188
+ node.publicId = publicId;
2189
+ node.systemId = systemId;
2190
+ // Introduced in DOM Level 2:
2191
+ //readonly attribute DOMString internalSubset;
2192
+
2193
+ //TODO:..
2194
+ // readonly attribute NamedNodeMap entities;
2195
+ // readonly attribute NamedNodeMap notations;
2196
+ return node;
2197
+ }
2198
+ };
2199
+
2200
+
2201
+ /**
2202
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
2203
+ */
2204
+
2205
+ function Node() {
2206
+ };
2207
+
2208
+ Node.prototype = {
2209
+ firstChild : null,
2210
+ lastChild : null,
2211
+ previousSibling : null,
2212
+ nextSibling : null,
2213
+ attributes : null,
2214
+ parentNode : null,
2215
+ childNodes : null,
2216
+ ownerDocument : null,
2217
+ nodeValue : null,
2218
+ namespaceURI : null,
2219
+ prefix : null,
2220
+ localName : null,
2221
+ // Modified in DOM Level 2:
2222
+ insertBefore:function(newChild, refChild){//raises
2223
+ return _insertBefore(this,newChild,refChild);
2224
+ },
2225
+ replaceChild:function(newChild, oldChild){//raises
2226
+ this.insertBefore(newChild,oldChild);
2227
+ if(oldChild){
2228
+ this.removeChild(oldChild);
2229
+ }
2230
+ },
2231
+ removeChild:function(oldChild){
2232
+ return _removeChild(this,oldChild);
2233
+ },
2234
+ appendChild:function(newChild){
2235
+ return this.insertBefore(newChild,null);
2236
+ },
2237
+ hasChildNodes:function(){
2238
+ return this.firstChild != null;
2239
+ },
2240
+ cloneNode:function(deep){
2241
+ return cloneNode(this.ownerDocument||this,this,deep);
2242
+ },
2243
+ // Modified in DOM Level 2:
2244
+ normalize:function(){
2245
+ var child = this.firstChild;
2246
+ while(child){
2247
+ var next = child.nextSibling;
2248
+ if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
2249
+ this.removeChild(next);
2250
+ child.appendData(next.data);
2251
+ }else{
2252
+ child.normalize();
2253
+ child = next;
2254
+ }
2255
+ }
2256
+ },
2257
+ // Introduced in DOM Level 2:
2258
+ isSupported:function(feature, version){
2259
+ return this.ownerDocument.implementation.hasFeature(feature,version);
2260
+ },
2261
+ // Introduced in DOM Level 2:
2262
+ hasAttributes:function(){
2263
+ return this.attributes.length>0;
2264
+ },
2265
+ lookupPrefix:function(namespaceURI){
2266
+ var el = this;
2267
+ while(el){
2268
+ var map = el._nsMap;
2269
+ //console.dir(map)
2270
+ if(map){
2271
+ for(var n in map){
2272
+ if(map[n] == namespaceURI){
2273
+ return n;
2274
+ }
2275
+ }
2276
+ }
2277
+ el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2278
+ }
2279
+ return null;
2280
+ },
2281
+ // Introduced in DOM Level 3:
2282
+ lookupNamespaceURI:function(prefix){
2283
+ var el = this;
2284
+ while(el){
2285
+ var map = el._nsMap;
2286
+ //console.dir(map)
2287
+ if(map){
2288
+ if(prefix in map){
2289
+ return map[prefix] ;
2290
+ }
2291
+ }
2292
+ el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2293
+ }
2294
+ return null;
2295
+ },
2296
+ // Introduced in DOM Level 3:
2297
+ isDefaultNamespace:function(namespaceURI){
2298
+ var prefix = this.lookupPrefix(namespaceURI);
2299
+ return prefix == null;
2300
+ }
2301
+ };
2302
+
2303
+
2304
+ function _xmlEncoder(c){
2305
+ return c == '<' && '&lt;' ||
2306
+ c == '>' && '&gt;' ||
2307
+ c == '&' && '&amp;' ||
2308
+ c == '"' && '&quot;' ||
2309
+ '&#'+c.charCodeAt()+';'
2310
+ }
2311
+
2312
+
2313
+ copy(NodeType,Node);
2314
+ copy(NodeType,Node.prototype);
2315
+
2316
+ /**
2317
+ * @param callback return true for continue,false for break
2318
+ * @return boolean true: break visit;
2319
+ */
2320
+ function _visitNode(node,callback){
2321
+ if(callback(node)){
2322
+ return true;
2323
+ }
2324
+ if(node = node.firstChild){
2325
+ do{
2326
+ if(_visitNode(node,callback)){return true}
2327
+ }while(node=node.nextSibling)
2328
+ }
2329
+ }
2330
+
2331
+
2332
+
2333
+ function Document(){
2334
+ }
2335
+ function _onAddAttribute(doc,el,newAttr){
2336
+ doc && doc._inc++;
2337
+ var ns = newAttr.namespaceURI ;
2338
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
2339
+ //update namespace
2340
+ el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
2341
+ }
2342
+ }
2343
+ function _onRemoveAttribute(doc,el,newAttr,remove){
2344
+ doc && doc._inc++;
2345
+ var ns = newAttr.namespaceURI ;
2346
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
2347
+ //update namespace
2348
+ delete el._nsMap[newAttr.prefix?newAttr.localName:'']
2349
+ }
2350
+ }
2351
+ function _onUpdateChild(doc,el,newChild){
2352
+ if(doc && doc._inc){
2353
+ doc._inc++;
2354
+ //update childNodes
2355
+ var cs = el.childNodes;
2356
+ if(newChild){
2357
+ cs[cs.length++] = newChild;
2358
+ }else{
2359
+ //console.log(1)
2360
+ var child = el.firstChild;
2361
+ var i = 0;
2362
+ while(child){
2363
+ cs[i++] = child;
2364
+ child =child.nextSibling;
2365
+ }
2366
+ cs.length = i;
2367
+ }
2368
+ }
2369
+ }
2370
+
2371
+ /**
2372
+ * attributes;
2373
+ * children;
2374
+ *
2375
+ * writeable properties:
2376
+ * nodeValue,Attr:value,CharacterData:data
2377
+ * prefix
2378
+ */
2379
+ function _removeChild(parentNode,child){
2380
+ var previous = child.previousSibling;
2381
+ var next = child.nextSibling;
2382
+ if(previous){
2383
+ previous.nextSibling = next;
2384
+ }else{
2385
+ parentNode.firstChild = next
2386
+ }
2387
+ if(next){
2388
+ next.previousSibling = previous;
2389
+ }else{
2390
+ parentNode.lastChild = previous;
2391
+ }
2392
+ _onUpdateChild(parentNode.ownerDocument,parentNode);
2393
+ return child;
2394
+ }
2395
+ /**
2396
+ * preformance key(refChild == null)
2397
+ */
2398
+ function _insertBefore(parentNode,newChild,nextChild){
2399
+ var cp = newChild.parentNode;
2400
+ if(cp){
2401
+ cp.removeChild(newChild);//remove and update
2402
+ }
2403
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
2404
+ var newFirst = newChild.firstChild;
2405
+ if (newFirst == null) {
2406
+ return newChild;
2407
+ }
2408
+ var newLast = newChild.lastChild;
2409
+ }else{
2410
+ newFirst = newLast = newChild;
2411
+ }
2412
+ var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
2413
+
2414
+ newFirst.previousSibling = pre;
2415
+ newLast.nextSibling = nextChild;
2416
+
2417
+
2418
+ if(pre){
2419
+ pre.nextSibling = newFirst;
2420
+ }else{
2421
+ parentNode.firstChild = newFirst;
2422
+ }
2423
+ if(nextChild == null){
2424
+ parentNode.lastChild = newLast;
2425
+ }else{
2426
+ nextChild.previousSibling = newLast;
2427
+ }
2428
+ do{
2429
+ newFirst.parentNode = parentNode;
2430
+ }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
2431
+ _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
2432
+ //console.log(parentNode.lastChild.nextSibling == null)
2433
+ if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
2434
+ newChild.firstChild = newChild.lastChild = null;
2435
+ }
2436
+ return newChild;
2437
+ }
2438
+ function _appendSingleChild(parentNode,newChild){
2439
+ var cp = newChild.parentNode;
2440
+ if(cp){
2441
+ var pre = parentNode.lastChild;
2442
+ cp.removeChild(newChild);//remove and update
2443
+ var pre = parentNode.lastChild;
2444
+ }
2445
+ var pre = parentNode.lastChild;
2446
+ newChild.parentNode = parentNode;
2447
+ newChild.previousSibling = pre;
2448
+ newChild.nextSibling = null;
2449
+ if(pre){
2450
+ pre.nextSibling = newChild;
2451
+ }else{
2452
+ parentNode.firstChild = newChild;
2453
+ }
2454
+ parentNode.lastChild = newChild;
2455
+ _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
2456
+ return newChild;
2457
+ //console.log("__aa",parentNode.lastChild.nextSibling == null)
2458
+ }
2459
+ Document.prototype = {
2460
+ //implementation : null,
2461
+ nodeName : '#document',
2462
+ nodeType : DOCUMENT_NODE,
2463
+ doctype : null,
2464
+ documentElement : null,
2465
+ _inc : 1,
2466
+
2467
+ insertBefore : function(newChild, refChild){//raises
2468
+ if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
2469
+ var child = newChild.firstChild;
2470
+ while(child){
2471
+ var next = child.nextSibling;
2472
+ this.insertBefore(child,refChild);
2473
+ child = next;
2474
+ }
2475
+ return newChild;
2476
+ }
2477
+ if(this.documentElement == null && newChild.nodeType == 1){
2478
+ this.documentElement = newChild;
2479
+ }
2480
+
2481
+ return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
2482
+ },
2483
+ removeChild : function(oldChild){
2484
+ if(this.documentElement == oldChild){
2485
+ this.documentElement = null;
2486
+ }
2487
+ return _removeChild(this,oldChild);
2488
+ },
2489
+ // Introduced in DOM Level 2:
2490
+ importNode : function(importedNode,deep){
2491
+ return importNode(this,importedNode,deep);
2492
+ },
2493
+ // Introduced in DOM Level 2:
2494
+ getElementById : function(id){
2495
+ var rtv = null;
2496
+ _visitNode(this.documentElement,function(node){
2497
+ if(node.nodeType == 1){
2498
+ if(node.getAttribute('id') == id){
2499
+ rtv = node;
2500
+ return true;
2501
+ }
2502
+ }
2503
+ })
2504
+ return rtv;
2505
+ },
2506
+
2507
+ //document factory method:
2508
+ createElement : function(tagName){
2509
+ var node = new Element();
2510
+ node.ownerDocument = this;
2511
+ node.nodeName = tagName;
2512
+ node.tagName = tagName;
2513
+ node.childNodes = new NodeList();
2514
+ var attrs = node.attributes = new NamedNodeMap();
2515
+ attrs._ownerElement = node;
2516
+ return node;
2517
+ },
2518
+ createDocumentFragment : function(){
2519
+ var node = new DocumentFragment();
2520
+ node.ownerDocument = this;
2521
+ node.childNodes = new NodeList();
2522
+ return node;
2523
+ },
2524
+ createTextNode : function(data){
2525
+ var node = new Text();
2526
+ node.ownerDocument = this;
2527
+ node.appendData(data)
2528
+ return node;
2529
+ },
2530
+ createComment : function(data){
2531
+ var node = new Comment();
2532
+ node.ownerDocument = this;
2533
+ node.appendData(data)
2534
+ return node;
2535
+ },
2536
+ createCDATASection : function(data){
2537
+ var node = new CDATASection();
2538
+ node.ownerDocument = this;
2539
+ node.appendData(data)
2540
+ return node;
2541
+ },
2542
+ createProcessingInstruction : function(target,data){
2543
+ var node = new ProcessingInstruction();
2544
+ node.ownerDocument = this;
2545
+ node.tagName = node.target = target;
2546
+ node.nodeValue= node.data = data;
2547
+ return node;
2548
+ },
2549
+ createAttribute : function(name){
2550
+ var node = new Attr();
2551
+ node.ownerDocument = this;
2552
+ node.name = name;
2553
+ node.nodeName = name;
2554
+ node.localName = name;
2555
+ node.specified = true;
2556
+ return node;
2557
+ },
2558
+ createEntityReference : function(name){
2559
+ var node = new EntityReference();
2560
+ node.ownerDocument = this;
2561
+ node.nodeName = name;
2562
+ return node;
2563
+ },
2564
+ // Introduced in DOM Level 2:
2565
+ createElementNS : function(namespaceURI,qualifiedName){
2566
+ var node = new Element();
2567
+ var pl = qualifiedName.split(':');
2568
+ var attrs = node.attributes = new NamedNodeMap();
2569
+ node.childNodes = new NodeList();
2570
+ node.ownerDocument = this;
2571
+ node.nodeName = qualifiedName;
2572
+ node.tagName = qualifiedName;
2573
+ node.namespaceURI = namespaceURI;
2574
+ if(pl.length == 2){
2575
+ node.prefix = pl[0];
2576
+ node.localName = pl[1];
2577
+ }else{
2578
+ //el.prefix = null;
2579
+ node.localName = qualifiedName;
2580
+ }
2581
+ attrs._ownerElement = node;
2582
+ return node;
2583
+ },
2584
+ // Introduced in DOM Level 2:
2585
+ createAttributeNS : function(namespaceURI,qualifiedName){
2586
+ var node = new Attr();
2587
+ var pl = qualifiedName.split(':');
2588
+ node.ownerDocument = this;
2589
+ node.nodeName = qualifiedName;
2590
+ node.name = qualifiedName;
2591
+ node.namespaceURI = namespaceURI;
2592
+ node.specified = true;
2593
+ if(pl.length == 2){
2594
+ node.prefix = pl[0];
2595
+ node.localName = pl[1];
2596
+ }else{
2597
+ //el.prefix = null;
2598
+ node.localName = qualifiedName;
2599
+ }
2600
+ return node;
2601
+ }
2602
+ };
2603
+ _extends(Document,Node);
2604
+
2605
+
2606
+ function Element() {
2607
+ this._nsMap = {};
2608
+ };
2609
+ Element.prototype = {
2610
+ nodeType : ELEMENT_NODE,
2611
+ hasAttribute : function(name){
2612
+ return this.getAttributeNode(name)!=null;
2613
+ },
2614
+ getAttribute : function(name){
2615
+ var attr = this.getAttributeNode(name);
2616
+ return attr && attr.value || '';
2617
+ },
2618
+ getAttributeNode : function(name){
2619
+ return this.attributes.getNamedItem(name);
2620
+ },
2621
+ setAttribute : function(name, value){
2622
+ var attr = this.ownerDocument.createAttribute(name);
2623
+ attr.value = attr.nodeValue = "" + value;
2624
+ this.setAttributeNode(attr)
2625
+ },
2626
+ removeAttribute : function(name){
2627
+ var attr = this.getAttributeNode(name)
2628
+ attr && this.removeAttributeNode(attr);
2629
+ },
2630
+
2631
+ //four real opeartion method
2632
+ appendChild:function(newChild){
2633
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
2634
+ return this.insertBefore(newChild,null);
2635
+ }else{
2636
+ return _appendSingleChild(this,newChild);
2637
+ }
2638
+ },
2639
+ setAttributeNode : function(newAttr){
2640
+ return this.attributes.setNamedItem(newAttr);
2641
+ },
2642
+ setAttributeNodeNS : function(newAttr){
2643
+ return this.attributes.setNamedItemNS(newAttr);
2644
+ },
2645
+ removeAttributeNode : function(oldAttr){
2646
+ return this.attributes.removeNamedItem(oldAttr.nodeName);
2647
+ },
2648
+ //get real attribute name,and remove it by removeAttributeNode
2649
+ removeAttributeNS : function(namespaceURI, localName){
2650
+ var old = this.getAttributeNodeNS(namespaceURI, localName);
2651
+ old && this.removeAttributeNode(old);
2652
+ },
2653
+
2654
+ hasAttributeNS : function(namespaceURI, localName){
2655
+ return this.getAttributeNodeNS(namespaceURI, localName)!=null;
2656
+ },
2657
+ getAttributeNS : function(namespaceURI, localName){
2658
+ var attr = this.getAttributeNodeNS(namespaceURI, localName);
2659
+ return attr && attr.value || '';
2660
+ },
2661
+ setAttributeNS : function(namespaceURI, qualifiedName, value){
2662
+ var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
2663
+ attr.value = attr.nodeValue = value;
2664
+ this.setAttributeNode(attr)
2665
+ },
2666
+ getAttributeNodeNS : function(namespaceURI, localName){
2667
+ return this.attributes.getNamedItemNS(namespaceURI, localName);
2668
+ },
2669
+
2670
+ getElementsByTagName : function(tagName){
2671
+ return new LiveNodeList(this,function(base){
2672
+ var ls = [];
2673
+ _visitNode(base,function(node){
2674
+ if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
2675
+ ls.push(node);
2676
+ }
2677
+ });
2678
+ return ls;
2679
+ });
2680
+ },
2681
+ getElementsByTagNameNS : function(namespaceURI, localName){
2682
+ return new LiveNodeList(this,function(base){
2683
+ var ls = [];
2684
+ _visitNode(base,function(node){
2685
+ if(node !== base && node.nodeType === ELEMENT_NODE && node.namespaceURI === namespaceURI && (localName === '*' || node.localName == localName)){
2686
+ ls.push(node);
2687
+ }
2688
+ });
2689
+ return ls;
2690
+ });
2691
+ }
2692
+ };
2693
+ Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
2694
+ Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
2695
+
2696
+
2697
+ _extends(Element,Node);
2698
+ function Attr() {
2699
+ };
2700
+ Attr.prototype.nodeType = ATTRIBUTE_NODE;
2701
+ _extends(Attr,Node);
2702
+
2703
+
2704
+ function CharacterData() {
2705
+ };
2706
+ CharacterData.prototype = {
2707
+ data : '',
2708
+ substringData : function(offset, count) {
2709
+ return this.data.substring(offset, offset+count);
2710
+ },
2711
+ appendData: function(text) {
2712
+ text = this.data+text;
2713
+ this.nodeValue = this.data = text;
2714
+ this.length = text.length;
2715
+ },
2716
+ insertData: function(offset,text) {
2717
+ this.replaceData(offset,0,text);
2718
+
2719
+ },
2720
+ appendChild:function(newChild){
2721
+ //if(!(newChild instanceof CharacterData)){
2722
+ throw new Error(ExceptionMessage[3])
2723
+ //}
2724
+ return Node.prototype.appendChild.apply(this,arguments)
2725
+ },
2726
+ deleteData: function(offset, count) {
2727
+ this.replaceData(offset,count,"");
2728
+ },
2729
+ replaceData: function(offset, count, text) {
2730
+ var start = this.data.substring(0,offset);
2731
+ var end = this.data.substring(offset+count);
2732
+ text = start + text + end;
2733
+ this.nodeValue = this.data = text;
2734
+ this.length = text.length;
2735
+ }
2736
+ }
2737
+ _extends(CharacterData,Node);
2738
+ function Text() {
2739
+ };
2740
+ Text.prototype = {
2741
+ nodeName : "#text",
2742
+ nodeType : TEXT_NODE,
2743
+ splitText : function(offset) {
2744
+ var text = this.data;
2745
+ var newText = text.substring(offset);
2746
+ text = text.substring(0, offset);
2747
+ this.data = this.nodeValue = text;
2748
+ this.length = text.length;
2749
+ var newNode = this.ownerDocument.createTextNode(newText);
2750
+ if(this.parentNode){
2751
+ this.parentNode.insertBefore(newNode, this.nextSibling);
2752
+ }
2753
+ return newNode;
2754
+ }
2755
+ }
2756
+ _extends(Text,CharacterData);
2757
+ function Comment() {
2758
+ };
2759
+ Comment.prototype = {
2760
+ nodeName : "#comment",
2761
+ nodeType : COMMENT_NODE
2762
+ }
2763
+ _extends(Comment,CharacterData);
2764
+
2765
+ function CDATASection() {
2766
+ };
2767
+ CDATASection.prototype = {
2768
+ nodeName : "#cdata-section",
2769
+ nodeType : CDATA_SECTION_NODE
2770
+ }
2771
+ _extends(CDATASection,CharacterData);
2772
+
2773
+
2774
+ function DocumentType() {
2775
+ };
2776
+ DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
2777
+ _extends(DocumentType,Node);
2778
+
2779
+ function Notation() {
2780
+ };
2781
+ Notation.prototype.nodeType = NOTATION_NODE;
2782
+ _extends(Notation,Node);
2783
+
2784
+ function Entity() {
2785
+ };
2786
+ Entity.prototype.nodeType = ENTITY_NODE;
2787
+ _extends(Entity,Node);
2788
+
2789
+ function EntityReference() {
2790
+ };
2791
+ EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
2792
+ _extends(EntityReference,Node);
2793
+
2794
+ function DocumentFragment() {
2795
+ };
2796
+ DocumentFragment.prototype.nodeName = "#document-fragment";
2797
+ DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
2798
+ _extends(DocumentFragment,Node);
2799
+
2800
+
2801
+ function ProcessingInstruction() {
2802
+ }
2803
+ ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
2804
+ _extends(ProcessingInstruction,Node);
2805
+ function XMLSerializer(){}
2806
+ XMLSerializer.prototype.serializeToString = function(node){
2807
+ var buf = [];
2808
+ serializeToString(node,buf);
2809
+ return buf.join('');
2810
+ }
2811
+ Node.prototype.toString =function(){
2812
+ return XMLSerializer.prototype.serializeToString(this);
2813
+ }
2814
+ function serializeToString(node,buf){
2815
+ switch(node.nodeType){
2816
+ case ELEMENT_NODE:
2817
+ var attrs = node.attributes;
2818
+ var len = attrs.length;
2819
+ var child = node.firstChild;
2820
+ var nodeName = node.tagName;
2821
+ var isHTML = htmlns === node.namespaceURI
2822
+ buf.push('<',nodeName);
2823
+ for(var i=0;i<len;i++){
2824
+ serializeToString(attrs.item(i),buf,isHTML);
2825
+ }
2826
+ if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
2827
+ buf.push('>');
2828
+ //if is cdata child node
2829
+ if(isHTML && /^script$/i.test(nodeName)){
2830
+ if(child){
2831
+ buf.push(child.data);
2832
+ }
2833
+ }else{
2834
+ while(child){
2835
+ serializeToString(child,buf);
2836
+ child = child.nextSibling;
2837
+ }
2838
+ }
2839
+ buf.push('</',nodeName,'>');
2840
+ }else{
2841
+ buf.push('/>');
2842
+ }
2843
+ return;
2844
+ case DOCUMENT_NODE:
2845
+ case DOCUMENT_FRAGMENT_NODE:
2846
+ var child = node.firstChild;
2847
+ while(child){
2848
+ serializeToString(child,buf);
2849
+ child = child.nextSibling;
2850
+ }
2851
+ return;
2852
+ case ATTRIBUTE_NODE:
2853
+ return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
2854
+ case TEXT_NODE:
2855
+ return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
2856
+ case CDATA_SECTION_NODE:
2857
+ return buf.push( '<![CDATA[',node.data,']]>');
2858
+ case COMMENT_NODE:
2859
+ return buf.push( "<!--",node.data,"-->");
2860
+ case DOCUMENT_TYPE_NODE:
2861
+ var pubid = node.publicId;
2862
+ var sysid = node.systemId;
2863
+ buf.push('<!DOCTYPE ',node.name);
2864
+ if(pubid){
2865
+ buf.push(' PUBLIC "',pubid);
2866
+ if (sysid && sysid!='.') {
2867
+ buf.push( '" "',sysid);
2868
+ }
2869
+ buf.push('">');
2870
+ }else if(sysid && sysid!='.'){
2871
+ buf.push(' SYSTEM "',sysid,'">');
2872
+ }else{
2873
+ var sub = node.internalSubset;
2874
+ if(sub){
2875
+ buf.push(" [",sub,"]");
2876
+ }
2877
+ buf.push(">");
2878
+ }
2879
+ return;
2880
+ case PROCESSING_INSTRUCTION_NODE:
2881
+ return buf.push( "<?",node.target," ",node.data,"?>");
2882
+ case ENTITY_REFERENCE_NODE:
2883
+ return buf.push( '&',node.nodeName,';');
2884
+ //case ENTITY_NODE:
2885
+ //case NOTATION_NODE:
2886
+ default:
2887
+ buf.push('??',node.nodeName);
2888
+ }
2889
+ }
2890
+ function importNode(doc,node,deep){
2891
+ var node2;
2892
+ switch (node.nodeType) {
2893
+ case ELEMENT_NODE:
2894
+ node2 = node.cloneNode(false);
2895
+ node2.ownerDocument = doc;
2896
+ //var attrs = node2.attributes;
2897
+ //var len = attrs.length;
2898
+ //for(var i=0;i<len;i++){
2899
+ //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
2900
+ //}
2901
+ case DOCUMENT_FRAGMENT_NODE:
2902
+ break;
2903
+ case ATTRIBUTE_NODE:
2904
+ deep = true;
2905
+ break;
2906
+ //case ENTITY_REFERENCE_NODE:
2907
+ //case PROCESSING_INSTRUCTION_NODE:
2908
+ ////case TEXT_NODE:
2909
+ //case CDATA_SECTION_NODE:
2910
+ //case COMMENT_NODE:
2911
+ // deep = false;
2912
+ // break;
2913
+ //case DOCUMENT_NODE:
2914
+ //case DOCUMENT_TYPE_NODE:
2915
+ //cannot be imported.
2916
+ //case ENTITY_NODE:
2917
+ //case NOTATION_NODE:
2918
+ //can not hit in level3
2919
+ //default:throw e;
2920
+ }
2921
+ if(!node2){
2922
+ node2 = node.cloneNode(false);//false
2923
+ }
2924
+ node2.ownerDocument = doc;
2925
+ node2.parentNode = null;
2926
+ if(deep){
2927
+ var child = node.firstChild;
2928
+ while(child){
2929
+ node2.appendChild(importNode(doc,child,deep));
2930
+ child = child.nextSibling;
2931
+ }
2932
+ }
2933
+ return node2;
2934
+ }
2935
+ //
2936
+ //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
2937
+ // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
2938
+ function cloneNode(doc,node,deep){
2939
+ var node2 = new node.constructor();
2940
+ for(var n in node){
2941
+ var v = node[n];
2942
+ if(typeof v != 'object' ){
2943
+ if(v != node2[n]){
2944
+ node2[n] = v;
2945
+ }
2946
+ }
2947
+ }
2948
+ if(node.childNodes){
2949
+ node2.childNodes = new NodeList();
2950
+ }
2951
+ node2.ownerDocument = doc;
2952
+ switch (node2.nodeType) {
2953
+ case ELEMENT_NODE:
2954
+ var attrs = node.attributes;
2955
+ var attrs2 = node2.attributes = new NamedNodeMap();
2956
+ var len = attrs.length
2957
+ attrs2._ownerElement = node2;
2958
+ for(var i=0;i<len;i++){
2959
+ node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
2960
+ }
2961
+ break;;
2962
+ case ATTRIBUTE_NODE:
2963
+ deep = true;
2964
+ }
2965
+ if(deep){
2966
+ var child = node.firstChild;
2967
+ while(child){
2968
+ node2.appendChild(cloneNode(doc,child,deep));
2969
+ child = child.nextSibling;
2970
+ }
2971
+ }
2972
+ return node2;
2973
+ }
2974
+
2975
+ function __set__(object,key,value){
2976
+ object[key] = value
2977
+ }
2978
+ //do dynamic
2979
+ try{
2980
+ if(Object.defineProperty){
2981
+ Object.defineProperty(LiveNodeList.prototype,'length',{
2982
+ get:function(){
2983
+ _updateLiveList(this);
2984
+ return this.$$length;
2985
+ }
2986
+ });
2987
+ Object.defineProperty(Node.prototype,'textContent',{
2988
+ get:function(){
2989
+ return getTextContent(this);
2990
+ },
2991
+ set:function(data){
2992
+ switch(this.nodeType){
2993
+ case 1:
2994
+ case 11:
2995
+ while(this.firstChild){
2996
+ this.removeChild(this.firstChild);
2997
+ }
2998
+ if(data || String(data)){
2999
+ this.appendChild(this.ownerDocument.createTextNode(data));
3000
+ }
3001
+ break;
3002
+ default:
3003
+ //TODO:
3004
+ this.data = data;
3005
+ this.value = value;
3006
+ this.nodeValue = data;
3007
+ }
3008
+ }
3009
+ })
3010
+
3011
+ function getTextContent(node){
3012
+ switch(node.nodeType){
3013
+ case 1:
3014
+ case 11:
3015
+ var buf = [];
3016
+ node = node.firstChild;
3017
+ while(node){
3018
+ if(node.nodeType!==7 && node.nodeType !==8){
3019
+ buf.push(getTextContent(node));
3020
+ }
3021
+ node = node.nextSibling;
3022
+ }
3023
+ return buf.join('');
3024
+ default:
3025
+ return node.nodeValue;
3026
+ }
3027
+ }
3028
+ __set__ = function(object,key,value){
3029
+ //console.log(value)
3030
+ object['$$'+key] = value
3031
+ }
3032
+ }
3033
+ }catch(e){//ie8
3034
+ }
3035
+
3036
+ if(typeof require == 'function'){
3037
+ exports.DOMImplementation = DOMImplementation;
3038
+ exports.XMLSerializer = XMLSerializer;
3039
+ }
3040
+
3041
+ },{}],8:[function(require,module,exports){
3042
+ //[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]
3043
+ //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
3044
+ //[5] Name ::= NameStartChar (NameChar)*
3045
+ 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
3046
+ var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\u00B7\u0300-\u036F\\ux203F-\u2040]");
3047
+ var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
3048
+ //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
3049
+ //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(',')
3050
+
3051
+ //S_TAG, S_ATTR, S_EQ, S_V
3052
+ //S_ATTR_S, S_E, S_S, S_C
3053
+ var S_TAG = 0;//tag name offerring
3054
+ var S_ATTR = 1;//attr name offerring
3055
+ var S_ATTR_S=2;//attr name end and space offer
3056
+ var S_EQ = 3;//=space?
3057
+ var S_V = 4;//attr value(no quot value only)
3058
+ var S_E = 5;//attr value end and no space(quot end)
3059
+ var S_S = 6;//(attr value end || tag end ) && (space offer)
3060
+ var S_C = 7;//closed el<el />
3061
+
3062
+ function XMLReader(){
3063
+
3064
+ }
3065
+
3066
+ XMLReader.prototype = {
3067
+ parse:function(source,defaultNSMap,entityMap){
3068
+ var domBuilder = this.domBuilder;
3069
+ domBuilder.startDocument();
3070
+ _copy(defaultNSMap ,defaultNSMap = {})
3071
+ parse(source,defaultNSMap,entityMap,
3072
+ domBuilder,this.errorHandler);
3073
+ domBuilder.endDocument();
3074
+ }
3075
+ }
3076
+ function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
3077
+ function fixedFromCharCode(code) {
3078
+ // String.prototype.fromCharCode does not supports
3079
+ // > 2 bytes unicode chars directly
3080
+ if (code > 0xffff) {
3081
+ code -= 0x10000;
3082
+ var surrogate1 = 0xd800 + (code >> 10)
3083
+ , surrogate2 = 0xdc00 + (code & 0x3ff);
3084
+
3085
+ return String.fromCharCode(surrogate1, surrogate2);
3086
+ } else {
3087
+ return String.fromCharCode(code);
3088
+ }
3089
+ }
3090
+ function entityReplacer(a){
3091
+ var k = a.slice(1,-1);
3092
+ if(k in entityMap){
3093
+ return entityMap[k];
3094
+ }else if(k.charAt(0) === '#'){
3095
+ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
3096
+ }else{
3097
+ errorHandler.error('entity not found:'+a);
3098
+ return a;
3099
+ }
3100
+ }
3101
+ function appendText(end){//has some bugs
3102
+ var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
3103
+ locator&&position(start);
3104
+ domBuilder.characters(xt,0,end-start);
3105
+ start = end
3106
+ }
3107
+ function position(start,m){
3108
+ while(start>=endPos && (m = linePattern.exec(source))){
3109
+ startPos = m.index;
3110
+ endPos = startPos + m[0].length;
3111
+ locator.lineNumber++;
3112
+ //console.log('line++:',locator,startPos,endPos)
3113
+ }
3114
+ locator.columnNumber = start-startPos+1;
3115
+ }
3116
+ var startPos = 0;
3117
+ var endPos = 0;
3118
+ var linePattern = /.+(?:\r\n?|\n)|.*$/g
3119
+ var locator = domBuilder.locator;
3120
+
3121
+ var parseStack = [{currentNSMap:defaultNSMapCopy}]
3122
+ var closeMap = {};
3123
+ var start = 0;
3124
+ while(true){
3125
+ var i = source.indexOf('<',start);
3126
+ if(i<0){
3127
+ if(!source.substr(start).match(/^\s*$/)){
3128
+ var doc = domBuilder.document;
3129
+ var text = doc.createTextNode(source.substr(start));
3130
+ doc.appendChild(text);
3131
+ domBuilder.currentElement = text;
3132
+ }
3133
+ return;
3134
+ }
3135
+ if(i>start){
3136
+ appendText(i);
3137
+ }
3138
+ switch(source.charAt(i+1)){
3139
+ case '/':
3140
+ var end = source.indexOf('>',i+3);
3141
+ var tagName = source.substring(i+2,end);
3142
+ var config = parseStack.pop();
3143
+ var localNSMap = config.localNSMap;
3144
+
3145
+ if(config.tagName != tagName){
3146
+ errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
3147
+ }
3148
+ domBuilder.endElement(config.uri,config.localName,tagName);
3149
+ if(localNSMap){
3150
+ for(var prefix in localNSMap){
3151
+ domBuilder.endPrefixMapping(prefix) ;
3152
+ }
3153
+ }
3154
+ end++;
3155
+ break;
3156
+ // end elment
3157
+ case '?':// <?...?>
3158
+ locator&&position(i);
3159
+ end = parseInstruction(source,i,domBuilder);
3160
+ break;
3161
+ case '!':// <!doctype,<![CDATA,<!--
3162
+ locator&&position(i);
3163
+ end = parseDCC(source,i,domBuilder,errorHandler);
3164
+ break;
3165
+ default:
3166
+ try{
3167
+ locator&&position(i);
3168
+
3169
+ var el = new ElementAttributes();
3170
+
3171
+ //elStartEnd
3172
+ var end = parseElementStartPart(source,i,el,entityReplacer,errorHandler);
3173
+ var len = el.length;
3174
+ //position fixed
3175
+ if(len && locator){
3176
+ var backup = copyLocator(locator,{});
3177
+ for(var i = 0;i<len;i++){
3178
+ var a = el[i];
3179
+ position(a.offset);
3180
+ a.offset = copyLocator(locator,{});
3181
+ }
3182
+ copyLocator(backup,locator);
3183
+ }
3184
+ if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
3185
+ el.closed = true;
3186
+ if(!entityMap.nbsp){
3187
+ errorHandler.warning('unclosed xml attribute');
3188
+ }
3189
+ }
3190
+ appendElement(el,domBuilder,parseStack);
3191
+
3192
+
3193
+ if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
3194
+ end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
3195
+ }else{
3196
+ end++;
3197
+ }
3198
+ }catch(e){
3199
+ errorHandler.error('element parse error: '+e);
3200
+ end = -1;
3201
+ }
3202
+
3203
+ }
3204
+ if(end<0){
3205
+ //TODO: 这里有可能sax回退,有位置错误风险
3206
+ appendText(i+1);
3207
+ }else{
3208
+ start = end;
3209
+ }
3210
+ }
3211
+ }
3212
+ function copyLocator(f,t){
3213
+ t.lineNumber = f.lineNumber;
3214
+ t.columnNumber = f.columnNumber;
3215
+ return t;
3216
+
3217
+ }
3218
+
3219
+ /**
3220
+ * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
3221
+ * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
3222
+ */
3223
+ function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
3224
+ var attrName;
3225
+ var value;
3226
+ var p = ++start;
3227
+ var s = S_TAG;//status
3228
+ while(true){
3229
+ var c = source.charAt(p);
3230
+ switch(c){
3231
+ case '=':
3232
+ if(s === S_ATTR){//attrName
3233
+ attrName = source.slice(start,p);
3234
+ s = S_EQ;
3235
+ }else if(s === S_ATTR_S){
3236
+ s = S_EQ;
3237
+ }else{
3238
+ //fatalError: equal must after attrName or space after attrName
3239
+ throw new Error('attribute equal must after attrName');
3240
+ }
3241
+ break;
3242
+ case '\'':
3243
+ case '"':
3244
+ if(s === S_EQ){//equal
3245
+ start = p+1;
3246
+ p = source.indexOf(c,start)
3247
+ if(p>0){
3248
+ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3249
+ el.add(attrName,value,start-1);
3250
+ s = S_E;
3251
+ }else{
3252
+ //fatalError: no end quot match
3253
+ throw new Error('attribute value no end \''+c+'\' match');
3254
+ }
3255
+ }else if(s == S_V){
3256
+ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3257
+ //console.log(attrName,value,start,p)
3258
+ el.add(attrName,value,start);
3259
+ //console.dir(el)
3260
+ errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
3261
+ start = p+1;
3262
+ s = S_E
3263
+ }else{
3264
+ //fatalError: no equal before
3265
+ throw new Error('attribute value must after "="');
3266
+ }
3267
+ break;
3268
+ case '/':
3269
+ switch(s){
3270
+ case S_TAG:
3271
+ el.setTagName(source.slice(start,p));
3272
+ case S_E:
3273
+ case S_S:
3274
+ case S_C:
3275
+ s = S_C;
3276
+ el.closed = true;
3277
+ case S_V:
3278
+ case S_ATTR:
3279
+ case S_ATTR_S:
3280
+ break;
3281
+ //case S_EQ:
3282
+ default:
3283
+ throw new Error("attribute invalid close char('/')")
3284
+ }
3285
+ break;
3286
+ case ''://end document
3287
+ //throw new Error('unexpected end of input')
3288
+ errorHandler.error('unexpected end of input');
3289
+ case '>':
3290
+ switch(s){
3291
+ case S_TAG:
3292
+ el.setTagName(source.slice(start,p));
3293
+ case S_E:
3294
+ case S_S:
3295
+ case S_C:
3296
+ break;//normal
3297
+ case S_V://Compatible state
3298
+ case S_ATTR:
3299
+ value = source.slice(start,p);
3300
+ if(value.slice(-1) === '/'){
3301
+ el.closed = true;
3302
+ value = value.slice(0,-1)
3303
+ }
3304
+ case S_ATTR_S:
3305
+ if(s === S_ATTR_S){
3306
+ value = attrName;
3307
+ }
3308
+ if(s == S_V){
3309
+ errorHandler.warning('attribute "'+value+'" missed quot(")!!');
3310
+ el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
3311
+ }else{
3312
+ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
3313
+ el.add(value,value,start)
3314
+ }
3315
+ break;
3316
+ case S_EQ:
3317
+ throw new Error('attribute value missed!!');
3318
+ }
3319
+ // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
3320
+ return p;
3321
+ /*xml space '\x20' | #x9 | #xD | #xA; */
3322
+ case '\u0080':
3323
+ c = ' ';
3324
+ default:
3325
+ if(c<= ' '){//space
3326
+ switch(s){
3327
+ case S_TAG:
3328
+ el.setTagName(source.slice(start,p));//tagName
3329
+ s = S_S;
3330
+ break;
3331
+ case S_ATTR:
3332
+ attrName = source.slice(start,p)
3333
+ s = S_ATTR_S;
3334
+ break;
3335
+ case S_V:
3336
+ var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
3337
+ errorHandler.warning('attribute "'+value+'" missed quot(")!!');
3338
+ el.add(attrName,value,start)
3339
+ case S_E:
3340
+ s = S_S;
3341
+ break;
3342
+ //case S_S:
3343
+ //case S_EQ:
3344
+ //case S_ATTR_S:
3345
+ // void();break;
3346
+ //case S_C:
3347
+ //ignore warning
3348
+ }
3349
+ }else{//not space
3350
+ //S_TAG, S_ATTR, S_EQ, S_V
3351
+ //S_ATTR_S, S_E, S_S, S_C
3352
+ switch(s){
3353
+ //case S_TAG:void();break;
3354
+ //case S_ATTR:void();break;
3355
+ //case S_V:void();break;
3356
+ case S_ATTR_S:
3357
+ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead!!')
3358
+ el.add(attrName,attrName,start);
3359
+ start = p;
3360
+ s = S_ATTR;
3361
+ break;
3362
+ case S_E:
3363
+ errorHandler.warning('attribute space is required"'+attrName+'"!!')
3364
+ case S_S:
3365
+ s = S_ATTR;
3366
+ start = p;
3367
+ break;
3368
+ case S_EQ:
3369
+ s = S_V;
3370
+ start = p;
3371
+ break;
3372
+ case S_C:
3373
+ throw new Error("elements closed character '/' and '>' must be connected to");
3374
+ }
3375
+ }
3376
+ }
3377
+ p++;
3378
+ }
3379
+ }
3380
+ /**
3381
+ * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
3382
+ */
3383
+ function appendElement(el,domBuilder,parseStack){
3384
+ var tagName = el.tagName;
3385
+ var localNSMap = null;
3386
+ var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
3387
+ var i = el.length;
3388
+ while(i--){
3389
+ var a = el[i];
3390
+ var qName = a.qName;
3391
+ var value = a.value;
3392
+ var nsp = qName.indexOf(':');
3393
+ if(nsp>0){
3394
+ var prefix = a.prefix = qName.slice(0,nsp);
3395
+ var localName = qName.slice(nsp+1);
3396
+ var nsPrefix = prefix === 'xmlns' && localName
3397
+ }else{
3398
+ localName = qName;
3399
+ prefix = null
3400
+ nsPrefix = qName === 'xmlns' && ''
3401
+ }
3402
+ //can not set prefix,because prefix !== ''
3403
+ a.localName = localName ;
3404
+ //prefix == null for no ns prefix attribute
3405
+ if(nsPrefix !== false){//hack!!
3406
+ if(localNSMap == null){
3407
+ localNSMap = {}
3408
+ //console.log(currentNSMap,0)
3409
+ _copy(currentNSMap,currentNSMap={})
3410
+ //console.log(currentNSMap,1)
3411
+ }
3412
+ currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
3413
+ a.uri = 'http://www.w3.org/2000/xmlns/'
3414
+ domBuilder.startPrefixMapping(nsPrefix, value)
3415
+ }
3416
+ }
3417
+ var i = el.length;
3418
+ while(i--){
3419
+ a = el[i];
3420
+ var prefix = a.prefix;
3421
+ if(prefix){//no prefix attribute has no namespace
3422
+ if(prefix === 'xml'){
3423
+ a.uri = 'http://www.w3.org/XML/1998/namespace';
3424
+ }if(prefix !== 'xmlns'){
3425
+ a.uri = currentNSMap[prefix]
3426
+
3427
+ //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
3428
+ }
3429
+ }
3430
+ }
3431
+ var nsp = tagName.indexOf(':');
3432
+ if(nsp>0){
3433
+ prefix = el.prefix = tagName.slice(0,nsp);
3434
+ localName = el.localName = tagName.slice(nsp+1);
3435
+ }else{
3436
+ prefix = null;//important!!
3437
+ localName = el.localName = tagName;
3438
+ }
3439
+ //no prefix element has default namespace
3440
+ var ns = el.uri = currentNSMap[prefix || ''];
3441
+ domBuilder.startElement(ns,localName,tagName,el);
3442
+ //endPrefixMapping and startPrefixMapping have not any help for dom builder
3443
+ //localNSMap = null
3444
+ if(el.closed){
3445
+ domBuilder.endElement(ns,localName,tagName);
3446
+ if(localNSMap){
3447
+ for(prefix in localNSMap){
3448
+ domBuilder.endPrefixMapping(prefix)
3449
+ }
3450
+ }
3451
+ }else{
3452
+ el.currentNSMap = currentNSMap;
3453
+ el.localNSMap = localNSMap;
3454
+ parseStack.push(el);
3455
+ }
3456
+ }
3457
+ function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
3458
+ if(/^(?:script|textarea)$/i.test(tagName)){
3459
+ var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
3460
+ var text = source.substring(elStartEnd+1,elEndStart);
3461
+ if(/[&<]/.test(text)){
3462
+ if(/^script$/i.test(tagName)){
3463
+ //if(!/\]\]>/.test(text)){
3464
+ //lexHandler.startCDATA();
3465
+ domBuilder.characters(text,0,text.length);
3466
+ //lexHandler.endCDATA();
3467
+ return elEndStart;
3468
+ //}
3469
+ }//}else{//text area
3470
+ text = text.replace(/&#?\w+;/g,entityReplacer);
3471
+ domBuilder.characters(text,0,text.length);
3472
+ return elEndStart;
3473
+ //}
3474
+
3475
+ }
3476
+ }
3477
+ return elStartEnd+1;
3478
+ }
3479
+ function fixSelfClosed(source,elStartEnd,tagName,closeMap){
3480
+ //if(tagName in closeMap){
3481
+ var pos = closeMap[tagName];
3482
+ if(pos == null){
3483
+ //console.log(tagName)
3484
+ pos = closeMap[tagName] = source.lastIndexOf('</'+tagName+'>')
3485
+ }
3486
+ return pos<elStartEnd;
3487
+ //}
3488
+ }
3489
+ function _copy(source,target){
3490
+ for(var n in source){target[n] = source[n]}
3491
+ }
3492
+ function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
3493
+ var next= source.charAt(start+2)
3494
+ switch(next){
3495
+ case '-':
3496
+ if(source.charAt(start + 3) === '-'){
3497
+ var end = source.indexOf('-->',start+4);
3498
+ //append comment source.substring(4,end)//<!--
3499
+ if(end>start){
3500
+ domBuilder.comment(source,start+4,end-start-4);
3501
+ return end+3;
3502
+ }else{
3503
+ errorHandler.error("Unclosed comment");
3504
+ return -1;
3505
+ }
3506
+ }else{
3507
+ //error
3508
+ return -1;
3509
+ }
3510
+ default:
3511
+ if(source.substr(start+3,6) == 'CDATA['){
3512
+ var end = source.indexOf(']]>',start+9);
3513
+ domBuilder.startCDATA();
3514
+ domBuilder.characters(source,start+9,end-start-9);
3515
+ domBuilder.endCDATA()
3516
+ return end+3;
3517
+ }
3518
+ //<!DOCTYPE
3519
+ //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
3520
+ var matchs = split(source,start);
3521
+ var len = matchs.length;
3522
+ if(len>1 && /!doctype/i.test(matchs[0][0])){
3523
+ var name = matchs[1][0];
3524
+ var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
3525
+ var sysid = len>4 && matchs[4][0];
3526
+ var lastMatch = matchs[len-1]
3527
+ domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
3528
+ sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
3529
+ domBuilder.endDTD();
3530
+
3531
+ return lastMatch.index+lastMatch[0].length
3532
+ }
3533
+ }
3534
+ return -1;
3535
+ }
3536
+
3537
+
3538
+
3539
+ function parseInstruction(source,start,domBuilder){
3540
+ var end = source.indexOf('?>',start);
3541
+ if(end){
3542
+ var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
3543
+ if(match){
3544
+ var len = match[0].length;
3545
+ domBuilder.processingInstruction(match[1], match[2]) ;
3546
+ return end+2;
3547
+ }else{//error
3548
+ return -1;
3549
+ }
3550
+ }
3551
+ return -1;
3552
+ }
3553
+
3554
+ /**
3555
+ * @param source
3556
+ */
3557
+ function ElementAttributes(source){
3558
+
3559
+ }
3560
+ ElementAttributes.prototype = {
3561
+ setTagName:function(tagName){
3562
+ if(!tagNamePattern.test(tagName)){
3563
+ throw new Error('invalid tagName:'+tagName)
3564
+ }
3565
+ this.tagName = tagName
3566
+ },
3567
+ add:function(qName,value,offset){
3568
+ if(!tagNamePattern.test(qName)){
3569
+ throw new Error('invalid attribute:'+qName)
3570
+ }
3571
+ this[this.length++] = {qName:qName,value:value,offset:offset}
3572
+ },
3573
+ length:0,
3574
+ getLocalName:function(i){return this[i].localName},
3575
+ getOffset:function(i){return this[i].offset},
3576
+ getQName:function(i){return this[i].qName},
3577
+ getURI:function(i){return this[i].uri},
3578
+ getValue:function(i){return this[i].value}
3579
+ // ,getIndex:function(uri, localName)){
3580
+ // if(localName){
3581
+ //
3582
+ // }else{
3583
+ // var qName = uri
3584
+ // }
3585
+ // },
3586
+ // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
3587
+ // getType:function(uri,localName){}
3588
+ // getType:function(i){},
3589
+ }
3590
+
3591
+
3592
+
3593
+
3594
+ function _set_proto_(thiz,parent){
3595
+ thiz.__proto__ = parent;
3596
+ return thiz;
3597
+ }
3598
+ if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
3599
+ _set_proto_ = function(thiz,parent){
3600
+ function p(){};
3601
+ p.prototype = parent;
3602
+ p = new p();
3603
+ for(parent in thiz){
3604
+ p[parent] = thiz[parent];
3605
+ }
3606
+ return p;
3607
+ }
3608
+ }
3609
+
3610
+ function split(source,start){
3611
+ var match;
3612
+ var buf = [];
3613
+ var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
3614
+ reg.lastIndex = start;
3615
+ reg.exec(source);//skip <
3616
+ while(match = reg.exec(source)){
3617
+ buf.push(match);
3618
+ if(match[1])return buf;
3619
+ }
3620
+ }
3621
+
3622
+ if(typeof require == 'function'){
3623
+ exports.XMLReader = XMLReader;
3624
+ }
3625
+
3626
+
3627
+ },{}]},{},[1])(1)
3628
+ });