-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathkarma.js
2904 lines (2692 loc) · 74.1 KB
/
karma.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
module.exports = {
VERSION: '%KARMA_VERSION%',
KARMA_URL_ROOT: '%KARMA_URL_ROOT%',
KARMA_PROXY_PATH: '%KARMA_PROXY_PATH%',
BROWSER_SOCKET_TIMEOUT: '%BROWSER_SOCKET_TIMEOUT%',
CONTEXT_URL: 'context.html'
}
},{}],2:[function(require,module,exports){
var stringify = require('../common/stringify')
var constant = require('./constants')
var util = require('../common/util')
function Karma (updater, socket, iframe, opener, navigator, location, document) {
this.updater = updater
var startEmitted = false
var self = this
var queryParams = util.parseQueryParams(location.search)
var browserId = queryParams.id || util.generateId('manual-')
var displayName = queryParams.displayName
var returnUrl = queryParams['return_url' + ''] || null
var resultsBufferLimit = 50
var resultsBuffer = []
// This is a no-op if not running with a Trusted Types CSP policy, and
// lets tests declare that they trust the way that karma creates and handles
// URLs.
//
// More info about the proposed Trusted Types standard at
// https://github.com/WICG/trusted-types
var policy = {
createURL: function (s) {
return s
},
createScriptURL: function (s) {
return s
}
}
var trustedTypes = window.trustedTypes || window.TrustedTypes
if (trustedTypes) {
policy = trustedTypes.createPolicy('karma', policy)
if (!policy.createURL) {
// Install createURL for newer browsers. Only browsers that implement an
// old version of the spec require createURL.
// Should be safe to delete all reference to createURL by
// February 2020.
// https://github.com/WICG/trusted-types/pull/204
policy.createURL = function (s) { return s }
}
}
// To start we will signal the server that we are not reconnecting. If the socket loses
// connection and was able to reconnect to the Karma server we will get a
// second 'connect' event. There we will pass 'true' and that will be passed to the
// Karma server then, so that Karma can differentiate between a socket client
// econnect and a full browser reconnect.
var socketReconnect = false
this.VERSION = constant.VERSION
this.config = {}
// Expose for testing purposes as there is no global socket.io
// registry anymore.
this.socket = socket
// Set up postMessage bindings for current window
// DEV: These are to allow windows in separate processes execute local tasks
// Electron is one of these environments
if (window.addEventListener) {
window.addEventListener('message', function handleMessage (evt) {
// Resolve the origin of our message
var origin = evt.origin || evt.originalEvent.origin
// If the message isn't from our host, then reject it
if (origin !== window.location.origin) {
return
}
// Take action based on the message type
var method = evt.data.__karmaMethod
if (method) {
if (!self[method]) {
self.error('Received `postMessage` for "' + method + '" but the method doesn\'t exist')
return
}
self[method].apply(self, evt.data.__karmaArguments)
}
}, false)
}
var childWindow = null
function navigateContextTo (url) {
if (self.config.useIframe === false) {
// run in new window
if (self.config.runInParent === false) {
// If there is a window already open, then close it
// DEV: In some environments (e.g. Electron), we don't have setter access for location
if (childWindow !== null && childWindow.closed !== true) {
// The onbeforeunload listener was added by context to catch
// unexpected navigations while running tests.
childWindow.onbeforeunload = undefined
childWindow.close()
}
childWindow = opener(url)
if (childWindow === null) {
self.error('Opening a new tab/window failed, probably because pop-ups are blocked.')
}
// run context on parent element (client_with_context)
// using window.__karma__.scriptUrls to get the html element strings and load them dynamically
} else if (url !== 'about:blank') {
var loadScript = function (idx) {
if (idx < window.__karma__.scriptUrls.length) {
var parser = new DOMParser()
// Revert escaped characters with special roles in HTML before parsing
var string = window.__karma__.scriptUrls[idx]
.replace(/\\x3C/g, '<')
.replace(/\\x3E/g, '>')
var doc = parser.parseFromString(string, 'text/html')
var ele = doc.head.firstChild || doc.body.firstChild
// script elements created by DomParser are marked as unexecutable,
// create a new script element manually and copy necessary properties
// so it is executable
if (ele.tagName && ele.tagName.toLowerCase() === 'script') {
var tmp = ele
ele = document.createElement('script')
ele.src = policy.createScriptURL(tmp.src)
ele.crossOrigin = tmp.crossOrigin
}
ele.onload = function () {
loadScript(idx + 1)
}
document.body.appendChild(ele)
} else {
window.__karma__.loaded()
}
}
loadScript(0)
}
// run in iframe
} else {
// The onbeforeunload listener was added by the context to catch
// unexpected navigations while running tests.
iframe.contentWindow.onbeforeunload = undefined
iframe.src = policy.createURL(url)
}
}
this.log = function (type, args) {
var values = []
for (var i = 0; i < args.length; i++) {
values.push(this.stringify(args[i], 3))
}
this.info({ log: values.join(', '), type: type })
}
this.stringify = stringify
function getLocation (url, lineno, colno) {
var location = ''
if (url !== undefined) {
location += url
}
if (lineno !== undefined) {
location += ':' + lineno
}
if (colno !== undefined) {
location += ':' + colno
}
return location
}
// error during js file loading (most likely syntax error)
// we are not going to execute at all. `window.onerror` callback.
this.error = function (messageOrEvent, source, lineno, colno, error) {
var message
if (typeof messageOrEvent === 'string') {
message = messageOrEvent
var location = getLocation(source, lineno, colno)
if (location !== '') {
message += '\nat ' + location
}
if (error && error.stack) {
message += '\n\n' + error.stack
}
} else {
// create an object with the string representation of the message to
// ensure all its content is properly transferred to the console log
message = { message: messageOrEvent, str: messageOrEvent.toString() }
}
socket.emit('karma_error', message)
self.updater.updateTestStatus('karma_error ' + message)
this.complete()
return false
}
this.result = function (originalResult) {
var convertedResult = {}
// Convert all array-like objects to real arrays.
for (var propertyName in originalResult) {
if (Object.prototype.hasOwnProperty.call(originalResult, propertyName)) {
var propertyValue = originalResult[propertyName]
if (Object.prototype.toString.call(propertyValue) === '[object Array]') {
convertedResult[propertyName] = Array.prototype.slice.call(propertyValue)
} else {
convertedResult[propertyName] = propertyValue
}
}
}
if (!startEmitted) {
socket.emit('start', { total: null })
self.updater.updateTestStatus('start')
startEmitted = true
}
if (resultsBufferLimit === 1) {
self.updater.updateTestStatus('result')
return socket.emit('result', convertedResult)
}
resultsBuffer.push(convertedResult)
if (resultsBuffer.length === resultsBufferLimit) {
socket.emit('result', resultsBuffer)
self.updater.updateTestStatus('result')
resultsBuffer = []
}
}
this.complete = function (result) {
if (resultsBuffer.length) {
socket.emit('result', resultsBuffer)
resultsBuffer = []
}
socket.emit('complete', result || {})
if (this.config.clearContext) {
navigateContextTo('about:blank')
} else {
self.updater.updateTestStatus('complete')
}
if (returnUrl) {
var isReturnUrlAllowed = false
for (var i = 0; i < this.config.allowedReturnUrlPatterns.length; i++) {
var allowedReturnUrlPattern = new RegExp(this.config.allowedReturnUrlPatterns[i])
if (allowedReturnUrlPattern.test(returnUrl)) {
isReturnUrlAllowed = true
break
}
}
if (!isReturnUrlAllowed) {
throw new Error(
'Security: Navigation to '.concat(
returnUrl,
' was blocked to prevent malicious exploits.'
)
)
}
location.href = returnUrl
}
}
this.info = function (info) {
// TODO(vojta): introduce special API for this
if (!startEmitted && util.isDefined(info.total)) {
socket.emit('start', info)
startEmitted = true
} else {
socket.emit('info', info)
}
}
socket.on('execute', function (cfg) {
self.updater.updateTestStatus('execute')
// reset startEmitted and reload the iframe
startEmitted = false
self.config = cfg
navigateContextTo(constant.CONTEXT_URL)
if (self.config.clientDisplayNone) {
[].forEach.call(document.querySelectorAll('#banner, #browsers'), function (el) {
el.style.display = 'none'
})
}
// clear the console before run
// works only on FF (Safari, Chrome do not allow to clear console from js source)
if (window.console && window.console.clear) {
window.console.clear()
}
})
socket.on('stop', function () {
this.complete()
}.bind(this))
// Report the browser name and Id. Note that this event can also fire if the connection has
// been temporarily lost, but the socket reconnected automatically. Read more in the docs:
// https://socket.io/docs/client-api/#Event-%E2%80%98connect%E2%80%99
socket.on('connect', function () {
socket.io.engine.on('upgrade', function () {
resultsBufferLimit = 1
// Flush any results which were buffered before the upgrade to WebSocket protocol.
if (resultsBuffer.length > 0) {
socket.emit('result', resultsBuffer)
resultsBuffer = []
}
})
var info = {
name: navigator.userAgent,
id: browserId,
isSocketReconnect: socketReconnect
}
if (displayName) {
info.displayName = displayName
}
socket.emit('register', info)
socketReconnect = true
})
}
module.exports = Karma
},{"../common/stringify":5,"../common/util":6,"./constants":1}],3:[function(require,module,exports){
/* global io */
/* eslint-disable no-new */
var Karma = require('./karma')
var StatusUpdater = require('./updater')
var util = require('../common/util')
var constants = require('./constants')
var KARMA_URL_ROOT = constants.KARMA_URL_ROOT
var KARMA_PROXY_PATH = constants.KARMA_PROXY_PATH
var BROWSER_SOCKET_TIMEOUT = constants.BROWSER_SOCKET_TIMEOUT
// Connect to the server using socket.io https://socket.io/
var socket = io(location.host, {
reconnectionDelay: 500,
reconnectionDelayMax: Infinity,
timeout: BROWSER_SOCKET_TIMEOUT,
path: KARMA_PROXY_PATH + KARMA_URL_ROOT.slice(1) + 'socket.io',
'sync disconnect on unload': true,
useNativeTimers: true
})
// instantiate the updater of the view
var updater = new StatusUpdater(socket, util.elm('title'), util.elm('banner'), util.elm('browsers'))
window.karma = new Karma(updater, socket, util.elm('context'), window.open,
window.navigator, window.location, window.document)
},{"../common/util":6,"./constants":1,"./karma":2,"./updater":4}],4:[function(require,module,exports){
var VERSION = require('./constants').VERSION
function StatusUpdater (socket, titleElement, bannerElement, browsersElement) {
function updateBrowsersInfo (browsers) {
if (!browsersElement) {
return
}
var status
// clear browsersElement
while (browsersElement.firstChild) {
browsersElement.removeChild(browsersElement.firstChild)
}
for (var i = 0; i < browsers.length; i++) {
status = browsers[i].isConnected ? 'idle' : 'executing'
var li = document.createElement('li')
li.setAttribute('class', status)
li.textContent = browsers[i].name + ' is ' + status
browsersElement.appendChild(li)
}
}
var connectionText = 'never-connected'
var testText = 'loading'
var pingText = ''
function updateBanner () {
if (!titleElement || !bannerElement) {
return
}
titleElement.textContent = 'Karma v ' + VERSION + ' - ' + connectionText + '; test: ' + testText + '; ' + pingText
bannerElement.className = connectionText === 'connected' ? 'online' : 'offline'
}
function updateConnectionStatus (connectionStatus) {
connectionText = connectionStatus || connectionText
updateBanner()
}
function updateTestStatus (testStatus) {
testText = testStatus || testText
updateBanner()
}
function updatePingStatus (pingStatus) {
pingText = pingStatus || pingText
updateBanner()
}
socket.on('connect', function () {
updateConnectionStatus('connected')
})
socket.on('disconnect', function () {
updateConnectionStatus('disconnected')
})
socket.on('reconnecting', function (sec) {
updateConnectionStatus('reconnecting in ' + sec + ' seconds')
})
socket.on('reconnect', function () {
updateConnectionStatus('reconnected')
})
socket.on('reconnect_failed', function () {
updateConnectionStatus('reconnect_failed')
})
socket.on('info', updateBrowsersInfo)
socket.on('disconnect', function () {
updateBrowsersInfo([])
})
socket.on('ping', function () {
updatePingStatus('ping...')
})
socket.on('pong', function (latency) {
updatePingStatus('ping ' + latency + 'ms')
})
return { updateTestStatus: updateTestStatus }
}
module.exports = StatusUpdater
},{"./constants":1}],5:[function(require,module,exports){
var serialize = null
try {
serialize = require('dom-serialize')
} catch (e) {
// Ignore failure on IE8
}
var instanceOf = require('./util').instanceOf
function isNode (obj) {
return (obj.tagName || obj.nodeName) && obj.nodeType
}
function stringify (obj, depth) {
if (depth === 0) {
return '...'
}
if (obj === null) {
return 'null'
}
switch (typeof obj) {
case 'symbol':
return obj.toString()
case 'string':
return "'" + obj + "'"
case 'undefined':
return 'undefined'
case 'function':
try {
// function abc(a, b, c) { /* code goes here */ }
// -> function abc(a, b, c) { ... }
return obj.toString().replace(/\{[\s\S]*\}/, '{ ... }')
} catch (err) {
if (err instanceof TypeError) {
// Support older browsers
return 'function ' + (obj.name || '') + '() { ... }'
} else {
throw err
}
}
case 'boolean':
return obj ? 'true' : 'false'
case 'object':
var strs = []
if (instanceOf(obj, 'Array')) {
strs.push('[')
for (var i = 0, ii = obj.length; i < ii; i++) {
if (i) {
strs.push(', ')
}
strs.push(stringify(obj[i], depth - 1))
}
strs.push(']')
} else if (instanceOf(obj, 'Date')) {
return obj.toString()
} else if (instanceOf(obj, 'Text')) {
return obj.nodeValue
} else if (instanceOf(obj, 'Comment')) {
return '<!--' + obj.nodeValue + '-->'
} else if (obj.outerHTML) {
return obj.outerHTML
} else if (isNode(obj)) {
if (serialize) {
return serialize(obj)
} else {
return 'Skipping stringify, no support for dom-serialize'
}
} else if (instanceOf(obj, 'Error')) {
return obj.toString() + '\n' + obj.stack
} else {
var constructor = 'Object'
if (obj.constructor && typeof obj.constructor === 'function') {
constructor = obj.constructor.name
}
strs.push(constructor)
strs.push('{')
var first = true
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (first) {
first = false
} else {
strs.push(', ')
}
strs.push(key + ': ' + stringify(obj[key], depth - 1))
}
}
strs.push('}')
}
return strs.join('')
default:
return obj
}
}
module.exports = stringify
},{"./util":6,"dom-serialize":8}],6:[function(require,module,exports){
exports.instanceOf = function (value, constructorName) {
return Object.prototype.toString.apply(value) === '[object ' + constructorName + ']'
}
exports.elm = function (id) {
return document.getElementById(id)
}
exports.generateId = function (prefix) {
return prefix + Math.floor(Math.random() * 10000)
}
exports.isUndefined = function (value) {
return typeof value === 'undefined'
}
exports.isDefined = function (value) {
return !exports.isUndefined(value)
}
exports.parseQueryParams = function (locationSearch) {
var params = {}
var pairs = locationSearch.slice(1).split('&')
var keyValue
for (var i = 0; i < pairs.length; i++) {
keyValue = pairs[i].split('=')
params[decodeURIComponent(keyValue[0])] = decodeURIComponent(keyValue[1])
}
return params
}
},{}],7:[function(require,module,exports){
(function (global){
var NativeCustomEvent = global.CustomEvent;
function useNative () {
try {
var p = new NativeCustomEvent('cat', { detail: { foo: 'bar' } });
return 'cat' === p.type && 'bar' === p.detail.foo;
} catch (e) {
}
return false;
}
/**
* Cross-browser `CustomEvent` constructor.
*
* https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent.CustomEvent
*
* @public
*/
module.exports = useNative() ? NativeCustomEvent :
// IE >= 9
'undefined' !== typeof document && 'function' === typeof document.createEvent ? function CustomEvent (type, params) {
var e = document.createEvent('CustomEvent');
if (params) {
e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
} else {
e.initCustomEvent(type, false, false, void 0);
}
return e;
} :
// IE <= 8
function CustomEvent (type, params) {
var e = document.createEventObject();
e.type = type;
if (params) {
e.bubbles = Boolean(params.bubbles);
e.cancelable = Boolean(params.cancelable);
e.detail = params.detail;
} else {
e.bubbles = false;
e.cancelable = false;
e.detail = void 0;
}
return e;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],8:[function(require,module,exports){
/**
* Module dependencies.
*/
var extend = require('extend');
var encode = require('ent/encode');
var CustomEvent = require('custom-event');
var voidElements = require('void-elements');
/**
* Module exports.
*/
exports = module.exports = serialize;
exports.serializeElement = serializeElement;
exports.serializeAttribute = serializeAttribute;
exports.serializeText = serializeText;
exports.serializeComment = serializeComment;
exports.serializeDocument = serializeDocument;
exports.serializeDoctype = serializeDoctype;
exports.serializeDocumentFragment = serializeDocumentFragment;
exports.serializeNodeList = serializeNodeList;
/**
* Serializes any DOM node. Returns a string.
*
* @param {Node} node - DOM Node to serialize
* @param {String} [context] - optional arbitrary "context" string to use (useful for event listeners)
* @param {Function} [fn] - optional callback function to use in the "serialize" event for this call
* @param {EventTarget} [eventTarget] - optional EventTarget instance to emit the "serialize" event on (defaults to `node`)
* return {String}
* @public
*/
function serialize (node, context, fn, eventTarget) {
if (!node) return '';
if ('function' === typeof context) {
fn = context;
context = null;
}
if (!context) context = null;
var rtn;
var nodeType = node.nodeType;
if (!nodeType && 'number' === typeof node.length) {
// assume it's a NodeList or Array of Nodes
rtn = exports.serializeNodeList(node, context, fn);
} else {
if ('function' === typeof fn) {
// one-time "serialize" event listener
node.addEventListener('serialize', fn, false);
}
// emit a custom "serialize" event on `node`, in case there
// are event listeners for custom serialization of this node
var e = new CustomEvent('serialize', {
bubbles: true,
cancelable: true,
detail: {
serialize: null,
context: context
}
});
e.serializeTarget = node;
var target = eventTarget || node;
var cancelled = !target.dispatchEvent(e);
// `e.detail.serialize` can be set to a:
// String - returned directly
// Node - goes through serializer logic instead of `node`
// Anything else - get Stringified first, and then returned directly
var s = e.detail.serialize;
if (s != null) {
if ('string' === typeof s) {
rtn = s;
} else if ('number' === typeof s.nodeType) {
// make it go through the serialization logic
rtn = serialize(s, context, null, target);
} else {
rtn = String(s);
}
} else if (!cancelled) {
// default serialization logic
switch (nodeType) {
case 1 /* element */:
rtn = exports.serializeElement(node, context, eventTarget);
break;
case 2 /* attribute */:
rtn = exports.serializeAttribute(node);
break;
case 3 /* text */:
rtn = exports.serializeText(node);
break;
case 8 /* comment */:
rtn = exports.serializeComment(node);
break;
case 9 /* document */:
rtn = exports.serializeDocument(node, context, eventTarget);
break;
case 10 /* doctype */:
rtn = exports.serializeDoctype(node);
break;
case 11 /* document fragment */:
rtn = exports.serializeDocumentFragment(node, context, eventTarget);
break;
}
}
if ('function' === typeof fn) {
node.removeEventListener('serialize', fn, false);
}
}
return rtn || '';
}
/**
* Serialize an Attribute node.
*/
function serializeAttribute (node, opts) {
return node.name + '="' + encode(node.value, extend({
named: true
}, opts)) + '"';
}
/**
* Serialize a DOM element.
*/
function serializeElement (node, context, eventTarget) {
var c, i, l;
var name = node.nodeName.toLowerCase();
// opening tag
var r = '<' + name;
// attributes
for (i = 0, c = node.attributes, l = c.length; i < l; i++) {
r += ' ' + exports.serializeAttribute(c[i]);
}
r += '>';
// child nodes
r += exports.serializeNodeList(node.childNodes, context, null, eventTarget);
// closing tag, only for non-void elements
if (!voidElements[name]) {
r += '</' + name + '>';
}
return r;
}
/**
* Serialize a text node.
*/
function serializeText (node, opts) {
return encode(node.nodeValue, extend({
named: true,
special: { '<': true, '>': true, '&': true }
}, opts));
}
/**
* Serialize a comment node.
*/
function serializeComment (node) {
return '<!--' + node.nodeValue + '-->';
}
/**
* Serialize a Document node.
*/
function serializeDocument (node, context, eventTarget) {
return exports.serializeNodeList(node.childNodes, context, null, eventTarget);
}
/**
* Serialize a DOCTYPE node.
* See: http://stackoverflow.com/a/10162353
*/
function serializeDoctype (node) {
var r = '<!DOCTYPE ' + node.name;
if (node.publicId) {
r += ' PUBLIC "' + node.publicId + '"';
}
if (!node.publicId && node.systemId) {
r += ' SYSTEM';
}
if (node.systemId) {
r += ' "' + node.systemId + '"';
}
r += '>';
return r;
}
/**
* Serialize a DocumentFragment instance.
*/
function serializeDocumentFragment (node, context, eventTarget) {
return exports.serializeNodeList(node.childNodes, context, null, eventTarget);
}
/**
* Serialize a NodeList/Array of nodes.
*/
function serializeNodeList (list, context, fn, eventTarget) {
var r = '';
for (var i = 0, l = list.length; i < l; i++) {
r += serialize(list[i], context, fn, eventTarget);
}
return r;
}
},{"custom-event":7,"ent/encode":9,"extend":11,"void-elements":13}],9:[function(require,module,exports){
var punycode = require('punycode');
var revEntities = require('./reversed.json');
module.exports = encode;
function encode (str, opts) {
if (typeof str !== 'string') {
throw new TypeError('Expected a String');
}
if (!opts) opts = {};
var numeric = true;
if (opts.named) numeric = false;
if (opts.numeric !== undefined) numeric = opts.numeric;
var special = opts.special || {
'"': true, "'": true,
'<': true, '>': true,
'&': true
};
var codePoints = punycode.ucs2.decode(str);
var chars = [];
for (var i = 0; i < codePoints.length; i++) {
var cc = codePoints[i];
var c = punycode.ucs2.encode([ cc ]);
var e = revEntities[cc];
if (e && (cc >= 127 || special[c]) && !numeric) {
chars.push('&' + (/;$/.test(e) ? e : e + ';'));
}
else if (cc < 32 || cc >= 127 || special[c]) {
chars.push('&#' + cc + ';');
}
else {
chars.push(c);
}
}
return chars.join('');
}
},{"./reversed.json":10,"punycode":12}],10:[function(require,module,exports){
module.exports={
"9": "Tab;",
"10": "NewLine;",
"33": "excl;",
"34": "quot;",
"35": "num;",
"36": "dollar;",
"37": "percnt;",
"38": "amp;",
"39": "apos;",
"40": "lpar;",
"41": "rpar;",
"42": "midast;",
"43": "plus;",
"44": "comma;",
"46": "period;",
"47": "sol;",
"58": "colon;",
"59": "semi;",
"60": "lt;",
"61": "equals;",
"62": "gt;",
"63": "quest;",
"64": "commat;",
"91": "lsqb;",
"92": "bsol;",
"93": "rsqb;",
"94": "Hat;",
"95": "UnderBar;",
"96": "grave;",
"123": "lcub;",
"124": "VerticalLine;",
"125": "rcub;",
"160": "NonBreakingSpace;",
"161": "iexcl;",
"162": "cent;",
"163": "pound;",
"164": "curren;",
"165": "yen;",
"166": "brvbar;",
"167": "sect;",
"168": "uml;",
"169": "copy;",
"170": "ordf;",
"171": "laquo;",
"172": "not;",
"173": "shy;",
"174": "reg;",
"175": "strns;",
"176": "deg;",
"177": "pm;",
"178": "sup2;",
"179": "sup3;",
"180": "DiacriticalAcute;",
"181": "micro;",
"182": "para;",
"183": "middot;",
"184": "Cedilla;",
"185": "sup1;",
"186": "ordm;",
"187": "raquo;",
"188": "frac14;",
"189": "half;",
"190": "frac34;",
"191": "iquest;",
"192": "Agrave;",
"193": "Aacute;",
"194": "Acirc;",
"195": "Atilde;",
"196": "Auml;",
"197": "Aring;",
"198": "AElig;",
"199": "Ccedil;",
"200": "Egrave;",
"201": "Eacute;",
"202": "Ecirc;",
"203": "Euml;",
"204": "Igrave;",
"205": "Iacute;",
"206": "Icirc;",
"207": "Iuml;",
"208": "ETH;",
"209": "Ntilde;",
"210": "Ograve;",
"211": "Oacute;",
"212": "Ocirc;",
"213": "Otilde;",
"214": "Ouml;",
"215": "times;",
"216": "Oslash;",
"217": "Ugrave;",
"218": "Uacute;",
"219": "Ucirc;",