diff --git a/dist/rechart.js b/dist/rechart.js
index 3df72ea..b96686b 100644
--- a/dist/rechart.js
+++ b/dist/rechart.js
@@ -42,15 +42,6 @@
/************************************************************************/
/******/ ([
/* 0 */
-/***/ function(module, exports, __webpack_require__) {
-
- __webpack_require__(1);
- __webpack_require__(659);
- module.exports = __webpack_require__(695);
-
-
-/***/ },
-/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
@@ -63,6 +54,10 @@
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+ var _canvasConstJs = __webpack_require__(1);
+
+ var _canvasConstJs2 = _interopRequireDefault(_canvasConstJs);
+
var _browserApiJs = __webpack_require__(2);
var _browserApiJs2 = _interopRequireDefault(_browserApiJs);
@@ -79,71 +74,102 @@
var _toolsArrowJs2 = _interopRequireDefault(_toolsArrowJs);
- var _toolsBoxJs = __webpack_require__(652);
+ var _toolsBoxJs = __webpack_require__(49);
var _toolsBoxJs2 = _interopRequireDefault(_toolsBoxJs);
- var _toolsClearToolJs = __webpack_require__(653);
+ var _toolsClearToolJs = __webpack_require__(50);
var _toolsClearToolJs2 = _interopRequireDefault(_toolsClearToolJs);
- var _toolsDumpToolJs = __webpack_require__(654);
+ var _toolsDumpToolJs = __webpack_require__(51);
var _toolsDumpToolJs2 = _interopRequireDefault(_toolsDumpToolJs);
- var _toolsHlineJs = __webpack_require__(655);
+ var _toolsHlineJs = __webpack_require__(52);
var _toolsHlineJs2 = _interopRequireDefault(_toolsHlineJs);
- var _toolsRemoveToolJs = __webpack_require__(656);
+ var _toolsRemoveToolJs = __webpack_require__(53);
var _toolsRemoveToolJs2 = _interopRequireDefault(_toolsRemoveToolJs);
- var _toolsTextJs = __webpack_require__(657);
+ var _toolsTextJs = __webpack_require__(54);
var _toolsTextJs2 = _interopRequireDefault(_toolsTextJs);
- var _controlsHorizontalBarJs = __webpack_require__(658);
+ var _controlsHorizontalBarJs = __webpack_require__(55);
var _controlsHorizontalBarJs2 = _interopRequireDefault(_controlsHorizontalBarJs);
function setupTool(domId, toolResource, canvasTool, eventAggregator) {
var toolInstance = new toolResource(canvasTool, eventAggregator);
- if (!toolInstance.init) {
- console.log('Tool ' + domId + ' has no init function!');
- } else {
- toolInstance.init();
- }
return toolInstance;
}
- var RechartJs = function RechartJs(domId, imagePath, options) {
+ var RechartJs = function RechartJs(domId, imgElement, options) {
_classCallCheck(this, RechartJs);
- var events = new _eventAggregatorJs2['default']();
+ var events = new _eventAggregatorJs2['default'](domId);
+
+ var imgInstance = new fabric.Image(imgElement, {
+ left: 0,
+ top: 0
+ });
- var canvas = new _canvasWrapperJs2['default'](domId, imagePath);
+ var canvas = new _canvasWrapperJs2['default'](domId, imgInstance);
var c = canvas.canvas;
- var toolbar = new _controlsHorizontalBarJs2['default'](events, document.getElementById(domId));
+ var tools = options && options.tools ? options.tools : [];
+ var toolbar = new _controlsHorizontalBarJs2['default'](domId, events, document.getElementById(domId));
var hasToolsDef = !!options && !!options.tools;
+ /*
+ tools[CONST.TOOL.BOX] = { id: 'action_box', content:'', address: CONST.TOOL.BOX };
+ tools[CONST.TOOL.ARROW] = { id: 'action_arrow', content:'', address: CONST.TOOL.ARROW };
+ tools[CONST.TOOL.HLINE] = { id: 'action_hline', content:'', address: CONST.TOOL.HLINE };
+ tools[CONST.TOOL.TEXT] = { id: 'action_text', content:'', address: CONST.TOOL.TEXT };
+ tools[CONST.TOOL.REMOVE] = { id: 'action_remove', content:'', address: CONST.TOOL.REMOVE };
+ tools[CONST.TOOL.CLEAR] = { id: 'action_clear', content:'', address: CONST.TOOL.CLEAR };
+ tools[CONST.TOOL.DUMP] = { id: 'action_dump', content:'', address: CONST.TOOL.DUMP };
+
+ */
+ if (!hasToolsDef || tools.indexOf('rectangle') >= 0) {
+ setupTool('action_box', _toolsBoxJs2['default'], canvas, events);
+ toolbar.addTool(_canvasConstJs2['default'].TOOL.BOX);
+ }
+ if (!hasToolsDef || tools.indexOf('reset') >= 0) {
+ setupTool('action_clear', _toolsClearToolJs2['default'], canvas, events);
+ toolbar.addTool(_canvasConstJs2['default'].TOOL.CLEAR);
+ }
+ if (!hasToolsDef || tools.indexOf('text') >= 0) {
+ setupTool('action_text', _toolsTextJs2['default'], canvas, events);
+ toolbar.addTool(_canvasConstJs2['default'].TOOL.TEXT);
+ }
+ if (!hasToolsDef || tools.indexOf('hline') >= 0) {
+ setupTool('action_hline', _toolsHlineJs2['default'], canvas, events, document.getElementById('action_hline'));
+ toolbar.addTool(_canvasConstJs2['default'].TOOL.HLINE);
+ }
+ if (!hasToolsDef || tools.indexOf('arrow') >= 0) {
+ setupTool('action_arrow', _toolsArrowJs2['default'], canvas, events);
+ toolbar.addTool(_canvasConstJs2['default'].TOOL.ARROW);
+ }
+ if (!hasToolsDef || tools.indexOf('remove') >= 0) {
+ setupTool('action_remove', _toolsRemoveToolJs2['default'], canvas, events);
+ toolbar.addTool(_canvasConstJs2['default'].TOOL.REMOVE);
+ }
+ if (!hasToolsDef || tools.indexOf('dump') >= 0) {
+ setupTool('action_dump', _toolsDumpToolJs2['default'], canvas, events);
+ toolbar.addTool(_canvasConstJs2['default'].TOOL.DUMP);
+ }
+ toolbar.initTools();
+ var onSelect = function onSelect() {
+ events.notify('canvas-selection', 'canvas', c.getActiveObject() ? 'selected' : 'cleared');
+ };
+ c.on('object:selected', onSelect).on('selection:cleared', onSelect);
- if (!hasToolsDef || options.tools.indexOf('rectangle') >= 0) setupTool('action_box', _toolsBoxJs2['default'], canvas, events);
- if (!hasToolsDef || options.tools.indexOf('reset') >= 0) setupTool('action_clear', _toolsClearToolJs2['default'], canvas, events);
- if (!hasToolsDef || options.tools.indexOf('text') >= 0) setupTool('action_text', _toolsTextJs2['default'], canvas, events);
- if (!hasToolsDef || options.tools.indexOf('hline') >= 0) setupTool('action_hline', _toolsHlineJs2['default'], canvas, events, document.getElementById('action_hline'));
- if (!hasToolsDef || options.tools.indexOf('arrow') >= 0) setupTool('action_arrow', _toolsArrowJs2['default'], canvas, events);
- if (!hasToolsDef || options.tools.indexOf('remove') >= 0) setupTool('action_remove', _toolsRemoveToolJs2['default'], canvas, events);
- if (!hasToolsDef || options.tools.indexOf('dump') >= 0) setupTool('action_dump', _toolsDumpToolJs2['default'], canvas, events);
-
- // var oRemoveBtn = document.querySelector('#action_remove');
-
- // var onSelect = function(options) {
- // oRemoveBtn.className = c.getActiveObject() ? '' : 'inactive';
- // };
- // c.on('object:selected', onSelect).on('selection:cleared', onSelect);
+ imgElement.parentNode.removeChild(imgElement);
};
new _browserApiJs2['default']().appendToWindow('RechartJs', RechartJs);
@@ -151,6 +177,28 @@
exports['default'] = RechartJs;
module.exports = exports['default'];
+/***/ },
+/* 1 */
+/***/ function(module, exports) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+ exports['default'] = {
+ TOOL: {
+ ARROW: 'arrow',
+ BOX: 'box',
+ CLEAR: 'clear',
+ DUMP: 'dump',
+ HLINE: 'hline',
+ REMOVE: 'delete',
+ TEXT: 'text'
+ }
+ };
+ module.exports = exports['default'];
+
/***/ },
/* 2 */
/***/ function(module, exports) {
@@ -207,8 +255,6 @@
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var CANVAS_WIDTH = 582;
- var CANVAS_HEIGHT = 345;
var functionRepository = {},
serviceRepository = {};
@@ -225,7 +271,7 @@
}
var Canvas = (function () {
- function Canvas(domId, imagePath) {
+ function Canvas(domId, imgElement) {
_classCallCheck(this, Canvas);
var canvasElem = document.createElement("canvas");
@@ -235,22 +281,24 @@
canvasWrapper.appendChild(innerDiv);
innerDiv.appendChild(canvasElem);
- this.setCanvasProps(canvasElem, canvasWrapper, innerDiv, imagePath);
+ this.setCanvasProps(canvasElem, canvasWrapper, innerDiv, imgElement);
}
_createClass(Canvas, [{
key: "setCanvasProps",
- value: function setCanvasProps(_canvasElem, overallWrapper, canvasContainer, _imagePath) {
-
+ value: function setCanvasProps(_canvasElem, overallWrapper, canvasContainer, imgElement) {
this.canvasElem = _canvasElem;
+ this.width = imgElement.width;
+ this.height = imgElement.height;
+
this.overallWrapper = overallWrapper;
this.canvasTop = this.canvasElem.offsetTop;
this.canvasContainer = canvasContainer;
this.canvasLeft = _canvasElem.offsetLeft;
- this.imagePath = _imagePath;
+ this.imageElement = imgElement;
this.canvas = this.initFabricjsCanvas(this.canvasElem);
}
@@ -264,24 +312,27 @@
value: function initFabricjsCanvas(canvasElem) {
var fabricCanvas = new fabric.Canvas(canvasElem);
- /* fabric.Image.fromURL('demo/chart.png', function(oImg) {
- canvas.add(oImg);
- });/*/
- fabricCanvas.setDimensions({ width: CANVAS_WIDTH, height: CANVAS_HEIGHT });
-
- fabricCanvas.setBackgroundImage(this.imagePath, fabricCanvas.renderAll.bind(fabricCanvas), {
- width: fabricCanvas.width,
- height: fabricCanvas.height,
- // Needed to position backgroundImage at 0/0
- originX: 'left',
- originY: 'top'
+ fabricCanvas.setDimensions({ width: this.width, height: this.height });
+
+ fabricCanvas.setBackgroundImage(this.imageElement, fabricCanvas.renderAll.bind(fabricCanvas), {
+ backgroundImageOpacity: 0.5,
+ backgroundImageStretch: false
});
+
return fabricCanvas;
}
+ }, {
+ key: "enableSelection",
+ value: function enableSelection(isEnabled) {
+ this.canvas.selection = isEnabled; // Restore fabricjs selection-box
+ this.canvas.forEachObject(function (o) {
+ o.selectable = isEnabled;
+ });
+ }
}, {
key: "getWidth",
value: function getWidth() {
- return CANVAS_WIDTH;
+ return this.width;
}
}, {
key: "getOffsetLeft",
@@ -305,33 +356,34 @@
/* 4 */
/***/ function(module, exports) {
- "use strict";
+ 'use strict';
- Object.defineProperty(exports, "__esModule", {
+ Object.defineProperty(exports, '__esModule', {
value: true
});
- var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
+ var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var EventAggregator = (function () {
- function EventAggregator() {
+ function EventAggregator(id) {
_classCallCheck(this, EventAggregator);
+ this.id = id;
this.subscriptions = {};
this.subscriptionsByTopic = {};
}
_createClass(EventAggregator, [{
- key: "subscribe",
+ key: 'subscribe',
value: function subscribe(subscriber, onNotifyFn) {
this.subscriptions[subscriber] = onNotifyFn;
}
}, {
- key: "subscribeTo",
+ key: 'subscribeTo',
value: function subscribeTo(topic, subscriberId, onNotifyFn) {
-
+ //console.log(this.id, 'EN subscribeTo',topic, subscriberId);
if (!this.subscriptionsByTopic[topic]) {
this.subscriptionsByTopic[topic] = [];
}
@@ -340,7 +392,7 @@
// ToDo needs test
}, {
- key: "unsubscribe",
+ key: 'unsubscribe',
value: function unsubscribe(_subscriber) {
delete this.subscriptions[_subscriber];
for (var i in this.subscriptionsByTopic) {
@@ -355,7 +407,7 @@
// ToDo needs test
}, {
- key: "unsubscribeTo",
+ key: 'unsubscribeTo',
value: function unsubscribeTo(topic, _subscriber) {
for (var j in this.subscriptionsByTopic[topic]) {
if (this.subscriptionsByTopic[topic][j].subscriber === _subscriber) {
@@ -364,8 +416,9 @@
}
}
}, {
- key: "notify",
+ key: 'notify',
value: function notify(topic, sender, payload) {
+ console.log(this.id, 'EN notify', topic, sender, payload);
for (var s1 in this.subscriptions) {
this.subscriptions[s1].apply(undefined, [topic, sender, payload]);
}
@@ -378,8 +431,8 @@
return EventAggregator;
})();
- exports["default"] = EventAggregator;
- module.exports = exports["default"];
+ exports['default'] = EventAggregator;
+ module.exports = exports['default'];
/***/ },
/* 5 */
@@ -397,23 +450,17 @@
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
- var _canvasConstJs = __webpack_require__(6);
+ var _canvasConstJs = __webpack_require__(1);
var _canvasConstJs2 = _interopRequireDefault(_canvasConstJs);
- var _sampleJs = __webpack_require__(7);
-
- var _sampleJs2 = _interopRequireDefault(_sampleJs);
+ var f = __webpack_require__(6).fabric;
- // var w = require('window');
-
- var circleMarkerRadius = 8;
var indicationLength = 20;
var arrowColor = '#444';
var dragArrowColor = '#888';
- var arrow, canvas;
- var circleMarker, line, start, end;
+ var circleMarker, line;
var ArrowTool = (function () {
function ArrowTool(canvasWrapper, eventAggregator) {
@@ -421,24 +468,35 @@
this.eventAggregator = eventAggregator;
this.canvasWrapper = canvasWrapper;
+ this.arrow = this.canvas = this.start = this.end = undefined;
+
var callee = this;
this.eventAggregator.subscribeTo(_canvasConstJs2['default'].TOOL.ARROW, 'ArrowTool', function () {
- console.log('tool callback', this);
- callee.startArrow();
+ callee.initListeners.apply(callee, arguments);
});
- canvas = canvasWrapper.canvas;
+
+ this.canvas = canvasWrapper.canvas;
this.moveFn = function (options) {
callee.onMove(options);
};
+ this.downFn = function (options) {
+ callee.onMouseDown(options);
+ };
this.upFn = function (options) {
callee.onMUP(options);
};
this.notify = function (message) {
- console.log('notify', this);
+ console.log(this.eventAggregator.id, 'notify', message);
this.eventAggregator.notify('TOOL_USAGE', _canvasConstJs2['default'].TOOL.ARROW, message);
};
+
+ this.done = function () {
+ this.canvasWrapper.enableSelection(true);
+ this.removeCanvasListeners();
+ this.notify('inactive');
+ };
}
// Cred till http://stackoverflow.com/questions/29890294/arrow-shape-using-fabricjs
@@ -456,10 +514,10 @@
angle *= 180 / Math.PI;
angle += 90;
- if (arrow) {
- canvas.remove(arrow);
+ if (this.arrow) {
+ this.canvas.remove(this.arrow);
}
- arrow = new _sampleJs2['default'].fabric.Triangle({
+ this.arrow = new f.Triangle({
angle: angle,
fill: dragArrowColor,
top: y2,
@@ -471,47 +529,29 @@
selectable: false
});
- canvas.add(arrow);
+ this.canvas.add(this.arrow);
}
}, {
key: 'abort',
value: function abort() {
-
- if (circleMarker) {
- canvas.remove(circleMarker);
- circleMarker = undefined;
- }
- if (arrow) {
- canvas.remove(arrow);
- arrow = undefined;
+ console.log('ARROW abort');
+ if (this.arrow) {
+ this.canvas.remove(this.arrow);
+ this.arrow = undefined;
}
if (line) {
- canvas.remove(line);
- arrow = line = undefined;
+ this.canvas.remove(line);
+ line = undefined;
}
- this.detachArrowListeners();
this.eventAggregator.unsubscribeTo('keydown', 'ArrowTool');
- this.notify('inactive');
- }
- }, {
- key: 'detachArrowListeners',
- value: function detachArrowListeners() {
- canvas.off('mouse:move', this.moveFn);
- canvas.off('mouse:up', this.upFn);
+ this.done();
}
}, {
key: 'onMove',
value: function onMove(options) {
- if (circleMarker) {
- circleMarker.set({
- 'top': options.e.clientY - this.canvasWrapper.getOffsetTop()
- });
- circleMarker.set({
- 'left': options.e.clientX - this.canvasWrapper.getOffsetLeft()
- });
- circleMarker.setCoords();
- }
- if (start) {
+
+ if (this.start && !this.end) {
+
var _x2 = options.e.clientX - this.canvasWrapper.getOffsetLeft();
var _y2 = options.e.clientY - this.canvasWrapper.getOffsetTop();
line.set({
@@ -521,85 +561,49 @@
'y2': _y2
});
- this.moveArrowIndicator([start.left, start.top, _x2, _y2]);
+ this.moveArrowIndicator([this.start.left, this.start.top, _x2, _y2]);
}
- canvas.renderAll();
+ this.canvas.renderAll();
}
}, {
key: 'onMUP',
value: function onMUP(options) {
- if (!start) {
- start = {
- top: circleMarker.get('top'),
- left: circleMarker.get('left')
- };
- line.set({
- 'x1': start.left
- });
- line.set({
- 'y1': start.top
- });
- line.set({
- 'x2': start.left
- });
- line.set({
- 'y2': start.top
- });
- canvas.add(line);
- canvas.remove(circleMarker);
- circleMarker = undefined;
- } else if (!end) {
- end = {
- top: options.e.clientY - this.canvasWrapper.getOffsetTop(),
- left: options.e.clientX - this.canvasWrapper.getOffsetLeft()
- };
- this.detachArrowListeners();
- arrow.fill = arrowColor;
- var group = new _sampleJs2['default'].fabric.Group([line, arrow], {
+ this.end = {
+ top: options.e.clientY - this.canvasWrapper.getOffsetTop(),
+ left: options.e.clientX - this.canvasWrapper.getOffsetLeft()
+ };
+
+ var perimeter = Math.abs(this.end.top - this.start.top) + Math.abs(this.end.left - this.start.left);
+
+ if (perimeter > 10) {
+ if (this.arrow) {
+ this.arrow.fill = arrowColor;
+ }
+ var group = new f.Group([line, this.arrow], {
hasControls: false,
hasBorders: true,
- selectable: true
+ selectable: false
});
line.stroke = arrowColor;
- canvas.add(group);
- canvas.remove(line);
- canvas.remove(arrow);
- arrow = line = undefined;
- this.notify('inactive');
+ this.canvas.add(group);
}
- canvas.renderAll();
+
+ this.canvas.remove(line);
+ this.canvas.remove(this.arrow);
+ this.arrow = line = this.start = this.end = undefined;
+ this.canvas.renderAll();
}
}, {
- key: 'startArrow',
- value: function startArrow(topic, sender, payload) {
- if (payload === 'toolbar-deactivate') {
- this.abort();
- return;
- }
- var callee = this;
- this.eventAggregator.subscribeTo('keydown', 'ArrowTool', function (topic, sender, keyCode) {
- if (keyCode === 27) {
- callee.abort();
- }
- });
- start = end = undefined;
- this.notify('active');
- console.log('required', _sampleJs2['default'].fabric);
- circleMarker = new _sampleJs2['default'].fabric.Circle({
- radius: circleMarkerRadius,
- fill: arrowColor,
- opacity: 0.7,
- left: 100,
- top: 0,
- selectable: false,
- originX: 'center',
- originY: 'center'
- });
- canvas.add(circleMarker);
+ key: 'onMouseDown',
+ value: function onMouseDown(options) {
+ this.start = {
+ top: options.e.clientY - this.canvasWrapper.getOffsetTop(),
+ left: options.e.clientX - this.canvasWrapper.getOffsetLeft()
+ };
- line = new FabricJs.Line([0, 0, 300, 300], {
+ line = new f.Line([this.start.left, this.start.top, this.start.left, this.start.top], {
strokeWidth: 5,
stroke: dragArrowColor,
originX: 'center',
@@ -609,71 +613,57 @@
selectable: true
});
- canvas.on('mouse:move', this.moveFn);
- canvas.on('mouse:up', this.upFn);
+ this.canvas.add(line);
}
- }]);
-
- return ArrowTool;
- })();
-
- exports['default'] = ArrowTool;
- module.exports = exports['default'];
-
-/***/ },
-/* 6 */
-/***/ function(module, exports) {
-
- 'use strict';
-
- Object.defineProperty(exports, '__esModule', {
- value: true
- });
- exports['default'] = {
- TOOL: {
- ARROW: 'arr_t',
- BOX: 'box_t',
- CLEAR: 'cl_t',
- DUMP: 'dump_t',
- HLINE: 'hline_t',
- REMOVE: 'rem_t',
- TEXT: 'txt_t'
- }
- };
- module.exports = exports['default'];
-
-/***/ },
-/* 7 */
-/***/ function(module, exports, __webpack_require__) {
-
- 'use strict';
+ }, {
+ key: 'initListeners',
+ value: function initListeners(topic, sender, payload) {
+ console.log(this.eventAggregator.id, 'ARROW init', this.eventAggregator);
+ if (payload === 'toolbar-deactivate') {
+ this.abort();
+ return;
+ }
+ var me = this;
- Object.defineProperty(exports, '__esModule', {
- value: true
- });
+ this.eventAggregator.subscribeTo('keydown', 'ArrowTool', function (topic, sender, keyCode) {
+ console.log(me.eventAggregator.id, 'ARROW keydown');
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+ if (keyCode === 27) {
+ me.abort.apply(me);
+ }
+ });
+ this.start = this.end = undefined;
- var FabricJs = __webpack_require__(8).fabric;
+ this.canvasWrapper.enableSelection(false);
- var isTest = false;
+ this.notify('active');
- var FabricProvider = function FabricProvider() {
- _classCallCheck(this, FabricProvider);
+ this.canvas.on('mouse:down', this.downFn);
+ this.canvas.on('mouse:move', this.moveFn);
+ this.canvas.on('mouse:up', this.upFn);
+ }
+ }, {
+ key: 'removeCanvasListeners',
+ value: function removeCanvasListeners() {
+ this.canvas.off('mouse:down', this.downFn);
+ this.canvas.off('mouse:move', this.moveFn);
+ this.canvas.off('mouse:up', this.upFn);
+ }
+ }]);
- this.fabric = isTest ? {} : FabricJs;
- };
+ return ArrowTool;
+ })();
- exports['default'] = FabricProvider;
+ exports['default'] = ArrowTool;
module.exports = exports['default'];
/***/ },
-/* 8 */
+/* 6 */
/***/ function(module, exports, __webpack_require__) {
- /* build: `node build.js modules=ALL exclude=gestures,json minifier=uglifyjs` */ /*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */'use strict';var fabric=fabric || {version:"1.5.0"};if(true){exports.fabric = fabric;}if(typeof document !== 'undefined' && typeof window !== 'undefined'){fabric.document = document;fabric.window = window; // ensure globality even if entire library were function wrapped (as in Meteor.js packaging system)
+ /* WEBPACK VAR INJECTION */(function(Buffer, process) {/* build: `node build.js modules=ALL exclude=gestures,json minifier=uglifyjs` */ /*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */'use strict';var fabric=fabric || {version:"1.5.0"};if(true){exports.fabric = fabric;}if(typeof document !== 'undefined' && typeof window !== 'undefined'){fabric.document = document;fabric.window = window; // ensure globality even if entire library were function wrapped (as in Meteor.js packaging system)
window.fabric = fabric;}else { // assume we're running under node.js when document/window are not present
- fabric.document = __webpack_require__(9).jsdom("
");if(fabric.document.createWindow){fabric.window = fabric.document.createWindow();}else {fabric.window = fabric.document.parentWindow;}} /**
+ fabric.document = __webpack_require__(12).jsdom("");if(fabric.document.createWindow){fabric.window = fabric.document.createWindow();}else {fabric.window = fabric.document.parentWindow;}} /**
* True when in environment that supports touch events
* @type boolean
*/fabric.isTouchSupported = "ontouchstart" in fabric.document.documentElement; /**
@@ -921,7 +911,7 @@
* @static
* @memberOf fabric.util
* @return {HTMLImageElement} HTML image element
- */createImage:function createImage(){return fabric.isLikelyNode?new (__webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"canvas\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())).Image)():fabric.document.createElement('img');}, /**
+ */createImage:function createImage(){return fabric.isLikelyNode?new (__webpack_require__(13).Image)():fabric.document.createElement('img');}, /**
* Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array
* @static
* @memberOf fabric.util
@@ -6861,9 +6851,9 @@
* @private
*/_createTextCharSpan:function _createTextCharSpan(_char,styleDecl,lineLeftOffset,lineTopOffset,charOffset){var fillStyles=this.getSvgStyles.call(fabric.util.object.extend({visible:true,fill:this.fill,stroke:this.stroke,type:'text'},styleDecl));return [ //jscs:disable validateIndentation
'',fabric.util.string.escapeXml(_char),'' //jscs:enable validateIndentation
- ].join('');}}); /* _TO_SVG_END_ */(function(){if(typeof document !== 'undefined' && typeof window !== 'undefined'){return;}var DOMParser=__webpack_require__(649).DOMParser,URL=__webpack_require__(13),HTTP=__webpack_require__(21),HTTPS=__webpack_require__(22),Canvas=__webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"canvas\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())),Image=__webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"canvas\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())).Image; /** @private */function request(url,encoding,callback){var oURL=URL.parse(url); // detect if http or https is used
+ ].join('');}}); /* _TO_SVG_END_ */(function(){if(typeof document !== 'undefined' && typeof window !== 'undefined'){return;}var DOMParser=__webpack_require__(14).DOMParser,URL=__webpack_require__(15),HTTP=__webpack_require__(21),HTTPS=__webpack_require__(47),Canvas=__webpack_require__(13),Image=__webpack_require__(13).Image; /** @private */function request(url,encoding,callback){var oURL=URL.parse(url); // detect if http or https is used
if(!oURL.port){oURL.port = oURL.protocol.indexOf('https:') === 0?443:80;} // assign request handler based on protocol
- var reqHandler=oURL.protocol.indexOf('https:') === 0?HTTPS:HTTP,req=reqHandler.request({hostname:oURL.hostname,port:oURL.port,path:oURL.path,method:'GET'},function(response){var body='';if(encoding){response.setEncoding(encoding);}response.on('end',function(){callback(body);});response.on('data',function(chunk){if(response.statusCode === 200){body += chunk;}});});req.on('error',function(err){if(err.errno === process.ECONNREFUSED){fabric.log('ECONNREFUSED: connection refused to ' + oURL.hostname + ':' + oURL.port);}else {fabric.log(err.message);}});req.end();} /** @private */function requestFs(path,callback){var fs=__webpack_require__(11);fs.readFile(path,function(err,data){if(err){fabric.log(err);throw err;}else {callback(data);}});}fabric.util.loadImage = function(url,callback,context){function createImageAndCallBack(data){img.src = new Buffer(data,'binary'); // preserving original url, which seems to be lost in node-canvas
+ var reqHandler=oURL.protocol.indexOf('https:') === 0?HTTPS:HTTP,req=reqHandler.request({hostname:oURL.hostname,port:oURL.port,path:oURL.path,method:'GET'},function(response){var body='';if(encoding){response.setEncoding(encoding);}response.on('end',function(){callback(body);});response.on('data',function(chunk){if(response.statusCode === 200){body += chunk;}});});req.on('error',function(err){if(err.errno === process.ECONNREFUSED){fabric.log('ECONNREFUSED: connection refused to ' + oURL.hostname + ':' + oURL.port);}else {fabric.log(err.message);}});req.end();} /** @private */function requestFs(path,callback){var fs=__webpack_require__(48);fs.readFile(path,function(err,data){if(err){fabric.log(err);throw err;}else {callback(data);}});}fabric.util.loadImage = function(url,callback,context){function createImageAndCallBack(data){img.src = new Buffer(data,'binary'); // preserving original url, which seems to be lost in node-canvas
img._src = url;callback && callback.call(context,img);}var img=new Image();if(url && (url instanceof Buffer || url.indexOf('data') === 0)){img.src = img._src = url;callback && callback.call(context,img);}else if(url && url.indexOf('http') !== 0){requestFs(url,createImageAndCallBack);}else if(url){request(url,'binary',createImageAndCallBack);}else {callback && callback.call(context,url);}};fabric.loadSVGFromURL = function(url,callback,reviver){url = url.replace(/^\n\s*/,'').replace(/\?.*$/,'').trim();if(url.indexOf('http') !== 0){requestFs(url,function(body){fabric.loadSVGFromString(body.toString(),callback,reviver);});}else {request(url,'',function(body){fabric.loadSVGFromString(body,callback,reviver);});}};fabric.loadSVGFromString = function(string,callback,reviver){var doc=new DOMParser().parseFromString(string);fabric.parseSVGDocument(doc.documentElement,function(results,options){callback && callback(results,options);},reviver);};fabric.util.getScript = function(url,callback){request(url,'',function(body){eval(body);callback && callback();});};fabric.Image.fromObject = function(object,callback){fabric.util.loadImage(object.src,function(img){var oImg=new fabric.Image(img);oImg._initConfig(object);oImg._initFilters(object,function(filters){oImg.filters = filters || [];callback && callback(oImg);});});}; /**
* Only available when running fabric on node.js
* @param {Number} width Canvas width
@@ -6873,89333 +6863,7836 @@
* @return {Object} wrapped canvas instance
*/fabric.createCanvasForNode = function(width,height,options,nodeCanvasOptions){nodeCanvasOptions = nodeCanvasOptions || options;var canvasEl=fabric.document.createElement('canvas'),nodeCanvas=new Canvas(width || 600,height || 600,nodeCanvasOptions); // jsdom doesn't create style on canvas element, so here be temp. workaround
canvasEl.style = {};canvasEl.width = nodeCanvas.width;canvasEl.height = nodeCanvas.height;var FabricCanvas=fabric.Canvas || fabric.StaticCanvas,fabricCanvas=new FabricCanvas(canvasEl,options);fabricCanvas.contextContainer = nodeCanvas.getContext('2d');fabricCanvas.nodeCanvas = nodeCanvas;fabricCanvas.Font = Canvas.Font;return fabricCanvas;}; /** @ignore */fabric.StaticCanvas.prototype.createPNGStream = function(){return this.nodeCanvas.createPNGStream();};fabric.StaticCanvas.prototype.createJPEGStream = function(opts){return this.nodeCanvas.createJPEGStream(opts);};var origSetWidth=fabric.StaticCanvas.prototype.setWidth;fabric.StaticCanvas.prototype.setWidth = function(width,options){origSetWidth.call(this,width,options);this.nodeCanvas.width = width;return this;};if(fabric.Canvas){fabric.Canvas.prototype.setWidth = fabric.StaticCanvas.prototype.setWidth;}var origSetHeight=fabric.StaticCanvas.prototype.setHeight;fabric.StaticCanvas.prototype.setHeight = function(height,options){origSetHeight.call(this,height,options);this.nodeCanvas.height = height;return this;};if(fabric.Canvas){fabric.Canvas.prototype.setHeight = fabric.StaticCanvas.prototype.setHeight;}})();
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7).Buffer, __webpack_require__(11)))
/***/ },
-/* 9 */
+/* 7 */
/***/ function(module, exports, __webpack_require__) {
- /* WEBPACK VAR INJECTION */(function(module) {var fs = __webpack_require__(11);
- var path = __webpack_require__(12);
- var URL = __webpack_require__(13);
-
- var toFileUrl = __webpack_require__(14).toFileUrl;
- var defineGetter = __webpack_require__(14).defineGetter;
- var defineSetter = __webpack_require__(14).defineSetter;
- var style = __webpack_require__(15);
- var features = __webpack_require__(20);
- var dom = __webpack_require__(438).dom;
- var createWindow = __webpack_require__(514).createWindow;
- var browserAugmentation = __webpack_require__(514).browserAugmentation;
- var windowAugmentation = __webpack_require__(514).windowAugmentation;
-
- var domToHtml = __webpack_require__(511).domToHtml;
-
- var request = function(options, cb) {
- request = __webpack_require__(525);
- return request(options, cb);
- }
+ /* WEBPACK VAR INJECTION */(function(Buffer) {/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
- exports.defaultLevel = dom.living.html;
- exports.debugMode = false;
+ var base64 = __webpack_require__(8)
+ var ieee754 = __webpack_require__(9)
+ var isArray = __webpack_require__(10)
- // Proxy feature functions to features module.
- ['availableDocumentFeatures',
- 'defaultDocumentFeatures',
- 'applyDocumentFeatures'].forEach(function (propName) {
- defineGetter(exports, propName, function () {
- return features[propName];
- });
- defineSetter(exports, propName, function (val) {
- return features[propName] = val;
- });
- });
+ exports.Buffer = Buffer
+ exports.SlowBuffer = SlowBuffer
+ exports.INSPECT_MAX_BYTES = 50
+ Buffer.poolSize = 8192 // not used by this implementation
- var level2Html = __webpack_require__(18);
- exports.level = function (level, feature) {
- if(!feature) {
- feature = 'core';
- }
+ var rootParent = {}
+
+ /**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * Due to various browser bugs, sometimes the Object implementation will be used even
+ * when the browser supports typed arrays.
+ *
+ * Note:
+ *
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
+ *
+ * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
+ * on objects.
+ *
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
+ *
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
+ * incorrect length in some situations.
- if (String(level) === '1' || String(level) === '2' || String(level) === '3') {
- level = 'level' + level;
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
+ * get the Object implementation, which is slower but behaves correctly.
+ */
+ Buffer.TYPED_ARRAY_SUPPORT = (function () {
+ function Bar () {}
+ try {
+ var arr = new Uint8Array(1)
+ arr.foo = function () { return 42 }
+ arr.constructor = Bar
+ return arr.foo() === 42 && // typed array instances can be augmented
+ arr.constructor === Bar && // constructor can be set
+ typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
+ arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
+ } catch (e) {
+ return false
}
+ })()
- return __webpack_require__(639)("./" + level + '/' + feature).dom[level][feature];
- };
+ function kMaxLength () {
+ return Buffer.TYPED_ARRAY_SUPPORT
+ ? 0x7fffffff
+ : 0x3fffffff
+ }
- exports.jsdom = function (html, options) {
- options = options || {};
+ /**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+ function Buffer (arg) {
+ if (!(this instanceof Buffer)) {
+ // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
+ if (arguments.length > 1) return new Buffer(arg, arguments[1])
+ return new Buffer(arg)
+ }
- if (typeof options.level === 'string') {
- options.level = exports.level(options.level, 'html');
- } else {
- options.level = options.level || exports.defaultLevel;
+ this.length = 0
+ this.parent = undefined
+
+ // Common case.
+ if (typeof arg === 'number') {
+ return fromNumber(this, arg)
}
- options.parsingMode = options.parsingMode || "auto";
- if (!options.url) {
- if (typeof location !== 'undefined' && location.href) {
- options.url = location.href;
- } else {
- options.url = module.parent.id === 'jsdom' ? module.parent.parent.filename : module.parent.filename;
- options.url = options.url.replace(/\\/g, '/');
- if (options.url[0] !== '/') {
- options.url = '/' + options.url;
- }
- options.url = 'file://' + options.url;
- }
+ // Slightly less common case.
+ if (typeof arg === 'string') {
+ return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
}
- var browser = browserAugmentation(options.level, options);
- var doc = browser.HTMLDocument ? new browser.HTMLDocument(options) : new browser.Document(options);
+ // Unusual.
+ return fromObject(this, arg)
+ }
- if (options.created) {
- options.created(null, doc.parentWindow);
+ function fromNumber (that, length) {
+ that = allocate(that, length < 0 ? 0 : checked(length) | 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
+ for (var i = 0; i < length; i++) {
+ that[i] = 0
+ }
}
+ return that
+ }
- __webpack_require__(647).applyQuerySelectorPrototype(options.level);
+ function fromString (that, string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
- features.applyDocumentFeatures(doc, options.features);
+ // Assumption: byteLength() return value is always < kMaxLength.
+ var length = byteLength(string, encoding) | 0
+ that = allocate(that, length)
- if (html === undefined) {
- html = '';
- }
- html = String(html);
- doc.write(html);
+ that.write(string, encoding)
+ return that
+ }
- if (doc.close && !options.deferClose) {
- doc.close();
- }
+ function fromObject (that, object) {
+ if (Buffer.isBuffer(object)) return fromBuffer(that, object)
- return doc;
- };
+ if (isArray(object)) return fromArray(that, object)
- exports.jQueryify = exports.jsdom.jQueryify = function (window, jqueryUrl, callback) {
- if (!window || !window.document) {
- return;
+ if (object == null) {
+ throw new TypeError('must start with number, buffer, array or string')
}
- var features = window.document.implementation._features;
- window.document.implementation.addFeature('FetchExternalResources', ['script']);
- window.document.implementation.addFeature('ProcessExternalResources', ['script']);
- window.document.implementation.addFeature('MutationEvents', ['2.0']);
-
- var scriptEl = window.document.createElement('script');
- scriptEl.className = 'jsdom';
- scriptEl.src = jqueryUrl;
- scriptEl.onload = scriptEl.onerror = function () {
- window.document.implementation._features = features;
-
- if (callback) {
- callback(window, window.jQuery);
+ if (typeof ArrayBuffer !== 'undefined') {
+ if (object.buffer instanceof ArrayBuffer) {
+ return fromTypedArray(that, object)
}
- };
+ if (object instanceof ArrayBuffer) {
+ return fromArrayBuffer(that, object)
+ }
+ }
- window.document.body.appendChild(scriptEl);
- };
+ if (object.length) return fromArrayLike(that, object)
- exports.env = exports.jsdom.env = function () {
- var config = getConfigFromArguments(arguments);
+ return fromJsonObject(that, object)
+ }
- if (config.file) {
- fs.readFile(config.file, 'utf-8', function (err, text) {
- if (err) {
- if (config.created) {
- config.created(err);
- }
- if (config.done) {
- config.done([err]);
- }
- return;
- }
+ function fromBuffer (that, buffer) {
+ var length = checked(buffer.length) | 0
+ that = allocate(that, length)
+ buffer.copy(that, 0, 0, length)
+ return that
+ }
- setParsingModeFromExtension(config, config.file);
+ function fromArray (that, array) {
+ var length = checked(array.length) | 0
+ that = allocate(that, length)
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+ }
- config.html = text;
- processHTML(config);
- });
- } else if (config.html) {
- processHTML(config);
- } else if (config.url) {
- handleUrl(config);
- } else if (config.somethingToAutodetect !== undefined) {
- var url = URL.parse(config.somethingToAutodetect);
- if (url.protocol && url.hostname) {
- config.url = config.somethingToAutodetect;
- handleUrl(config.somethingToAutodetect);
- } else {
- fs.readFile(config.somethingToAutodetect, 'utf-8', function (err, text) {
- if (err) {
- if (err.code === 'ENOENT' || err.code === 'ENAMETOOLONG') {
- config.html = config.somethingToAutodetect;
- processHTML(config);
- } else {
- if (config.created) {
- config.created(err);
- }
- if (config.done) {
- config.done([err]);
- }
- }
- } else {
- setParsingModeFromExtension(config, config.somethingToAutodetect);
+ // Duplicate of fromArray() to keep fromArray() monomorphic.
+ function fromTypedArray (that, array) {
+ var length = checked(array.length) | 0
+ that = allocate(that, length)
+ // Truncating the elements is probably not what people expect from typed
+ // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
+ // of the old Buffer constructor.
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+ }
- config.html = text;
- config.url = toFileUrl(config.somethingToAutodetect);
- processHTML(config);
- }
- });
- }
+ function fromArrayBuffer (that, array) {
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ array.byteLength
+ that = Buffer._augment(new Uint8Array(array))
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that = fromTypedArray(that, new Uint8Array(array))
}
+ return that
+ }
- function handleUrl() {
- var options = {
- uri: config.url,
- encoding: config.encoding || 'utf8',
- headers: config.headers || {},
- proxy: config.proxy || null,
- jar: config.jar !== undefined ? config.jar : true
- };
+ function fromArrayLike (that, array) {
+ var length = checked(array.length) | 0
+ that = allocate(that, length)
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+ }
- request(options, function (err, res, responseText) {
- if (err) {
- if (config.created) {
- config.created(err);
- }
- if (config.done) {
- config.done([err]);
- }
- return;
- }
+ // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
+ // Returns a zero-length buffer for inputs that don't conform to the spec.
+ function fromJsonObject (that, object) {
+ var array
+ var length = 0
- // The use of `res.request.uri.href` ensures that `window.location.href`
- // is updated when `request` follows redirects.
- config.html = responseText;
- config.url = res.request.uri.href;
+ if (object.type === 'Buffer' && isArray(object.data)) {
+ array = object.data
+ length = checked(array.length) | 0
+ }
+ that = allocate(that, length)
- if (config.parsingMode === "auto" && (
- res.headers["content-type"] === "application/xml" ||
- res.headers["content-type"] === "text/xml" ||
- res.headers["content-type"] === "application/xhtml+xml")) {
- config.parsingMode = "xml";
- }
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+ }
- processHTML(config);
- });
+ function allocate (that, length) {
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = Buffer._augment(new Uint8Array(length))
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that.length = length
+ that._isBuffer = true
}
- };
- exports.serializeDocument = function (doc) {
- return domToHtml(doc, true);
- };
+ var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
+ if (fromPool) that.parent = rootParent
- function processHTML(config) {
- var options = {
- features: config.features,
- url: config.url,
- parser: config.parser,
- parsingMode: config.parsingMode,
- created: config.created,
- level: config.level
- };
+ return that
+ }
- if (config.document) {
- options.referrer = config.document.referrer;
- options.cookie = config.document.cookie;
- options.cookieDomain = config.document.cookieDomain;
+ function checked (length) {
+ // Note: cannot use `length < kMaxLength` here because that fails when
+ // length is NaN (which is otherwise coerced to zero.)
+ if (length >= kMaxLength()) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
+ 'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
+ return length | 0
+ }
+
+ function SlowBuffer (subject, encoding) {
+ if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
- var window = exports.jsdom(config.html, options).parentWindow;
- var features = JSON.parse(JSON.stringify(window.document.implementation._features));
+ var buf = new Buffer(subject, encoding)
+ delete buf.parent
+ return buf
+ }
- var docsLoaded = 0;
- var totalDocs = config.scripts.length + config.src.length;
- var readyState = null;
- var errors = [];
+ Buffer.isBuffer = function isBuffer (b) {
+ return !!(b != null && b._isBuffer)
+ }
- if (!window || !window.document) {
- if (config.created) {
- config.created(new Error('JSDOM: a window object could not be created.'));
- }
- if (config.done) {
- config.done([new Error('JSDOM: a window object could not be created.')]);
- }
- return;
+ Buffer.compare = function compare (a, b) {
+ if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
+ throw new TypeError('Arguments must be Buffers')
}
- window.document.implementation.addFeature('FetchExternalResources', ['script']);
- window.document.implementation.addFeature('ProcessExternalResources', ['script']);
- window.document.implementation.addFeature('MutationEvents', ['2.0']);
+ if (a === b) return 0
- function scriptComplete() {
- docsLoaded++;
+ var x = a.length
+ var y = b.length
- if (docsLoaded >= totalDocs) {
- window.document.implementation._features = features;
+ var i = 0
+ var len = Math.min(x, y)
+ while (i < len) {
+ if (a[i] !== b[i]) break
- errors = errors.concat(window.document.errors || []);
- if (errors.length === 0) {
- errors = null;
- }
+ ++i
+ }
- process.nextTick(function() {
- if (config.loaded) {
- config.loaded(errors, window);
- }
- if (config.done) {
- config.done(errors, window);
- }
- });
- }
- }
-
- function handleScriptError(e) {
- if (!errors) {
- errors = [];
- }
- errors.push(e.error || e.message);
-
- // nextTick so that an exception within scriptComplete won't cause
- // another script onerror (which would be an infinite loop)
- process.nextTick(scriptComplete);
+ if (i !== len) {
+ x = a[i]
+ y = b[i]
}
- if (config.scripts.length > 0 || config.src.length > 0) {
- config.scripts.forEach(function (scriptSrc) {
- var script = window.document.createElement('script');
- script.className = 'jsdom';
- script.onload = scriptComplete;
- script.onerror = handleScriptError;
- script.src = scriptSrc;
-
- try {
- // protect against invalid dom
- // ex: http://www.google.com/foo#bar
- window.document.documentElement.appendChild(script);
- } catch (e) {
- handleScriptError(e);
- }
- });
-
- config.src.forEach(function (scriptText) {
- var script = window.document.createElement('script');
- script.onload = scriptComplete;
- script.onerror = handleScriptError;
- script.text = scriptText;
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+ }
- window.document.documentElement.appendChild(script);
- window.document.documentElement.removeChild(script);
- });
- } else {
- if (window.document.readyState === 'complete') {
- scriptComplete();
- } else {
- window.addEventListener('load', function() {
- scriptComplete();
- });
- }
+ Buffer.isEncoding = function isEncoding (encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'binary':
+ case 'base64':
+ case 'raw':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true
+ default:
+ return false
}
}
- function getConfigFromArguments(args, callback) {
- var config = {};
- if (typeof args[0] === 'object') {
- var configToClone = args[0];
- Object.keys(configToClone).forEach(function (key) {
- config[key] = configToClone[key];
- });
- } else {
- var stringToAutodetect = null;
-
- Array.prototype.forEach.call(args, function (arg) {
- switch (typeof arg) {
- case 'string':
- config.somethingToAutodetect = arg;
- break;
- case 'function':
- config.done = arg;
- break;
- case 'object':
- if (Array.isArray(arg)) {
- config.scripts = arg;
- } else {
- extend(config, arg);
- }
- break;
- }
- });
- }
+ Buffer.concat = function concat (list, length) {
+ if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
- if (!config.done && !config.created && !config.loaded) {
- throw new Error('Must pass a "created", "loaded", "done" option or a callback to jsdom.env.');
+ if (list.length === 0) {
+ return new Buffer(0)
}
- if (config.somethingToAutodetect === undefined &&
- config.html === undefined && !config.file && !config.url) {
- throw new Error('Must pass a "html", "file", or "url" option, or a string, to jsdom.env');
+ var i
+ if (length === undefined) {
+ length = 0
+ for (i = 0; i < list.length; i++) {
+ length += list[i].length
+ }
}
- config.scripts = ensureArray(config.scripts);
- config.src = ensureArray(config.src);
- config.parsingMode = config.parsingMode || "auto";
-
- config.features = config.features || {
- FetchExternalResources: false,
- ProcessExternalResources: false,
- SkipExternalResources: false
- };
-
- if (!config.url && config.file) {
- config.url = toFileUrl(config.file);
+ var buf = new Buffer(length)
+ var pos = 0
+ for (i = 0; i < list.length; i++) {
+ var item = list[i]
+ item.copy(buf, pos)
+ pos += item.length
}
-
- return config;
+ return buf
}
- function ensureArray(value) {
- var array = value || [];
- if (typeof array === 'string') {
- array = [array];
- }
- return array;
- }
+ function byteLength (string, encoding) {
+ if (typeof string !== 'string') string = '' + string
- function extend(config, overrides) {
- Object.keys(overrides).forEach(function (key) {
- config[key] = overrides[key];
- });
- }
+ var len = string.length
+ if (len === 0) return 0
- function setParsingModeFromExtension(config, filename) {
- if (config.parsingMode === "auto") {
- var ext = path.extname(filename);
- if (ext === ".xhtml" || ext === ".xml") {
- config.parsingMode = "xml";
+ // Use a for loop to avoid recursion
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'ascii':
+ case 'binary':
+ // Deprecated
+ case 'raw':
+ case 'raws':
+ return len
+ case 'utf8':
+ case 'utf-8':
+ return utf8ToBytes(string).length
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return len * 2
+ case 'hex':
+ return len >>> 1
+ case 'base64':
+ return base64ToBytes(string).length
+ default:
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
}
}
}
+ Buffer.byteLength = byteLength
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10)(module)))
-
-/***/ },
-/* 10 */
-/***/ function(module, exports) {
-
- module.exports = function(module) {
- if(!module.webpackPolyfill) {
- module.deprecate = function() {};
- module.paths = [];
- // module.parent = undefined by default
- module.children = [];
- module.webpackPolyfill = 1;
- }
- return module;
- }
+ // pre-set for values that may exist in the future
+ Buffer.prototype.length = undefined
+ Buffer.prototype.parent = undefined
+ function slowToString (encoding, start, end) {
+ var loweredCase = false
-/***/ },
-/* 11 */
-/***/ function(module, exports) {
+ start = start | 0
+ end = end === undefined || end === Infinity ? this.length : end | 0
- module.exports = require("fs");
+ if (!encoding) encoding = 'utf8'
+ if (start < 0) start = 0
+ if (end > this.length) end = this.length
+ if (end <= start) return ''
-/***/ },
-/* 12 */
-/***/ function(module, exports) {
+ while (true) {
+ switch (encoding) {
+ case 'hex':
+ return hexSlice(this, start, end)
- module.exports = require("path");
+ case 'utf8':
+ case 'utf-8':
+ return utf8Slice(this, start, end)
-/***/ },
-/* 13 */
-/***/ function(module, exports) {
+ case 'ascii':
+ return asciiSlice(this, start, end)
- module.exports = require("url");
+ case 'binary':
+ return binarySlice(this, start, end)
-/***/ },
-/* 14 */
-/***/ function(module, exports, __webpack_require__) {
+ case 'base64':
+ return base64Slice(this, start, end)
- var path = __webpack_require__(12);
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return utf16leSlice(this, start, end)
- /**
- * Intercepts a method by replacing the prototype's implementation
- * with a wrapper that invokes the given interceptor instead.
- *
- * utils.intercept(core.Element, 'inserBefore',
- * function(_super, args, newChild, refChild) {
- * console.log('insertBefore', newChild, refChild);
- * return _super.apply(this, args);
- * }
- * );
- */
- exports.intercept = function(clazz, method, interceptor) {
- var proto = clazz.prototype,
- _super = proto[method],
- unwrapArgs = interceptor.length > 2;
-
- proto[method] = function() {
- if (unwrapArgs) {
- var args = Array.prototype.slice.call(arguments);
- args.unshift(_super, arguments);
- return interceptor.apply(this, args);
- }
- else {
- return interceptor.call(this, _super, arguments);
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = (encoding + '').toLowerCase()
+ loweredCase = true
}
- };
- };
-
- exports.toFileUrl = function (fileName) {
- // Beyond just the `path.resolve`, this is mostly for the benefit of Windows,
- // where we need to convert '\' to '/' and add an extra '/' prefix before the
- // drive letter.
- var pathname = path.resolve(process.cwd(), fileName).replace(/\\/g, '/');
- if (pathname[0] !== '/') {
- pathname = '/' + pathname;
}
+ }
- return 'file://' + pathname;
- };
-
- /**
- * Define a setter on an object
- *
- * This method replaces any existing setter but leaves getters in place.
- *
- * - `object` {Object} the object to define the setter on
- * - `property` {String} the name of the setter
- * - `setterFn` {Function} the setter
- */
- exports.defineSetter = function defineSetter(object, property, setterFn) {
- var descriptor = Object.getOwnPropertyDescriptor(object, property) || {
- configurable: true,
- enumerable: true
- };
+ Buffer.prototype.toString = function toString () {
+ var length = this.length | 0
+ if (length === 0) return ''
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
+ return slowToString.apply(this, arguments)
+ }
- descriptor.set = setterFn;
+ Buffer.prototype.equals = function equals (b) {
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return true
+ return Buffer.compare(this, b) === 0
+ }
- Object.defineProperty(object, property, descriptor);
- };
+ Buffer.prototype.inspect = function inspect () {
+ var str = ''
+ var max = exports.INSPECT_MAX_BYTES
+ if (this.length > 0) {
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
+ if (this.length > max) str += ' ... '
+ }
+ return ''
+ }
- /**
- * Define a getter on an object
- *
- * This method replaces any existing getter but leaves setters in place.
- *
- * - `object` {Object} the object to define the getter on
- * - `property` {String} the name of the getter
- * - `getterFn` {Function} the getter
- */
- exports.defineGetter = function defineGetter(object, property, getterFn) {
- var descriptor = Object.getOwnPropertyDescriptor(object, property) || {
- configurable: true,
- enumerable: true
- };
+ Buffer.prototype.compare = function compare (b) {
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return 0
+ return Buffer.compare(this, b)
+ }
- descriptor.get = getterFn;
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
+ if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
+ else if (byteOffset < -0x80000000) byteOffset = -0x80000000
+ byteOffset >>= 0
- Object.defineProperty(object, property, descriptor);
- };
+ if (this.length === 0) return -1
+ if (byteOffset >= this.length) return -1
- /**
- * Create an object with the given prototype
- *
- * Optionally augment the created object.
- *
- * - `prototyp` {Object} the created object's prototype
- * - `[properties]` {Object} properties to attach to the created object
- */
- exports.createFrom = function createFrom(prototype, properties) {
- properties = properties || {};
+ // Negative offsets start from the end of the buffer
+ if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
- var descriptors = {};
- Object.getOwnPropertyNames(properties).forEach(function (name) {
- descriptors[name] = Object.getOwnPropertyDescriptor(properties, name);
- });
+ if (typeof val === 'string') {
+ if (val.length === 0) return -1 // special case: looking for empty string always fails
+ return String.prototype.indexOf.call(this, val, byteOffset)
+ }
+ if (Buffer.isBuffer(val)) {
+ return arrayIndexOf(this, val, byteOffset)
+ }
+ if (typeof val === 'number') {
+ if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
+ return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
+ }
+ return arrayIndexOf(this, [ val ], byteOffset)
+ }
- return Object.create(prototype, descriptors);
- };
+ function arrayIndexOf (arr, val, byteOffset) {
+ var foundIndex = -1
+ for (var i = 0; byteOffset + i < arr.length; i++) {
+ if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
+ if (foundIndex === -1) foundIndex = i
+ if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
+ } else {
+ foundIndex = -1
+ }
+ }
+ return -1
+ }
- /**
- * Create an inheritance relationship between two classes
- *
- * Optionally augment the inherited prototype.
- *
- * - `Superclass` {Function} the inherited class
- * - `Subclass` {Function} the inheriting class
- * - `[properties]` {Object} properties to attach to the inherited prototype
- */
- exports.inheritFrom = function inheritFrom(Superclass, Subclass, properties) {
- properties = properties || {};
+ throw new TypeError('val must be string, number or Buffer')
+ }
- Object.defineProperty(properties, 'constructor', {
- value: Subclass,
- writable: true,
- configurable: true
- });
+ // `get` is deprecated
+ Buffer.prototype.get = function get (offset) {
+ console.log('.get() is deprecated. Access using array indexes instead.')
+ return this.readUInt8(offset)
+ }
- Subclass.prototype = exports.createFrom(Superclass.prototype, properties);
- };
+ // `set` is deprecated
+ Buffer.prototype.set = function set (v, offset) {
+ console.log('.set() is deprecated. Access using array indexes instead.')
+ return this.writeUInt8(v, offset)
+ }
+ function hexWrite (buf, string, offset, length) {
+ offset = Number(offset) || 0
+ var remaining = buf.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
+ }
+ }
-/***/ },
-/* 15 */
-/***/ function(module, exports, __webpack_require__) {
+ // must be an even number of digits
+ var strLen = string.length
+ if (strLen % 2 !== 0) throw new Error('Invalid hex string')
- var core = __webpack_require__(16).dom.level2.core,
- html = __webpack_require__(18).dom.level2.html,
- utils = __webpack_require__(14),
- defineGetter = utils.defineGetter,
- defineSetter = utils.defineSetter,
- inheritFrom = utils.inheritFrom,
- cssom = __webpack_require__(24),
- cssstyle = __webpack_require__(42),
- assert = __webpack_require__(437);
-
- // What works now:
- // - Accessing the rules defined in individual stylesheets
- // - Modifications to style content attribute are reflected in style property
- // - Modifications to style property are reflected in style content attribute
- // TODO
- // - Modifications to style element's textContent are reflected in sheet property.
- // - Modifications to style element's sheet property are reflected in textContent.
- // - Modifications to link.href property are reflected in sheet property.
- // - Less-used features of link: disabled
- // - Less-used features of style: disabled, scoped, title
- // - CSSOM-View
- // - getComputedStyle(): requires default stylesheet, cascading, inheritance,
- // filtering by @media (screen? print?), layout for widths/heights
- // - Load events are not in the specs, but apparently some browsers
- // implement something. Should onload only fire after all @imports have been
- // loaded, or only the primary sheet?
-
- core.StyleSheet = cssom.StyleSheet;
- core.MediaList = cssom.MediaList;
- core.CSSStyleSheet = cssom.CSSStyleSheet;
- core.CSSRule = cssom.CSSRule;
- core.CSSStyleRule = cssom.CSSStyleRule;
- core.CSSMediaRule = cssom.CSSMediaRule;
- core.CSSImportRule = cssom.CSSImportRule;
- core.CSSStyleDeclaration = cssstyle.CSSStyleDeclaration;
-
- // Relavant specs
- // http://www.w3.org/TR/DOM-Level-2-Style (2000)
- // http://www.w3.org/TR/cssom-view/ (2008)
- // http://dev.w3.org/csswg/cssom/ (2010) Meant to replace DOM Level 2 Style
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/ HTML5, of course
- // http://dev.w3.org/csswg/css-style-attr/ not sure what's new here
-
- // Objects that aren't in cssom library but should be:
- // CSSRuleList (cssom just uses array)
- // CSSFontFaceRule
- // CSSPageRule
-
- // These rules don't really make sense to implement, so CSSOM draft makes them
- // obsolete.
- // CSSCharsetRule
- // CSSUnknownRule
-
- // These objects are considered obsolete by CSSOM draft, although modern
- // browsers implement them.
- // CSSValue
- // CSSPrimitiveValue
- // CSSValueList
- // RGBColor
- // Rect
- // Counter
-
- // StyleSheetList -
- // http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-StyleSheetList
- // added a push method to help manage the length
- core.StyleSheetList = function() {
- this._length = 0;
- };
- core.StyleSheetList.prototype = {
- item: function (i) {
- return this[i];
- },
- push: function (sheet) {
- this[this._length] = sheet;
- this._length++;
- },
- get length() {
- return this._length;
+ if (length > strLen / 2) {
+ length = strLen / 2
}
- };
-
- defineGetter(core.Document.prototype, 'styleSheets', function() {
- if (!this._styleSheets) {
- this._styleSheets = new core.StyleSheetList();
+ for (var i = 0; i < length; i++) {
+ var parsed = parseInt(string.substr(i * 2, 2), 16)
+ if (isNaN(parsed)) throw new Error('Invalid hex string')
+ buf[offset + i] = parsed
}
- // TODO: each style and link element should register its sheet on creation
- // and remove it on removal.
- return this._styleSheets;
- });
-
-
- /**
- * @this {html.HTMLLinkElement|html.HTMLStyleElement}
- * @param {string} url
- * @param {cssom.CSSStyleSheet} sheet
- * @see http://dev.w3.org/csswg/cssom/#requirements-on-user-agents-implementing0
- */
- function fetchStylesheet(url, sheet) {
- html.resourceLoader.load(this, url, function(data, filename) {
- // TODO: abort if the content-type is not text/css, and the document is
- // in strict mode
- sheet.href = html.resourceLoader.resolve(this.ownerDocument, url);
- evaluateStylesheet.call(this, data, sheet, url);
- });
+ return i
}
- /**
- * @this {html.HTMLLinkElement|html.HTMLStyleElement}
- * @param {string} data
- * @param {cssom.CSSStyleSheet} sheet
- * @param {string} baseUrl
- */
- function evaluateStylesheet(data, sheet, baseUrl) {
- // this is the element
- var newStyleSheet = cssom.parse(data);
- var spliceArgs = newStyleSheet.cssRules;
- spliceArgs.unshift(0, sheet.cssRules.length);
- Array.prototype.splice.apply(sheet.cssRules, spliceArgs);
- scanForImportRules.call(this, sheet.cssRules, baseUrl);
- this.ownerDocument.styleSheets.push(sheet);
+
+ function utf8Write (buf, string, offset, length) {
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
- /**
- * @this {html.HTMLLinkElement|html.HTMLStyleElement}
- * @param {cssom.CSSStyleSheet} sheet
- * @param {string} baseUrl
- */
- function scanForImportRules(cssRules, baseUrl) {
- if (!cssRules) return;
- for (var i = 0; i < cssRules.length; ++i) {
- if (cssRules[i].cssRules) {
- // @media rule: keep searching inside it.
- scanForImportRules.call(this, cssRules[i].cssRules, baseUrl);
- } else if (cssRules[i].href) {
- // @import rule: fetch the resource and evaluate it.
- // See http://dev.w3.org/csswg/cssom/#css-import-rule
- // If loading of the style sheet fails its cssRules list is simply
- // empty. I.e. an @import rule always has an associated style sheet.
- fetchStylesheet.call(this, cssRules[i].href, this.sheet);
- }
- }
+
+ function asciiWrite (buf, string, offset, length) {
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
}
- /**
- * @param {string} data
- * @param {cssstyle.CSSStyleDeclaration} style
- */
- function evaluateStyleAttribute(data) {
- // this is the element.
+ function binaryWrite (buf, string, offset, length) {
+ return asciiWrite(buf, string, offset, length)
+ }
+ function base64Write (buf, string, offset, length) {
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
}
- /**
- * Subclass of core.Attr that reflects the current cssText.
- */
- function StyleAttr(node, value) {
- this._node = node;
- core.Attr.call(this, node.ownerDocument, 'style');
- if (!this._node._ignoreValueOfStyleAttr) {
- this.nodeValue = value;
- }
+ function ucs2Write (buf, string, offset, length) {
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
- inheritFrom(core.Attr, StyleAttr, {
- get nodeValue() {
- if (typeof this._node._style === 'string') {
- return this._node._style;
+
+ Buffer.prototype.write = function write (string, offset, length, encoding) {
+ // Buffer#write(string)
+ if (offset === undefined) {
+ encoding = 'utf8'
+ length = this.length
+ offset = 0
+ // Buffer#write(string, encoding)
+ } else if (length === undefined && typeof offset === 'string') {
+ encoding = offset
+ length = this.length
+ offset = 0
+ // Buffer#write(string, offset[, length][, encoding])
+ } else if (isFinite(offset)) {
+ offset = offset | 0
+ if (isFinite(length)) {
+ length = length | 0
+ if (encoding === undefined) encoding = 'utf8'
} else {
- return this._node.style.cssText;
+ encoding = length
+ length = undefined
}
- },
- set nodeValue(value) {
- this._node._style = value;
+ // legacy write(string, encoding, offset, length) - remove in v0.13
+ } else {
+ var swap = encoding
+ encoding = offset
+ offset = length | 0
+ length = swap
}
- });
- /**
- * Overwrite core.AttrNodeMap#setNamedItem to create a StyleAttr instance
- * instead of a core.Attr if the name equals 'style'.
- */
- utils.intercept(core.AttributeList, '$setNode', function(_super, args, attr) {
- if (attr.name == 'style') {
- attr = new StyleAttr(this._parentNode, attr.nodeValue);
- }
- return _super.call(this, attr);
- });
+ var remaining = this.length - offset
+ if (length === undefined || length > remaining) length = remaining
- /**
- * Lazily create a CSSStyleDeclaration.
- */
- defineGetter(html.HTMLElement.prototype, 'style', function() {
- if (typeof this._style === 'string') {
- // currently, cssom's parse doesn't really work if you pass in
- // {state: 'name'}, so instead we just build a dummy sheet.
- var styleSheet = cssom.parse('dummy{' + this._style + '}');
- this._style = new cssstyle.CSSStyleDeclaration();
- if (styleSheet.cssRules.length > 0 && styleSheet.cssRules[0].style) {
- var newStyle = styleSheet.cssRules[0].style;
- for (var i = 0; i < newStyle.length; ++i) {
- var prop = newStyle[i];
- this._style.setProperty(
- prop,
- newStyle.getPropertyValue(prop),
- newStyle.getPropertyPriority(prop));
- }
- }
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
+ throw new RangeError('attempt to write outside buffer bounds')
}
- if (!this._style) {
- this._style = new cssstyle.CSSStyleDeclaration();
- }
- if (!this.getAttributeNode('style')) {
- // Tell the StyleAttr constructor to not overwrite this._style
- this._ignoreValueOfStyleAttr = true;
- this.setAttribute('style');
- this._ignoreValueOfStyleAttr = false;
- }
- return this._style;
- });
+ if (!encoding) encoding = 'utf8'
- assert.equal(undefined, html.HTMLLinkElement._init);
- html.HTMLLinkElement._init = function() {
- this.addEventListener('DOMNodeInsertedIntoDocument', function() {
- if (!/(?:[ \t\n\r\f]|^)stylesheet(?:[ \t\n\r\f]|$)/i.test(this.rel)) {
- // rel is a space-separated list of tokens, and the original rel types
- // are case-insensitive.
- return;
- }
- if (this.href) {
- fetchStylesheet.call(this, this.href, this.sheet);
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'hex':
+ return hexWrite(this, string, offset, length)
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Write(this, string, offset, length)
+
+ case 'ascii':
+ return asciiWrite(this, string, offset, length)
+
+ case 'binary':
+ return binaryWrite(this, string, offset, length)
+
+ case 'base64':
+ // Warning: maxLength not taken into account in base64Write
+ return base64Write(this, string, offset, length)
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return ucs2Write(this, string, offset, length)
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
}
- });
- this.addEventListener('DOMNodeRemovedFromDocument', function() {
- });
- };
- /**
- * @this {HTMLStyleElement|HTMLLinkElement}
- */
- var getOrCreateSheet = function() {
- if (!this._cssStyleSheet) {
- this._cssStyleSheet = new cssom.CSSStyleSheet();
}
- return this._cssStyleSheet;
- };
- defineGetter(html.HTMLLinkElement.prototype, 'sheet', getOrCreateSheet);
-
- assert.equal(undefined, html.HTMLStyleElement._init);
- html.HTMLStyleElement._init = function() {
- //console.log('init style')
- this.addEventListener('DOMNodeInsertedIntoDocument', function() {
- //console.log('style inserted')
- //console.log('sheet: ', this.sheet);
- if (this.type && this.type !== 'text/css') {
- //console.log('bad type: ' + this.type)
- return;
- }
- var content = '';
- Array.prototype.forEach.call(this.childNodes, function (child) {
- if (child.nodeType === child.TEXT_NODE) { // text node
- content += child.nodeValue;
- }
- });
- evaluateStylesheet.call(this, content, this.sheet, this._ownerDocument.URL);
- });
- };
- defineGetter(html.HTMLStyleElement.prototype, 'sheet', getOrCreateSheet);
+ }
- exports.dom = {
- level2 : {
- html : html,
- core : core
+ Buffer.prototype.toJSON = function toJSON () {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
}
- };
+ }
+ function base64Slice (buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return base64.fromByteArray(buf)
+ } else {
+ return base64.fromByteArray(buf.slice(start, end))
+ }
+ }
-/***/ },
-/* 16 */
-/***/ function(module, exports, __webpack_require__) {
+ function utf8Slice (buf, start, end) {
+ end = Math.min(buf.length, end)
+ var res = []
- var core = __webpack_require__(17).dom.level1.core;
- var defineGetter = __webpack_require__(14).defineGetter;
- var defineSetter = __webpack_require__(14).defineSetter;
-
- // modify cloned instance for more info check: https://github.com/tmpvar/jsdom/issues/325
- core = Object.create(core);
-
- var INVALID_STATE_ERR = core.INVALID_STATE_ERR = 11,
- SYNTAX_ERR = core.SYNTAX_ERR = 12,
- INVALID_MODIFICATION_ERR = core.INVALID_MODIFICATION_ERR = 13,
- NAMESPACE_ERR = core.NAMESPACE_ERR = 14,
- INVALID_ACCESS_ERR = core.INVALID_ACCESS_ERR = 15,
- ns = {
- validate : function(ns, URI) {
- if (!ns) {
- throw new core.DOMException(core.INVALID_CHARACTER_ERR, "namespace is undefined");
- }
+ var i = start
+ while (i < end) {
+ var firstByte = buf[i]
+ var codePoint = null
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
+ : (firstByte > 0xDF) ? 3
+ : (firstByte > 0xBF) ? 2
+ : 1
- if(ns.match(/[^0-9a-z\.:\-_]/i) !== null) {
- throw new core.DOMException(core.INVALID_CHARACTER_ERR, ns);
- }
+ if (i + bytesPerSequence <= end) {
+ var secondByte, thirdByte, fourthByte, tempCodePoint
- var msg = false, parts = ns.split(':');
- if (ns === 'xmlns' &&
- URI !== "http://www.w3.org/2000/xmlns/")
- {
- msg = "localName is 'xmlns' but the namespaceURI is invalid";
+ switch (bytesPerSequence) {
+ case 1:
+ if (firstByte < 0x80) {
+ codePoint = firstByte
+ }
+ break
+ case 2:
+ secondByte = buf[i + 1]
+ if ((secondByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
+ if (tempCodePoint > 0x7F) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 3:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 4:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ fourthByte = buf[i + 3]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
+ codePoint = tempCodePoint
+ }
+ }
+ }
+ }
- } else if (ns === "xml" &&
- URI !== "http://www.w3.org/XML/1998/namespace")
- {
- msg = "localName is 'xml' but the namespaceURI is invalid";
+ if (codePoint === null) {
+ // we did not generate a valid codePoint so insert a
+ // replacement char (U+FFFD) and advance only 1 byte
+ codePoint = 0xFFFD
+ bytesPerSequence = 1
+ } else if (codePoint > 0xFFFF) {
+ // encode to utf16 (surrogate pair dance)
+ codePoint -= 0x10000
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800)
+ codePoint = 0xDC00 | codePoint & 0x3FF
+ }
- } else if (ns[ns.length-1] === ':') {
- msg = "Namespace seperator found with no localName";
+ res.push(codePoint)
+ i += bytesPerSequence
+ }
- } else if (ns[0] === ':') {
- msg = "Namespace seperator found, without a prefix";
+ return decodeCodePointsArray(res)
+ }
- } else if (parts.length > 2) {
- msg = "Too many namespace seperators";
+ // Based on http://stackoverflow.com/a/22747272/680742, the browser with
+ // the lowest limit is Chrome, with 0x10000 args.
+ // We go 1 magnitude less, for safety
+ var MAX_ARGUMENTS_LENGTH = 0x1000
- }
+ function decodeCodePointsArray (codePoints) {
+ var len = codePoints.length
+ if (len <= MAX_ARGUMENTS_LENGTH) {
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
+ }
- if (msg) {
- throw new core.DOMException(NAMESPACE_ERR, msg + " (" + ns + "@" + URI + ")");
- }
- }
- };
+ // Decode in chunks to avoid "call stack size exceeded".
+ var res = ''
+ var i = 0
+ while (i < len) {
+ res += String.fromCharCode.apply(
+ String,
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
+ )
+ }
+ return res
+ }
- core.exceptionMessages['NAMESPACE_ERR'] = "Invalid namespace";
-
- core.DOMImplementation.prototype.createDocumentType = function(/* String */ qualifiedName,
- /* String */ publicId,
- /* String */ systemId)
- {
- ns.validate(qualifiedName);
- var doctype = new core.DocumentType(null, qualifiedName);
- doctype._publicId = String(publicId);
- doctype._systemId = String(systemId);
- return doctype;
- };
+ function asciiSlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
- /**
- Creates an XML Document object of the specified type with its document element.
- HTML-only DOM implementations do not need to implement this method.
- */
- core.DOMImplementation.prototype.createDocument = function(/* String */ namespaceURI,
- /* String */ qualifiedName,
- /* DocumentType */ doctype)
- {
- if (qualifiedName || namespaceURI) {
- ns.validate(qualifiedName, namespaceURI);
+ for (var i = start; i < end; i++) {
+ ret += String.fromCharCode(buf[i] & 0x7F)
}
+ return ret
+ }
- if (doctype && doctype._ownerDocument !== null) {
- throw new core.DOMException(core.WRONG_DOCUMENT_ERR);
- }
+ function binarySlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
- if (qualifiedName && qualifiedName.indexOf(':') > -1 && !namespaceURI) {
- throw new core.DOMException(NAMESPACE_ERR);
+ for (var i = start; i < end; i++) {
+ ret += String.fromCharCode(buf[i])
}
+ return ret
+ }
- var document = new core.Document();
+ function hexSlice (buf, start, end) {
+ var len = buf.length
- if (doctype) {
- document.doctype = doctype;
- doctype._ownerDocument = document;
- document.appendChild(doctype);
- } else {
- document.doctype = null;
+ if (!start || start < 0) start = 0
+ if (!end || end < 0 || end > len) end = len
+
+ var out = ''
+ for (var i = start; i < end; i++) {
+ out += toHex(buf[i])
}
+ return out
+ }
- if (doctype && !doctype.entities) {
- doctype.entities = new core.EntityNodeMap();
+ function utf16leSlice (buf, start, end) {
+ var bytes = buf.slice(start, end)
+ var res = ''
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
+ return res
+ }
- document._ownerDocument = document;
+ Buffer.prototype.slice = function slice (start, end) {
+ var len = this.length
+ start = ~~start
+ end = end === undefined ? len : ~~end
- if (qualifiedName) {
- var docElement = document.createElementNS(namespaceURI, qualifiedName);
- document.appendChild(docElement);
+ if (start < 0) {
+ start += len
+ if (start < 0) start = 0
+ } else if (start > len) {
+ start = len
}
- return document;
- };
+ if (end < 0) {
+ end += len
+ if (end < 0) end = 0
+ } else if (end > len) {
+ end = len
+ }
- defineGetter(core.Node.prototype, "ownerDocument", function() {
- return this._ownerDocument || null;
- });
+ if (end < start) end = start
- core.Node.prototype.isSupported = function(/* string */ feature,
- /* string */ version)
- {
- return this._ownerDocument.implementation.hasFeature(feature, version);
- };
+ var newBuf
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ newBuf = Buffer._augment(this.subarray(start, end))
+ } else {
+ var sliceLen = end - start
+ newBuf = new Buffer(sliceLen, undefined)
+ for (var i = 0; i < sliceLen; i++) {
+ newBuf[i] = this[i + start]
+ }
+ }
- core.Node.prototype._namespaceURI = null;
- defineGetter(core.Node.prototype, "namespaceURI", function() {
- return this._namespaceURI || null;
- });
+ if (newBuf.length) newBuf.parent = this.parent || this
- defineSetter(core.Node.prototype, "namespaceURI", function(value) {
- this._namespaceURI = value;
- });
+ return newBuf
+ }
- defineGetter(core.Node.prototype, "prefix", function() {
- return this._prefix || null;
- });
+ /*
+ * Need to make sure that buffer isn't trying to write out of bounds.
+ */
+ function checkOffset (offset, ext, length) {
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
+ }
- defineSetter(core.Node.prototype, "prefix", function(value) {
+ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
- if (this.readonly) {
- throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
}
- ns.validate(value, this._namespaceURI);
+ return val
+ }
- if ((this._created && !this._namespaceURI) ||
- this._prefix === "xmlns" ||
- (!this._prefix && this._created))
- {
- throw new core.DOMException(core.NAMESPACE_ERR);
+ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) {
+ checkOffset(offset, byteLength, this.length)
}
- if (this._localName) {
- this._nodeName = value + ':' + this._localName;
+ var val = this[offset + --byteLength]
+ var mul = 1
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul
}
- this._prefix = value;
- });
+ return val
+ }
- defineGetter(core.Node.prototype, "localName", function() {
- return this._localName || null;
- });
+ Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ return this[offset]
+ }
- /* return boolean */
- core.Node.prototype.hasAttributes = function() {
- return (this.nodeType === this.ELEMENT_NODE &&
- this._attributes &&
- this._attributes.length > 0);
- };
+ Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return this[offset] | (this[offset + 1] << 8)
+ }
- core.NamedNodeMap.prototype.getNamedItemNS = function(/* string */ namespaceURI,
- /* string */ localName)
- {
- if (this._nsStore[namespaceURI] && this._nsStore[namespaceURI][localName]) {
- return this._nsStore[namespaceURI][localName];
- }
- return null;
- };
+ Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return (this[offset] << 8) | this[offset + 1]
+ }
- core.NamedNodeMap.prototype.setNamedItemNS = function(/* Node */ arg)
- {
- if (this._readonly) {
- throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
- }
+ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
- var owner = this._ownerDocument;
- if (this._parentNode &&
- this._parentNode._parentNode &&
- this._parentNode._parentNode.nodeType === owner.ENTITY_NODE)
- {
- throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
- }
+ return ((this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16)) +
+ (this[offset + 3] * 0x1000000)
+ }
- if (this._ownerDocument !== arg.ownerDocument) {
- throw new core.DOMException(core.WRONG_DOCUMENT_ERR);
- }
+ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
- if (arg._ownerElement) {
- throw new core.DOMException(core.INUSE_ATTRIBUTE_ERR);
- }
+ return (this[offset] * 0x1000000) +
+ ((this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ this[offset + 3])
+ }
+
+ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
- // readonly
- if (this._readonly === true) {
- throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
}
+ mul *= 0x80
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- if (!this._nsStore[arg.namespaceURI]) {
- this._nsStore[arg.namespaceURI] = {};
- }
- var existing = null;
- if (this._nsStore[arg.namespaceURI][arg.localName]) {
- var existing = this._nsStore[arg.namespaceURI][arg.localName];
+ return val
+ }
+
+ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var i = byteLength
+ var mul = 1
+ var val = this[offset + --i]
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul
}
+ mul *= 0x80
- this._nsStore[arg.namespaceURI][arg.localName] = arg;
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- arg._specified = true;
- arg._ownerDocument = this._ownerDocument;
+ return val
+ }
- return this.setNamedItem(arg);
- };
+ Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ if (!(this[offset] & 0x80)) return (this[offset])
+ return ((0xff - this[offset] + 1) * -1)
+ }
- core.NamedNodeMap.prototype.removeNamedItemNS = function(/*string */ namespaceURI,
- /* string */ localName)
- {
+ Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset] | (this[offset + 1] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+ }
- if (this.readonly) {
- throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
- }
+ Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset + 1] | (this[offset] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+ }
+ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
- var parent = this._parentNode,
- found = null,
- defaults,
- clone,
- defaultEl,
- defaultAttr;
+ return (this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16) |
+ (this[offset + 3] << 24)
+ }
- if (this._parentNode &&
- this._parentNode._parentNode &&
- this._parentNode._parentNode.nodeType === this._ownerDocument.ENTITY_NODE)
- {
- throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
- }
+ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
- if (this._nsStore[namespaceURI] &&
- this._nsStore[namespaceURI][localName])
- {
- found = this._nsStore[namespaceURI][localName];
- this.removeNamedItem(found.qualifiedName);
- delete this._nsStore[namespaceURI][localName];
- }
+ return (this[offset] << 24) |
+ (this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ (this[offset + 3])
+ }
- if (!found) {
- throw new core.DOMException(core.NOT_FOUND_ERR);
- }
+ Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, true, 23, 4)
+ }
- if (parent.ownerDocument.doctype && parent.ownerDocument.doctype._attributes) {
- defaults = parent.ownerDocument.doctype._attributes;
- defaultEl = defaults.getNamedItemNS(parent._namespaceURI, parent._localName);
- }
+ Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, false, 23, 4)
+ }
- if (defaultEl) {
- defaultAttr = defaultEl._attributes.getNamedItemNS(namespaceURI, localName);
-
- if (defaultAttr) {
- clone = defaultAttr.cloneNode(true);
- clone._created = false;
- clone._namespaceURI = found._namespaceURI;
- clone._nodeName = found.name;
- clone._localName = found._localName;
- clone._prefix = found._prefix
- this.setNamedItemNS(clone);
- clone._created = true;
- clone._specified = false;
- }
+ Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, true, 52, 8)
+ }
+
+ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, false, 52, 8)
+ }
+
+ function checkInt (buf, value, offset, ext, max, min) {
+ if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
+ if (value > max || value < min) throw new RangeError('value is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('index out of range')
+ }
+
+ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+
+ var mul = 1
+ var i = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
}
- return found;
- };
+ return offset + byteLength
+ }
- defineGetter(core.Attr.prototype, "ownerElement", function() {
- return this._ownerElement || null;
- });
+ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+ var i = byteLength - 1
+ var mul = 1
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
- core.Node.prototype._prefix = false;
+ return offset + byteLength
+ }
- defineSetter(core.Node.prototype, "qualifiedName", function(qualifiedName) {
- ns.validate(qualifiedName, this._namespaceURI);
- qualifiedName = qualifiedName || "";
- this._localName = qualifiedName.split(":")[1] || null;
- this.prefix = qualifiedName.split(":")[0] || null;
- this._nodeName = qualifiedName;
- });
+ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+ this[offset] = value
+ return offset + 1
+ }
- defineGetter(core.Node.prototype, "qualifiedName", function() {
- return this._nodeName;
- });
+ function objectWriteUInt16 (buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffff + value + 1
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
+ buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+ (littleEndian ? i : 1 - i) * 8
+ }
+ }
- core.NamedNodeMap.prototype._map = function(fn) {
- var ret = [], l = this.length, i = 0, node;
- for(i; i>> 8)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
}
- return ret;
- };
+ return offset + 2
+ }
- core.Element.prototype.getAttribute = function(/* string */ name)
- {
- var attr = this.getAttributeNode(name);
- return attr && attr.value;
- };
+ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 8)
+ this[offset + 1] = value
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
+ return offset + 2
+ }
- core.Element.prototype.getAttributeNode = function(/* string */ name)
- {
- return this._attributes.$getNoNS(name);
- };
+ function objectWriteUInt32 (buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffffffff + value + 1
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
+ buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+ }
+ }
- core.Element.prototype.removeAttribute = function(/* string */ name)
- {
- return this._attributes.$removeNoNS(name);
- };
+ Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset + 3] = (value >>> 24)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 1] = (value >>> 8)
+ this[offset] = value
+ } else {
+ objectWriteUInt32(this, value, offset, true)
+ }
+ return offset + 4
+ }
- core.Element.prototype.getAttributeNS = function(/* string */ namespaceURI,
- /* string */ localName)
- {
- if (namespaceURI === "") {
- namespaceURI = null;
+ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = value
+ } else {
+ objectWriteUInt32(this, value, offset, false)
}
+ return offset + 4
+ }
- var attr = this._attributes.$getNode(namespaceURI, localName);
- return attr && attr.value;
- };
+ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1)
- core.Element.prototype.setAttribute = function(/* string */ name,
- /* string */ value)
- {
- this._attributes.$setNoNS(name, value);
- };
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
- core.Element.prototype.setAttributeNS = function(/* string */ namespaceURI,
- /* string */ qualifiedName,
- /* string */ value)
- {
- if (namespaceURI === "") {
- namespaceURI = null;
+ var i = 0
+ var mul = 1
+ var sub = value < 0 ? 1 : 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
- var s = qualifiedName.split(':'),
- local = s.pop(),
- prefix = s.pop() || null,
- attr;
+ return offset + byteLength
+ }
- ns.validate(qualifiedName, namespaceURI);
+ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1)
- if (prefix !== null && !namespaceURI) {
- throw new core.DOMException(core.NAMESPACE_ERR);
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
- if (prefix === "xml" &&
- namespaceURI !== "http://www.w3.org/XML/1998/namespace") {
- throw new core.DOMException(core.NAMESPACE_ERR);
+ var i = byteLength - 1
+ var mul = 1
+ var sub = value < 0 ? 1 : 0
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
- if (prefix === "xmlns" && namespaceURI !== "http://www.w3.org/2000/xmlns/") {
- throw new core.DOMException(core.NAMESPACE_ERR);
+ return offset + byteLength
+ }
+
+ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+ if (value < 0) value = 0xff + value + 1
+ this[offset] = value
+ return offset + 1
+ }
+
+ Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value
+ this[offset + 1] = (value >>> 8)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
}
+ return offset + 2
+ }
- this._attributes.$set(local, value, qualifiedName, prefix, namespaceURI);
- };
+ Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 8)
+ this[offset + 1] = value
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
+ return offset + 2
+ }
- core.Element.prototype.removeAttributeNS = function(/* string */ namespaceURI,
- /* string */ localName)
- {
- if (namespaceURI === "") {
- namespaceURI = null;
+ Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value
+ this[offset + 1] = (value >>> 8)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 3] = (value >>> 24)
+ } else {
+ objectWriteUInt32(this, value, offset, true)
}
+ return offset + 4
+ }
- this._attributes.$remove(namespaceURI, localName);
- };
+ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (value < 0) value = 0xffffffff + value + 1
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = value
+ } else {
+ objectWriteUInt32(this, value, offset, false)
+ }
+ return offset + 4
+ }
+
+ function checkIEEE754 (buf, value, offset, ext, max, min) {
+ if (value > max || value < min) throw new RangeError('value is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('index out of range')
+ if (offset < 0) throw new RangeError('index out of range')
+ }
- core.Element.prototype.getAttributeNodeNS = function(/* string */ namespaceURI,
- /* string */ localName)
- {
- if (namespaceURI === "") {
- namespaceURI = null;
+ function writeFloat (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
+ return offset + 4
+ }
- return this._attributes.$getNode(namespaceURI, localName);
- };
- core.Element.prototype._created = false;
+ Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert)
+ }
+
+ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert)
+ }
- core.Element.prototype.setAttributeNodeNS = function(/* Attr */ newAttr)
- {
- if (newAttr.ownerElement) {
- throw new core.DOMException(core.INUSE_ATTRIBUTE_ERR);
+ function writeDouble (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+ return offset + 8
+ }
- return this._attributes.$setNode(newAttr);
- };
+ Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert)
+ }
- core.Element.prototype.getElementsByTagNameNS = core.memoizeQuery(function(/* String */ namespaceURI,
- /* String */ localName)
- {
- var nsPrefixCache = {};
+ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert)
+ }
- function filterByTagName(child) {
- if (child.nodeType && child.nodeType === this.ENTITY_REFERENCE_NODE) {
- child = child._entity;
- }
+ // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
+ if (!start) start = 0
+ if (!end && end !== 0) end = this.length
+ if (targetStart >= target.length) targetStart = target.length
+ if (!targetStart) targetStart = 0
+ if (end > 0 && end < start) end = start
- var localMatch = child.localName === localName,
- nsMatch = child.namespaceURI === namespaceURI;
+ // Copy 0 bytes; we're done
+ if (end === start) return 0
+ if (target.length === 0 || this.length === 0) return 0
- if ((localMatch || localName === "*") &&
- (nsMatch || namespaceURI === "*"))
- {
- if (child.nodeType === child.ELEMENT_NODE) {
- return true;
- }
- }
- return false;
+ // Fatal error conditions
+ if (targetStart < 0) {
+ throw new RangeError('targetStart out of bounds')
}
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
- return new core.NodeList(this.ownerDocument || this,
- core.mapper(this, filterByTagName));
- });
-
- core.Element.prototype.hasAttribute = function(/* string */name)
- {
- if (!this._attributes) {
- return false;
+ // Are we oob?
+ if (end > this.length) end = this.length
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start
}
- return !!this._attributes.$getNoNS(name);
- };
+ var len = end - start
+ var i
- core.Element.prototype.hasAttributeNS = function(/* string */namespaceURI,
- /* string */localName)
- {
- if (namespaceURI === "") {
- namespaceURI = null;
+ if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (i = len - 1; i >= 0; i--) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
+ // ascending copy from start
+ for (i = 0; i < len; i++) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else {
+ target._set(this.subarray(start, start + len), targetStart)
}
- return (this._attributes.getNamedItemNS(namespaceURI, localName) ||
- this.hasAttribute(localName));
- };
+ return len
+ }
- defineGetter(core.DocumentType.prototype, "publicId", function() {
- return this._publicId || "";
- });
+ // fill(value, start=0, end=buffer.length)
+ Buffer.prototype.fill = function fill (value, start, end) {
+ if (!value) value = 0
+ if (!start) start = 0
+ if (!end) end = this.length
- defineGetter(core.DocumentType.prototype, "systemId", function() {
- return this._systemId || "";
- });
+ if (end < start) throw new RangeError('end < start')
- defineGetter(core.DocumentType.prototype, "internalSubset", function() {
- return this._internalSubset || null;
- });
+ // Fill 0 bytes; we're done
+ if (end === start) return
+ if (this.length === 0) return
+
+ if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
+ if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
- core.Document.prototype.importNode = function(/* Node */ importedNode,
- /* bool */ deep)
- {
- if (importedNode && importedNode.nodeType) {
- if (importedNode.nodeType === this.DOCUMENT_NODE ||
- importedNode.nodeType === this.DOCUMENT_TYPE_NODE) {
- throw new core.DOMException(core.NOT_SUPPORTED_ERR);
+ var i
+ if (typeof value === 'number') {
+ for (i = start; i < end; i++) {
+ this[i] = value
+ }
+ } else {
+ var bytes = utf8ToBytes(value.toString())
+ var len = bytes.length
+ for (i = start; i < end; i++) {
+ this[i] = bytes[i % len]
}
}
- var self = this,
- newNode = importedNode.cloneNode(deep, function(a, b) {
- b._namespaceURI = a._namespaceURI;
- b._nodeName = a._nodeName;
- b._localName = a._localName;
- }),
- defaults = false,
- defaultEl;
-
- if (this.doctype && this.doctype._attributes) {
- defaults = this.doctype._attributes;
+ return this
+ }
+
+ /**
+ * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
+ * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
+ */
+ Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
+ if (typeof Uint8Array !== 'undefined') {
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ return (new Buffer(this)).buffer
+ } else {
+ var buf = new Uint8Array(this.length)
+ for (var i = 0, len = buf.length; i < len; i += 1) {
+ buf[i] = this[i]
+ }
+ return buf.buffer
+ }
+ } else {
+ throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
+ }
- function lastChance(el) {
- var attr, defaultEl, i, len;
+ // HELPER FUNCTIONS
+ // ================
- el._ownerDocument = self;
- if (el.id) {
- if (!self._ids) {self._ids = {};}
- if (!self._ids[el.id]) {self._ids[el.id] = [];}
- self._ids[el.id].push(el);
- }
- if (el._attributes) {
- var drop = [];
- el._attributes._ownerDocument = self;
- for (i=0,len=el._attributes.length; i < len; i++) {
- attr = el._attributes[i];
- // Attributes nodes that were expressing default values in the
- // original document must not be copied over. Record them.
- if (!attr._specified) {
- drop.push(attr);
- continue;
- }
+ var BP = Buffer.prototype
- attr._ownerDocument = self;
- }
+ /**
+ * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
+ */
+ Buffer._augment = function _augment (arr) {
+ arr.constructor = Buffer
+ arr._isBuffer = true
+
+ // save reference to original Uint8Array set method before overwriting
+ arr._set = arr.set
+
+ // deprecated
+ arr.get = BP.get
+ arr.set = BP.set
+
+ arr.write = BP.write
+ arr.toString = BP.toString
+ arr.toLocaleString = BP.toString
+ arr.toJSON = BP.toJSON
+ arr.equals = BP.equals
+ arr.compare = BP.compare
+ arr.indexOf = BP.indexOf
+ arr.copy = BP.copy
+ arr.slice = BP.slice
+ arr.readUIntLE = BP.readUIntLE
+ arr.readUIntBE = BP.readUIntBE
+ arr.readUInt8 = BP.readUInt8
+ arr.readUInt16LE = BP.readUInt16LE
+ arr.readUInt16BE = BP.readUInt16BE
+ arr.readUInt32LE = BP.readUInt32LE
+ arr.readUInt32BE = BP.readUInt32BE
+ arr.readIntLE = BP.readIntLE
+ arr.readIntBE = BP.readIntBE
+ arr.readInt8 = BP.readInt8
+ arr.readInt16LE = BP.readInt16LE
+ arr.readInt16BE = BP.readInt16BE
+ arr.readInt32LE = BP.readInt32LE
+ arr.readInt32BE = BP.readInt32BE
+ arr.readFloatLE = BP.readFloatLE
+ arr.readFloatBE = BP.readFloatBE
+ arr.readDoubleLE = BP.readDoubleLE
+ arr.readDoubleBE = BP.readDoubleBE
+ arr.writeUInt8 = BP.writeUInt8
+ arr.writeUIntLE = BP.writeUIntLE
+ arr.writeUIntBE = BP.writeUIntBE
+ arr.writeUInt16LE = BP.writeUInt16LE
+ arr.writeUInt16BE = BP.writeUInt16BE
+ arr.writeUInt32LE = BP.writeUInt32LE
+ arr.writeUInt32BE = BP.writeUInt32BE
+ arr.writeIntLE = BP.writeIntLE
+ arr.writeIntBE = BP.writeIntBE
+ arr.writeInt8 = BP.writeInt8
+ arr.writeInt16LE = BP.writeInt16LE
+ arr.writeInt16BE = BP.writeInt16BE
+ arr.writeInt32LE = BP.writeInt32LE
+ arr.writeInt32BE = BP.writeInt32BE
+ arr.writeFloatLE = BP.writeFloatLE
+ arr.writeFloatBE = BP.writeFloatBE
+ arr.writeDoubleLE = BP.writeDoubleLE
+ arr.writeDoubleBE = BP.writeDoubleBE
+ arr.fill = BP.fill
+ arr.inspect = BP.inspect
+ arr.toArrayBuffer = BP.toArrayBuffer
- // Remove obsolete default nodes.
- for(i = 0; i < drop.length; ++i) {
- el._attributes.$removeNode(drop[i]);
- }
+ return arr
+ }
- }
- if (defaults) {
-
- defaultEl = defaults.getNamedItemNS(el._namespaceURI,
- el._localName);
-
- // TODO: This could use some love
- if (defaultEl) {
- for(i = 0; i < defaultEl._attributes.length; ++i) {
- var defaultAttr = defaultEl._attributes[i];
- if (!el.hasAttributeNS(defaultAttr.namespaceURL,
- defaultAttr.localName))
- {
- var clone = defaultAttr.cloneNode(true);
- clone._namespaceURI = defaultAttr._namespaceURI;
- clone._prefix = defaultAttr._prefix;
- clone._localName = defaultAttr._localName;
- el.setAttributeNodeNS(clone);
- clone._specified = false;
- }
- }
- }
- }
+ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
+ function base64clean (str) {
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '')
+ // Node converts strings with length < 2 to ''
+ if (str.length < 2) return ''
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+ while (str.length % 4 !== 0) {
+ str = str + '='
}
+ return str
+ }
- if (deep) {
- core.visitTree(newNode, lastChance);
- }
- else {
- lastChance(newNode);
- }
+ function stringtrim (str) {
+ if (str.trim) return str.trim()
+ return str.replace(/^\s+|\s+$/g, '')
+ }
- if (newNode.nodeType == newNode.ATTRIBUTE_NODE) {
- newNode._specified = true;
- }
+ function toHex (n) {
+ if (n < 16) return '0' + n.toString(16)
+ return n.toString(16)
+ }
- return newNode;
- };
+ function utf8ToBytes (string, units) {
+ units = units || Infinity
+ var codePoint
+ var length = string.length
+ var leadSurrogate = null
+ var bytes = []
- core.Document.prototype.createElementNS = function(/* string */ namespaceURI,
- /* string */ qualifiedName)
- {
- var parts = qualifiedName.split(':'),
- element, prefix;
+ for (var i = 0; i < length; i++) {
+ codePoint = string.charCodeAt(i)
+
+ // is surrogate component
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (!leadSurrogate) {
+ // no lead yet
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ }
- if (parts.length > 1 && !namespaceURI) {
- throw new core.DOMException(core.NAMESPACE_ERR);
+ // valid lead
+ leadSurrogate = codePoint
+
+ continue
+ }
+
+ // 2 leads in a row
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = codePoint
+ continue
+ }
+
+ // valid surrogate pair
+ codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ }
+
+ leadSurrogate = null
+
+ // encode utf8
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break
+ bytes.push(codePoint)
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break
+ bytes.push(
+ codePoint >> 0x6 | 0xC0,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break
+ bytes.push(
+ codePoint >> 0xC | 0xE0,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x110000) {
+ if ((units -= 4) < 0) break
+ bytes.push(
+ codePoint >> 0x12 | 0xF0,
+ codePoint >> 0xC & 0x3F | 0x80,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else {
+ throw new Error('Invalid code point')
+ }
}
- ns.validate(qualifiedName, namespaceURI);
- element = this.createElement(qualifiedName),
+ return bytes
+ }
- element._created = false;
+ function asciiToBytes (str) {
+ var byteArray = []
+ for (var i = 0; i < str.length; i++) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF)
+ }
+ return byteArray
+ }
- element._namespaceURI = namespaceURI;
- element._nodeName = qualifiedName;
- element._localName = parts.pop();
+ function utf16leToBytes (str, units) {
+ var c, hi, lo
+ var byteArray = []
+ for (var i = 0; i < str.length; i++) {
+ if ((units -= 2) < 0) break
- if (parts.length > 0) {
- prefix = parts.pop();
- element.prefix = prefix;
+ c = str.charCodeAt(i)
+ hi = c >> 8
+ lo = c % 256
+ byteArray.push(lo)
+ byteArray.push(hi)
}
- element._created = true;
- return element;
- };
+ return byteArray
+ }
- core.Document.prototype.createAttributeNS = function(/* string */ namespaceURI,
- /* string */ qualifiedName)
- {
- var attribute, parts = qualifiedName.split(':');
+ function base64ToBytes (str) {
+ return base64.toByteArray(base64clean(str))
+ }
- if (parts.length > 1 && !namespaceURI) {
- throw new core.DOMException(core.NAMESPACE_ERR,
- "Prefix specified without namespaceURI (" + qualifiedName + ")");
+ function blitBuffer (src, dst, offset, length) {
+ for (var i = 0; i < length; i++) {
+ if ((i + offset >= dst.length) || (i >= src.length)) break
+ dst[i + offset] = src[i]
}
+ return i
+ }
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7).Buffer))
- ns.validate(qualifiedName, namespaceURI);
+/***/ },
+/* 8 */
+/***/ function(module, exports, __webpack_require__) {
- attribute = this.createAttribute(qualifiedName);
- attribute.namespaceURI = namespaceURI;
- attribute.qualifiedName = qualifiedName;
+ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- attribute._localName = parts.pop();
- attribute._prefix = (parts.length > 0) ? parts.pop() : null;
- return attribute;
- };
+ ;(function (exports) {
+ 'use strict';
- core.Document.prototype.getElementsByTagNameNS = function(/* String */ namespaceURI,
- /* String */ localName)
- {
- return core.Element.prototype.getElementsByTagNameNS.call(this,
- namespaceURI,
- localName);
- };
+ var Arr = (typeof Uint8Array !== 'undefined')
+ ? Uint8Array
+ : Array
- defineSetter(core.Element.prototype, "id", function(id) {
- this.setAttribute("id", id);
- });
+ var PLUS = '+'.charCodeAt(0)
+ var SLASH = '/'.charCodeAt(0)
+ var NUMBER = '0'.charCodeAt(0)
+ var LOWER = 'a'.charCodeAt(0)
+ var UPPER = 'A'.charCodeAt(0)
+ var PLUS_URL_SAFE = '-'.charCodeAt(0)
+ var SLASH_URL_SAFE = '_'.charCodeAt(0)
- defineGetter(core.Element.prototype, "id", function() {
- return this.getAttribute("id");
- });
+ function decode (elt) {
+ var code = elt.charCodeAt(0)
+ if (code === PLUS ||
+ code === PLUS_URL_SAFE)
+ return 62 // '+'
+ if (code === SLASH ||
+ code === SLASH_URL_SAFE)
+ return 63 // '/'
+ if (code < NUMBER)
+ return -1 //no match
+ if (code < NUMBER + 10)
+ return code - NUMBER + 26 + 26
+ if (code < UPPER + 26)
+ return code - UPPER
+ if (code < LOWER + 26)
+ return code - LOWER + 26
+ }
- core.Document.prototype.getElementById = function(id) {
- // return the first element
- return (this._ids && this._ids[id] && this._ids[id].length > 0 ? this._ids[id][0] : null);
- };
+ function b64ToByteArray (b64) {
+ var i, j, l, tmp, placeHolders, arr
+ if (b64.length % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
+ }
- exports.dom =
- {
- level2 : {
- core : core
- }
- };
+ // the number of equal signs (place holders)
+ // if there are two placeholders, than the two characters before it
+ // represent one byte
+ // if there is only one, then the three characters before it represent 2 bytes
+ // this is just a cheap hack to not do indexOf twice
+ var len = b64.length
+ placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
+ // base64 is 4/3 + up to two characters of the original data
+ arr = new Arr(b64.length * 3 / 4 - placeHolders)
-/***/ },
-/* 17 */
-/***/ function(module, exports, __webpack_require__) {
+ // if there are placeholders, only get up to the last complete 4 chars
+ l = placeHolders > 0 ? b64.length - 4 : b64.length
- /*
- ServerJS Javascript DOM Level 1
- */
- var inheritFrom = __webpack_require__(14).inheritFrom;
-
- // utility functions
- var attachId = function(id,elm,doc) {
- if (id && elm && doc) {
- if (!doc._ids[id]) {
- doc._ids[id] = [];
- }
- doc._ids[id].push(elm);
- }
- };
- var detachId = function(id,elm,doc) {
- var elms, i;
- if (id && elm && doc) {
- if (doc._ids && doc._ids[id]) {
- elms = doc._ids[id];
- for (i=0;i 2) {
- return fn;
- }
- return function() {
- if (!this._memoizedQueries) {
- return fn.apply(this, arguments);
- }
- if (!this._memoizedQueries[type]) {
- this._memoizedQueries[type] = {};
- }
- if (arguments.length !== 0 && typeof arguments[0] === 'string' && (arguments.length === 1 || (typeof arguments[1] === 'string' && arguments.length === 2))) {
- var k = String(arguments[0]);
- if (arguments.length === 2) {
- k += '::' + String(arguments[1]);
- }
- if (this._memoizedQueries[type].hasOwnProperty(k)) {
- return this._memoizedQueries[type][k];
- }
- return (this._memoizedQueries[type][k] = fn.apply(this, arguments));
- }
- return fn.apply(this, arguments);
- }
- },
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
+ tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
+ push((tmp & 0xFF0000) >> 16)
+ push((tmp & 0xFF00) >> 8)
+ push(tmp & 0xFF)
+ }
- // Returns Array
- mapDOMNodes : function(parent, recursive, callback) {
- function visit(parent, result) {
- return Array.prototype.reduce.call(parent.childNodes, reducer, result);
- }
+ if (placeHolders === 2) {
+ tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
+ push(tmp & 0xFF)
+ } else if (placeHolders === 1) {
+ tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
+ push((tmp >> 8) & 0xFF)
+ push(tmp & 0xFF)
+ }
- function reducer(array, child) {
- if (callback(child)) {
- array.push(child);
- }
- if (recursive && child._childNodes) {
- visit(child, array);
- }
- return array;
- }
+ return arr
+ }
- return visit(parent, []);
- },
+ function uint8ToBase64 (uint8) {
+ var i,
+ extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
+ output = "",
+ temp, length
- visitTree: function(root, callback) {
- var cur = root; // TODO: Unroll this.
+ function encode (num) {
+ return lookup.charAt(num)
+ }
- function visit(el) {
- if (el) {
- callback(el);
- if (el._childNodes) {
- var i = 0,
- children = el._childNodes,
- l = children.length;
+ function tripletToBase64 (num) {
+ return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
+ }
- for (i; i> 2)
+ output += encode((temp << 4) & 0x3F)
+ output += '=='
+ break
+ case 2:
+ temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
+ output += encode(temp >> 10)
+ output += encode((temp >> 4) & 0x3F)
+ output += encode((temp << 2) & 0x3F)
+ output += '='
+ break
+ }
- // ExceptionCode
- var INDEX_SIZE_ERR = core.INDEX_SIZE_ERR = 1,
- DOMSTRING_SIZE_ERR = core.DOMSTRING_SIZE_ERR = 2,
- HIERARCHY_REQUEST_ERR = core.HIERARCHY_REQUEST_ERR = 3,
- WRONG_DOCUMENT_ERR = core.WRONG_DOCUMENT_ERR = 4,
- INVALID_CHARACTER_ERR = core.INVALID_CHARACTER_ERR = 5,
- NO_DATA_ALLOWED_ERR = core.NO_DATA_ALLOWED_ERR = 6,
- NO_MODIFICATION_ALLOWED_ERR = core.NO_MODIFICATION_ALLOWED_ERR = 7,
- NOT_FOUND_ERR = core.NOT_FOUND_ERR = 8,
- NOT_SUPPORTED_ERR = core.NOT_SUPPORTED_ERR = 9,
- INUSE_ATTRIBUTE_ERR = core.INUSE_ATTRIBUTE_ERR = 10,
-
- // Node Types
- ELEMENT_NODE = 1,
- ATTRIBUTE_NODE = 2,
- TEXT_NODE = 3,
- CDATA_SECTION_NODE = 4,
- ENTITY_REFERENCE_NODE = 5,
- ENTITY_NODE = 6,
- PROCESSING_INSTRUCTION_NODE = 7,
- COMMENT_NODE = 8,
- DOCUMENT_NODE = 9,
- DOCUMENT_TYPE_NODE = 10,
- DOCUMENT_FRAGMENT_NODE = 11,
- NOTATION_NODE = 12;
-
- var messages = core.exceptionMessages = { };
- messages[INDEX_SIZE_ERR] = "Index size error";
- messages[DOMSTRING_SIZE_ERR] = "DOMString size error";
- messages[HIERARCHY_REQUEST_ERR] = "Hierarchy request error";
- messages[WRONG_DOCUMENT_ERR] = "Wrong document";
- messages[INVALID_CHARACTER_ERR] = "Invalid character";
- messages[NO_DATA_ALLOWED_ERR] = "No data allowed";
- messages[NO_MODIFICATION_ALLOWED_ERR] = "No modification allowed";
- messages[NOT_FOUND_ERR] = "Not found";
- messages[NOT_SUPPORTED_ERR] = "Not supported";
- messages[INUSE_ATTRIBUTE_ERR] = "Attribute in use";
-
- core.DOMException = function(code, message) {
- this.code = code;
- Error.call(this, core.exceptionMessages[code]);
- this.message = core.exceptionMessages[code];
- if(message) this.message = this.message + ": " + message;
- if(Error.captureStackTrace) Error.captureStackTrace(this, core.DOMException);
- };
+ return output
+ }
- core.DOMException.INDEX_SIZE_ERR = INDEX_SIZE_ERR;
- core.DOMException.DOMSTRING_SIZE_ERR = DOMSTRING_SIZE_ERR;
- core.DOMException.HIERARCHY_REQUEST_ERR = HIERARCHY_REQUEST_ERR;
- core.DOMException.WRONG_DOCUMENT_ERR = WRONG_DOCUMENT_ERR;
- core.DOMException.INVALID_CHARACTER_ERR = INVALID_CHARACTER_ERR;
- core.DOMException.NO_DATA_ALLOWED_ERR = NO_DATA_ALLOWED_ERR;
- core.DOMException.NO_MODIFICATION_ALLOWED_ERR = NO_MODIFICATION_ALLOWED_ERR;
- core.DOMException.NOT_FOUND_ERR = NOT_FOUND_ERR;
- core.DOMException.NOT_SUPPORTED_ERR = NOT_SUPPORTED_ERR;
- core.DOMException.INUSE_ATTRIBUTE_ERR = INUSE_ATTRIBUTE_ERR;
-
- inheritFrom(Error, core.DOMException, {
- INDEX_SIZE_ERR : INDEX_SIZE_ERR,
- DOMSTRING_SIZE_ERR : DOMSTRING_SIZE_ERR,
- HIERARCHY_REQUEST_ERR : HIERARCHY_REQUEST_ERR,
- WRONG_DOCUMENT_ERR : WRONG_DOCUMENT_ERR,
- INVALID_CHARACTER_ERR : INVALID_CHARACTER_ERR,
- NO_DATA_ALLOWED_ERR : NO_DATA_ALLOWED_ERR,
- NO_MODIFICATION_ALLOWED_ERR : NO_MODIFICATION_ALLOWED_ERR,
- NOT_FOUND_ERR : NOT_FOUND_ERR,
- NOT_SUPPORTED_ERR : NOT_SUPPORTED_ERR,
- INUSE_ATTRIBUTE_ERR : INUSE_ATTRIBUTE_ERR
- });
+ exports.toByteArray = b64ToByteArray
+ exports.fromByteArray = uint8ToBase64
+ }( false ? (this.base64js = {}) : exports))
- core.NodeList = function NodeList(element, query) {
- if (!query) {
- // Non-live NodeList
- if (Array.isArray(element)) {
- Array.prototype.push.apply(this, element);
- }
- Object.defineProperties(this, {
- _length: {value: element ? element.length : 0, writable:true}
- });
- } else {
- Object.defineProperties(this, {
- _element: {value: element},
- _query: {value: query},
- _snapshot: {writable: true},
- _length: {value: 0, writable: true},
- _version: {value: -1, writable: true}
- });
- this._update();
- }
- };
- function lengthFromProperties(arrayLike) {
- var max = -1;
- for (var i in arrayLike) {
- var asNumber = +i;
- if (!isNaN(asNumber) && asNumber > max) {
- max = asNumber;
- }
+/***/ },
+/* 9 */
+/***/ function(module, exports) {
+
+ exports.read = function (buffer, offset, isLE, mLen, nBytes) {
+ var e, m
+ var eLen = nBytes * 8 - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var nBits = -7
+ var i = isLE ? (nBytes - 1) : 0
+ var d = isLE ? -1 : 1
+ var s = buffer[offset + i]
+
+ i += d
+
+ e = s & ((1 << (-nBits)) - 1)
+ s >>= (-nBits)
+ nBits += eLen
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ m = e & ((1 << (-nBits)) - 1)
+ e >>= (-nBits)
+ nBits += mLen
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ if (e === 0) {
+ e = 1 - eBias
+ } else if (e === eMax) {
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
+ } else {
+ m = m + Math.pow(2, mLen)
+ e = e - eBias
}
- return max + 1;
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
- core.NodeList.prototype = {
- _update: function() {
- var i;
- if (!this._element) {
- this._length = lengthFromProperties(this);
+ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
+ var e, m, c
+ var eLen = nBytes * 8 - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
+ var i = isLE ? 0 : (nBytes - 1)
+ var d = isLE ? 1 : -1
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
+
+ value = Math.abs(value)
+
+ if (isNaN(value) || value === Infinity) {
+ m = isNaN(value) ? 1 : 0
+ e = eMax
+ } else {
+ e = Math.floor(Math.log(value) / Math.LN2)
+ if (value * (c = Math.pow(2, -e)) < 1) {
+ e--
+ c *= 2
+ }
+ if (e + eBias >= 1) {
+ value += rt / c
} else {
- if (this._version < this._element._version) {
- var nodes = this._snapshot = this._query();
- this._resetTo(nodes);
- this._version = this._element._version;
- }
+ value += rt * Math.pow(2, 1 - eBias)
}
- },
- _resetTo: function(array) {
- var startingLength = lengthFromProperties(this);
- for (var i = 0; i < startingLength; ++i) {
- delete this[i];
+ if (value * c >= 2) {
+ e++
+ c /= 2
}
- for (var j = 0; j < array.length; ++j) {
- this[j] = array[j];
- }
- this._length = array.length;
- },
- _toArray: function() {
- if (this._element) {
- this._update();
- return this._snapshot;
+ if (e + eBias >= eMax) {
+ m = 0
+ e = eMax
+ } else if (e + eBias >= 1) {
+ m = (value * c - 1) * Math.pow(2, mLen)
+ e = e + eBias
+ } else {
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
+ e = 0
}
-
- return Array.prototype.slice.call(this);
- },
- get length() {
- this._update();
- return this._length || 0;
- },
- set length(length) {
- return this._length;
- },
- item: function(index) {
- this._update();
- return this[index] || null;
- },
- toString: function() {
- return '[ jsdom NodeList ]: contains ' + this.length + ' items';
}
- };
- Object.defineProperty(core.NodeList.prototype, 'constructor', {
- value: core.NodeList,
- writable: true,
- configurable: true
- });
- core.DOMImplementation = function DOMImplementation(document, /* Object */ features) {
- this._ownerDocument = document;
- this._features = {};
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- if (features) {
- for (var feature in features) {
- if (features.hasOwnProperty(feature)) {
- this.addFeature(feature.toLowerCase(), features[feature]);
- }
- }
- }
- };
+ e = (e << mLen) | m
+ eLen += mLen
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- core.DOMImplementation.prototype = {
- get ownerDocument() { return this._ownerDocument },
- removeFeature : function(feature, version) {
- feature = feature.toLowerCase();
- if (this._features[feature]) {
- if (version) {
- var j = 0,
- versions = this._features[feature],
- l = versions.length;
-
- for (j; j 0) {
- return true;
- } else if (typeof versions === 'string') {
- return versions === version;
- } else if (versions.indexOf && versions.length > 0) {
- for (var i = 0; i < versions.length; i++) {
- var found = versions[i] instanceof RegExp ?
- versions[i].test(version) :
- versions[i] === version;
- if (found) { return true; }
- }
- return false;
- } else {
- return false;
- }
- }
- };
+ var isArray = Array.isArray;
+ /**
+ * toString
+ */
- var attrCopy = function(src, dest, fn) {
- if (src.attributes) {
- var attrs = src.attributes, i, l = attrs.length, attr, copied;
- for (i=0;i true
+ * isArray(arguments);
+ * // > false
+ * isArray('');
+ * // > false
+ *
+ * @param {mixed} val
+ * @return {bool}
+ */
- core.Node = function Node(ownerDocument) {
- this._childNodes = new core.NodeList();
- this._ownerDocument = ownerDocument;
- this._attributes = new AttributeList(ownerDocument, this);
- this._nodeName = null;
- this._childrenList = null;
- this._version = 0;
- this._nodeValue = null;
- this._parentNode = null;
- this._nodeName = null;
- this._memoizedQueries = {};
- this._readonly = false;
+ module.exports = isArray || function (val) {
+ return !! val && '[object Array]' == str.call(val);
};
- core.Node.ELEMENT_NODE = ELEMENT_NODE;
- core.Node.ATTRIBUTE_NODE = ATTRIBUTE_NODE;
- core.Node.TEXT_NODE = TEXT_NODE;
- core.Node.CDATA_SECTION_NODE = CDATA_SECTION_NODE;
- core.Node.ENTITY_REFERENCE_NODE = ENTITY_REFERENCE_NODE;
- core.Node.ENTITY_NODE = ENTITY_NODE;
- core.Node.PROCESSING_INSTRUCTION_NODE = PROCESSING_INSTRUCTION_NODE;
- core.Node.COMMENT_NODE = COMMENT_NODE;
- core.Node.DOCUMENT_NODE = DOCUMENT_NODE;
- core.Node.DOCUMENT_TYPE_NODE = DOCUMENT_TYPE_NODE;
- core.Node.DOCUMENT_FRAGMENT_NODE = DOCUMENT_FRAGMENT_NODE;
- core.Node.NOTATION_NODE = NOTATION_NODE;
-
- core.Node.prototype = {
- ELEMENT_NODE : ELEMENT_NODE,
- ATTRIBUTE_NODE : ATTRIBUTE_NODE,
- TEXT_NODE : TEXT_NODE,
- CDATA_SECTION_NODE : CDATA_SECTION_NODE,
- ENTITY_REFERENCE_NODE : ENTITY_REFERENCE_NODE,
- ENTITY_NODE : ENTITY_NODE,
- PROCESSING_INSTRUCTION_NODE : PROCESSING_INSTRUCTION_NODE,
- COMMENT_NODE : COMMENT_NODE,
- DOCUMENT_NODE : DOCUMENT_NODE,
- DOCUMENT_TYPE_NODE : DOCUMENT_TYPE_NODE,
- DOCUMENT_FRAGMENT_NODE : DOCUMENT_FRAGMENT_NODE,
- NOTATION_NODE : NOTATION_NODE,
-
- get children() {
- if (!this._childrenList) {
- var self = this;
- this._childrenList = new core.NodeList(this, function() {
- return Array.prototype.filter.call(self._childNodes, function(node) {
- return node.tagName;
- });
- });
- }
- return this._childrenList;
- },
- get nodeValue() {
- return this._nodeValue;
- },
- set nodeValue(value) {
- // readonly
- if (this._readonly === true) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR, 'Attempting to modify a read-only node');
- }
- this._nodeValue = value;
- },
- get parentNode() { return this._parentNode;},
-
- get nodeName() {
- var name = this._nodeName || this._tagName;
- if (this.nodeType === ELEMENT_NODE &&
- this._ownerDocument &&
- this._ownerDocument._doctype &&
- this._ownerDocument._doctype.name.toLowerCase().indexOf("html") !== -1)
- {
- return name.toUpperCase();
- }
- return name;
- },
- set nodeName(unused) { throw new core.DOMException();},
- get attributes() { return this._attributes;},
- get firstChild() {
- return this._childNodes.length > 0 ? this._childNodes[0] : null;
- },
- set firstChild(unused) { throw new core.DOMException();},
- get ownerDocument() { return this._ownerDocument;},
- get readonly() { return this._readonly;},
-
- get lastChild() {
- var len = this._childNodes.length;
- return len > 0 ? this._childNodes[len -1] : null;
- },
- set lastChild(unused) { throw new core.DOMException();},
-
- get childNodes() {
- return this._childNodes;
- },
- set childNodes(unused) { throw new core.DOMException();},
-
- _indexOf: function(/*Node*/ child) {
- if (!this._childNodes ||
- !this._childNodes.length) {
- return -1;
- }
+/***/ },
+/* 11 */
+/***/ function(module, exports) {
- var currentNode, index = 0, children = this._childNodes;
+ // shim for using process in browser
- while ((currentNode = children[index])) {
- if (currentNode == child) {
- break;
- }
- index++;
- }
+ var process = module.exports = {};
+ var queue = [];
+ var draining = false;
+ var currentQueue;
+ var queueIndex = -1;
- if (currentNode == child) {
- return index;
+ function cleanUpNextTick() {
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
}
- return -1;
- },
-
- get nextSibling() {
- // find this node's index in the parentNode, add one and call it a day
- if (!this._parentNode || !this._parentNode._indexOf) {
- return null;
+ if (queue.length) {
+ drainQueue();
}
+ }
- var index = this._parentNode._indexOf(this);
-
- if (index == -1 || index+1 >= this._parentNode._childNodes.length) {
- return null;
+ function drainQueue() {
+ if (draining) {
+ return;
}
+ var timeout = setTimeout(cleanUpNextTick);
+ draining = true;
- return this._parentNode._childNodes[index+1] || null;
- },
- set nextSibling(unused) { throw new core.DOMException();},
-
- get previousSibling() {
- if (!this._parentNode || !this._parentNode._indexOf) {
- return null;
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ while (++queueIndex < len) {
+ currentQueue[queueIndex].run();
+ }
+ queueIndex = -1;
+ len = queue.length;
}
+ currentQueue = null;
+ draining = false;
+ clearTimeout(timeout);
+ }
- var index = this._parentNode._indexOf(this);
-
- if (index == -1 || index-1 < 0) {
- return null;
+ process.nextTick = function (fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
}
-
- return this._parentNode._childNodes[index-1] || null;
- },
- set previousSibling(unused) { throw new core.DOMException();},
-
- /* returns Node */
- insertBefore : function(/* Node */ newChild, /* Node*/ refChild) {
- if (this._readonly === true) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR, 'Attempting to modify a read-only node');
+ queue.push(new Item(fun, args));
+ if (queue.length === 1 && !draining) {
+ setTimeout(drainQueue, 0);
}
+ };
- // Adopt unowned children, for weird nodes like DocumentType
- if (!newChild._ownerDocument) newChild._ownerDocument = this._ownerDocument;
+ // v8 likes predictible objects
+ function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
+ }
+ Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
+ };
+ process.title = 'browser';
+ process.browser = true;
+ process.env = {};
+ process.argv = [];
+ process.version = ''; // empty string to avoid regexp issues
+ process.versions = {};
- // TODO - if (!newChild) then?
- if (newChild._ownerDocument !== this._ownerDocument) {
- throw new core.DOMException(WRONG_DOCUMENT_ERR);
- }
+ function noop() {}
- if (newChild.nodeType && newChild.nodeType === ATTRIBUTE_NODE) {
- throw new core.DOMException(HIERARCHY_REQUEST_ERR);
- }
+ process.on = noop;
+ process.addListener = noop;
+ process.once = noop;
+ process.off = noop;
+ process.removeListener = noop;
+ process.removeAllListeners = noop;
+ process.emit = noop;
- // search for parents matching the newChild
- var current = this;
- do {
- if (current === newChild) {
- throw new core.DOMException(HIERARCHY_REQUEST_ERR);
- }
- } while((current = current._parentNode));
-
- // fragments are merged into the element
- if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
- var tmpNode, i = newChild._childNodes.length;
- while (i-- > 0) {
- tmpNode = newChild.removeChild(newChild.firstChild);
- this.insertBefore(tmpNode, refChild);
- }
- } else if (newChild === refChild) {
- return newChild;
- } else {
- // if the newChild is already in the tree elsewhere, remove it first
- if (newChild._parentNode) {
- newChild._parentNode.removeChild(newChild);
- }
+ process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+ };
- if (refChild == null) {
- var refChildIndex = this._childNodes.length;
- } else {
- var refChildIndex = this._indexOf(refChild);
- if (refChildIndex == -1) {
- throw new core.DOMException(NOT_FOUND_ERR);
- }
- }
+ // TODO(shtylman)
+ process.cwd = function () { return '/' };
+ process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+ };
+ process.umask = function() { return 0; };
- Array.prototype.splice.call(this._childNodes, refChildIndex, 0, newChild);
- newChild._parentNode = this;
- if (this._attached && newChild._attach) {
- newChild._attach();
- }
+/***/ },
+/* 12 */
+/***/ function(module, exports) {
- this._modified();
- }
+ /* (ignored) */
- return newChild;
- }, // raises(DOMException);
+/***/ },
+/* 13 */
+/***/ function(module, exports) {
- _modified: function() {
- this._version++;
- if (this._ownerDocument) {
- this._ownerDocument._version++;
- }
+ /* (ignored) */
- if (this._childrenList) {
- this._childrenList._update();
- }
- this._clearMemoizedQueries()
- },
+/***/ },
+/* 14 */
+/***/ function(module, exports) {
- _clearMemoizedQueries: function() {
- this._memoizedQueries = {};
- if (this._parentNode && this._parentNode !== this) {
- this._parentNode._clearMemoizedQueries();
- }
- },
+ /* (ignored) */
- _attrModified: function(name, value, oldValue) {
- if (name == 'id' && this._attached) {
- var doc = this._ownerDocument;
- detachId(oldValue,this,doc);
- attachId(value,this,doc);
- }
+/***/ },
+/* 15 */
+/***/ function(module, exports, __webpack_require__) {
+
+ // Copyright Joyent, Inc. and other Node contributors.
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining a
+ // copy of this software and associated documentation files (the
+ // "Software"), to deal in the Software without restriction, including
+ // without limitation the rights to use, copy, modify, merge, publish,
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
+ // persons to whom the Software is furnished to do so, subject to the
+ // following conditions:
+ //
+ // The above copyright notice and this permission notice shall be included
+ // in all copies or substantial portions of the Software.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // Check for inline event handlers.
- // We can't set these like other attributes then look it up in
- // dispatchEvent() because that would create 2 'traditional' event handlers
- // in the case where there's an inline event handler attribute, plus one
- // set using element.on* in a script.
+ var punycode = __webpack_require__(16);
+
+ exports.parse = urlParse;
+ exports.resolve = urlResolve;
+ exports.resolveObject = urlResolveObject;
+ exports.format = urlFormat;
+
+ exports.Url = Url;
+
+ function Url() {
+ this.protocol = null;
+ this.slashes = null;
+ this.auth = null;
+ this.host = null;
+ this.port = null;
+ this.hostname = null;
+ this.hash = null;
+ this.search = null;
+ this.query = null;
+ this.pathname = null;
+ this.path = null;
+ this.href = null;
+ }
+
+ // Reference: RFC 3986, RFC 1808, RFC 2396
+
+ // define these here so at least they only have to be
+ // compiled once on the first module load.
+ var protocolPattern = /^([a-z0-9.+-]+:)/i,
+ portPattern = /:[0-9]*$/,
+
+ // RFC 2396: characters reserved for delimiting URLs.
+ // We actually just auto-escape these.
+ delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
+
+ // RFC 2396: characters not allowed for various reasons.
+ unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
+
+ // Allowed by RFCs, but cause of XSS attacks. Always escape these.
+ autoEscape = ['\''].concat(unwise),
+ // Characters that are never ever allowed in a hostname.
+ // Note that any invalid chars are also handled, but these
+ // are the ones that are *expected* to be seen, so we fast-path
+ // them.
+ nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
+ hostEndingChars = ['/', '?', '#'],
+ hostnameMaxLen = 255,
+ hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
+ hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
+ // protocols that can allow "unsafe" and "unwise" chars.
+ unsafeProtocol = {
+ 'javascript': true,
+ 'javascript:': true
+ },
+ // protocols that never have a hostname.
+ hostlessProtocol = {
+ 'javascript': true,
+ 'javascript:': true
+ },
+ // protocols that always contain a // bit.
+ slashedProtocol = {
+ 'http': true,
+ 'https': true,
+ 'ftp': true,
+ 'gopher': true,
+ 'file': true,
+ 'http:': true,
+ 'https:': true,
+ 'ftp:': true,
+ 'gopher:': true,
+ 'file:': true
+ },
+ querystring = __webpack_require__(18);
+
+ function urlParse(url, parseQueryString, slashesDenoteHost) {
+ if (url && isObject(url) && url instanceof Url) return url;
+
+ var u = new Url;
+ u.parse(url, parseQueryString, slashesDenoteHost);
+ return u;
+ }
+
+ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
+ if (!isString(url)) {
+ throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
+ }
+
+ var rest = url;
+
+ // trim before proceeding.
+ // This is to support parse stuff like " http://foo.com \n"
+ rest = rest.trim();
+
+ var proto = protocolPattern.exec(rest);
+ if (proto) {
+ proto = proto[0];
+ var lowerProto = proto.toLowerCase();
+ this.protocol = lowerProto;
+ rest = rest.substr(proto.length);
+ }
+
+ // figure out if it's got a host
+ // user@server is *always* interpreted as a hostname, and url
+ // resolution will treat //foo/bar as host=foo,path=bar because that's
+ // how the browser resolves relative URLs.
+ if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
+ var slashes = rest.substr(0, 2) === '//';
+ if (slashes && !(proto && hostlessProtocol[proto])) {
+ rest = rest.substr(2);
+ this.slashes = true;
+ }
+ }
+
+ if (!hostlessProtocol[proto] &&
+ (slashes || (proto && !slashedProtocol[proto]))) {
+
+ // there's a hostname.
+ // the first instance of /, ?, ;, or # ends the host.
//
- // @see http://www.w3.org/TR/2011/WD-html5-20110405/webappapis.html#event-handler-content-attributes
- if ((name.length > 2) && (name[0] == 'o') && (name[1] == 'n')) {
- if (value) {
- var self = this;
- // Check whether we're the window. This can happen because inline
- // handlers on the body are proxied to the window.
- var w = (typeof self.run !== 'undefined') ? self : self._ownerDocument.parentWindow;
- self[name] = function (event) {
- // The handler code probably refers to functions declared in the
- // window context, so we need to call run().
-
- // Use awesome hacks to get the correct `this` context for the
- // inline event handler. This would only be necessary if we're an
- // element, but for the sake of simplicity we also do it on window.
-
- // Also set event variable and support `return false`.
- w.__tempContextForInlineEventHandler = self;
- w.__tempEvent = event;
- w.run("if ((function (event) {" + value + "}).call(" +
- "window.__tempContextForInlineEventHandler, window.__tempEvent) === false) {" +
- "window.__tempEvent.preventDefault()}");
- delete w.__tempContextForInlineEventHandler;
- delete w.__tempEvent;
- };
- } else {
- this[name] = null;
+ // If there is an @ in the hostname, then non-host chars *are* allowed
+ // to the left of the last @ sign, unless some host-ending character
+ // comes *before* the @-sign.
+ // URLs are obnoxious.
+ //
+ // ex:
+ // http://a@b@c/ => user:a@b host:c
+ // http://a@b?@c => user:a host:c path:/?@c
+
+ // v0.12 TODO(isaacs): This is not quite how Chrome does things.
+ // Review our test case against browsers more comprehensively.
+
+ // find the first instance of any hostEndingChars
+ var hostEnd = -1;
+ for (var i = 0; i < hostEndingChars.length; i++) {
+ var hec = rest.indexOf(hostEndingChars[i]);
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
+ hostEnd = hec;
+ }
+
+ // at this point, either we have an explicit point where the
+ // auth portion cannot go past, or the last @ char is the decider.
+ var auth, atSign;
+ if (hostEnd === -1) {
+ // atSign can be anywhere.
+ atSign = rest.lastIndexOf('@');
+ } else {
+ // atSign must be in auth portion.
+ // http://a@b/c@d => host:b auth:a path:/c@d
+ atSign = rest.lastIndexOf('@', hostEnd);
+ }
+
+ // Now we have a portion which is definitely the auth.
+ // Pull that off.
+ if (atSign !== -1) {
+ auth = rest.slice(0, atSign);
+ rest = rest.slice(atSign + 1);
+ this.auth = decodeURIComponent(auth);
+ }
+
+ // the host is the remaining to the left of the first non-host char
+ hostEnd = -1;
+ for (var i = 0; i < nonHostChars.length; i++) {
+ var hec = rest.indexOf(nonHostChars[i]);
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
+ hostEnd = hec;
+ }
+ // if we still have not hit it, then the entire thing is a host.
+ if (hostEnd === -1)
+ hostEnd = rest.length;
+
+ this.host = rest.slice(0, hostEnd);
+ rest = rest.slice(hostEnd);
+
+ // pull out port.
+ this.parseHost();
+
+ // we've indicated that there is a hostname,
+ // so even if it's empty, it has to be present.
+ this.hostname = this.hostname || '';
+
+ // if hostname begins with [ and ends with ]
+ // assume that it's an IPv6 address.
+ var ipv6Hostname = this.hostname[0] === '[' &&
+ this.hostname[this.hostname.length - 1] === ']';
+
+ // validate a little.
+ if (!ipv6Hostname) {
+ var hostparts = this.hostname.split(/\./);
+ for (var i = 0, l = hostparts.length; i < l; i++) {
+ var part = hostparts[i];
+ if (!part) continue;
+ if (!part.match(hostnamePartPattern)) {
+ var newpart = '';
+ for (var j = 0, k = part.length; j < k; j++) {
+ if (part.charCodeAt(j) > 127) {
+ // we replace non-ASCII char with a temporary placeholder
+ // we need this to make sure size of hostname is not
+ // broken by replacing non-ASCII by nothing
+ newpart += 'x';
+ } else {
+ newpart += part[j];
+ }
+ }
+ // we test again with ASCII char only
+ if (!newpart.match(hostnamePartPattern)) {
+ var validParts = hostparts.slice(0, i);
+ var notHost = hostparts.slice(i + 1);
+ var bit = part.match(hostnamePartStart);
+ if (bit) {
+ validParts.push(bit[1]);
+ notHost.unshift(bit[2]);
+ }
+ if (notHost.length) {
+ rest = '/' + notHost.join('.') + rest;
+ }
+ this.hostname = validParts.join('.');
+ break;
+ }
}
- }
- },
-
- /* returns Node */
- replaceChild : function(/* Node */ newChild, /* Node */ oldChild){
- this.insertBefore(newChild, oldChild);
- return this.removeChild(oldChild);
- }, //raises(DOMException);
-
- /* returns void */
- _attach : function() {
- this._attached = true;
- if (this.id) {
- attachId(this.id,this,this._ownerDocument);
- }
- for (var i=0,len=this._childNodes.length;i 0;
- },
-
- /* returns Node */
- cloneNode : function(/* bool */ deep, fn) {
-
- var object = null;
- switch (this.nodeType) {
-
- case this.ELEMENT_NODE:
- object = attrCopy(this,this._ownerDocument.createElement(this.tagName), fn);
- break;
-
- case this.TEXT_NODE:
- object = attrCopy(this,this._ownerDocument.createTextNode(this.tagName));
- object.nodeValue = this.nodeValue;
- break;
- case this.CDATA_SECTION_NODE:
- object = this._ownerDocument.createCDATASection(this.tagName);
- object.nodeValue = this.nodeValue;
- break;
- case this.ENTITY_REFERENCE_NODE:
- var name = (this._entity) ? this._entity.name : this._entityName,
- ref = this._ownerDocument.createEntityReference(name);
-
- object = attrCopy(this, ref);
- object.nodeValue = this.nodeValue;
- break;
- case this.ATTRIBUTE_NODE:
- object = this._ownerDocument.createAttribute(this.name);
- break;
- case this.ENTITY_NODE:
- var entity = this._ownerDocument.createEntityNode(this.name);
- object = attrCopy(this, entity);
- object.nodeValue = this.nodeValue;
- object._publicId = this._publicId;
- object._systemId = this._systemId;
- object._notationName = this.notationName;
- break;
- case this.PROCESSING_INSTRUCTION_NODE:
- var pi = this._ownerDocument.createProcessingInstruction(this._target,
- this._data);
- object = attrCopy(this, pi);
- object.nodeValue = this.nodeValue;
- break;
- case this.COMMENT_NODE:
- object = this._ownerDocument.createComment(this.tagName);
- object.nodeValue = this.nodeValue;
- break;
- case this.DOCUMENT_NODE:
- object = attrCopy(this, new core.Document());
- // TODO: clone the doctype/entities/notations/etc?
- break;
- case this.DOCUMENT_TYPE_NODE:
- object = attrCopy(this, new core.DocumentType());
- object.nodeValue = this.nodeValue;
- break;
- case this.DOCUMENT_FRAGMENT_NODE:
- object = this._ownerDocument.createDocumentFragment();
- break;
- case this.NOTATION_NODE:
- object = this._ownerDocument.createNotationNode(this._name,
- this._publicId,
- this._systemId);
- object = attrCopy(this,object);
- object.nodeValue = this.nodeValue;
- break;
- default:
- throw new core.DOMException(NOT_FOUND_ERR);
- break;
- }
- if (typeof fn === "function") {
- fn(this, object);
+ if (this.hostname.length > hostnameMaxLen) {
+ this.hostname = '';
+ } else {
+ // hostnames are always lower case.
+ this.hostname = this.hostname.toLowerCase();
}
- if (deep || this.nodeType === ATTRIBUTE_NODE) {
- var clone = null;
- for (var i=0,len=this._childNodes.length;i0) {
- prevChild = this._childNodes[i-1];
-
- if (child.nodeType === TEXT_NODE &&
- prevChild.nodeType === TEXT_NODE)
- {
-
- // remove the child and decrement i
- prevChild.appendData(child.nodeValue);
+ // now rest is set to the post-host stuff.
+ // chop off any delim chars.
+ if (!unsafeProtocol[lowerProto]) {
- this.removeChild(child);
- i--;
- }
- }
- }
- },
- toString: function() {
- var id = '';
- if (this.id) {
- id = '#' + this.id;
- }
- if (this.className) {
- var classes = this.className.split(/\s+/);
- for (var i = 0, len = classes.length; i < len; i++) {
- id += '.' + classes[i];
- }
- }
- return '[ ' + this.tagName + id + ' ]';
- },
- raise: function(type, message, data) {
- var text = type + ": " + message;
-
- if (data) {
- if (data.exception) {
- text = data.exception.stack;
- } else {
- text += ' - More:\n' + data;
+ // First, make 100% sure that any "autoEscape" chars get
+ // escaped, even if encodeURIComponent doesn't think they
+ // need to be.
+ for (var i = 0, l = autoEscape.length; i < l; i++) {
+ var ae = autoEscape[i];
+ var esc = encodeURIComponent(ae);
+ if (esc === ae) {
+ esc = escape(ae);
}
+ rest = rest.split(ae).join(esc);
}
+ }
- if (type === "error") {
- if (!this.errors) {
- this.errors = [];
- }
- // TODO: consider using actual `Error` objects or `DOMException`s even..
- var err = {
- type : type,
- message : message || "No message",
- data : data || null
- };
-
- this.errors.push(err);
- if (this._ownerDocument &&
- this._ownerDocument.raise &&
- this !== this._ownerDocument)
- {
- this._ownerDocument.raise(type, message, data);
- }
+ // chop off from the tail first.
+ var hash = rest.indexOf('#');
+ if (hash !== -1) {
+ // got a fragment string.
+ this.hash = rest.substr(hash);
+ rest = rest.slice(0, hash);
+ }
+ var qm = rest.indexOf('?');
+ if (qm !== -1) {
+ this.search = rest.substr(qm);
+ this.query = rest.substr(qm + 1);
+ if (parseQueryString) {
+ this.query = querystring.parse(this.query);
}
+ rest = rest.slice(0, qm);
+ } else if (parseQueryString) {
+ // no query string, but parseQueryString still requested
+ this.search = '';
+ this.query = {};
+ }
+ if (rest) this.pathname = rest;
+ if (slashedProtocol[lowerProto] &&
+ this.hostname && !this.pathname) {
+ this.pathname = '/';
}
- };
+ //to support http.request
+ if (this.pathname || this.search) {
+ var p = this.pathname || '';
+ var s = this.search || '';
+ this.path = p + s;
+ }
- core.NamedNodeMap = function NamedNodeMap(document) {
- this._nodes = Object.create(null);
- this._nsStore = {};
- this.length = 0;
- this._ownerDocument = document;
- this._readonly = false;
+ // finally, reconstruct the href based on what has been validated.
+ this.href = this.format();
+ return this;
};
- core.NamedNodeMap.prototype = {
- get readonly() { return this._readonly;},
- get ownerDocument() { this._ownerDocument;},
- exists : function(name) {
- return (this._nodes[name] || this._nodes[name] === null) ? true : false;
- },
-
- /* returns Node */
- getNamedItem: function(/* string */ name) {
- return this._nodes[name] || null;
- },
+ // format a parsed object into a url string
+ function urlFormat(obj) {
+ // ensure it's an object, and not a string url.
+ // If it's an obj, this is a no-op.
+ // this way, you can call url_format() on strings
+ // to clean up potentially wonky urls.
+ if (isString(obj)) obj = urlParse(obj);
+ if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
+ return obj.format();
+ }
- /* returns Node */
- setNamedItem: function(/* Node */ arg) {
+ Url.prototype.format = function() {
+ var auth = this.auth || '';
+ if (auth) {
+ auth = encodeURIComponent(auth);
+ auth = auth.replace(/%3A/i, ':');
+ auth += '@';
+ }
- // readonly
- if (this._readonly === true) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
- }
+ var protocol = this.protocol || '',
+ pathname = this.pathname || '',
+ hash = this.hash || '',
+ host = false,
+ query = '';
- // arg is from a different document
- if (arg && arg._ownerDocument !== this._ownerDocument) {
- throw new core.DOMException(WRONG_DOCUMENT_ERR);
+ if (this.host) {
+ host = auth + this.host;
+ } else if (this.hostname) {
+ host = auth + (this.hostname.indexOf(':') === -1 ?
+ this.hostname :
+ '[' + this.hostname + ']');
+ if (this.port) {
+ host += ':' + this.port;
}
+ }
- // if this argument is already in use..
- if (arg && arg._ownerElement) {
- throw new core.DOMException(INUSE_ATTRIBUTE_ERR);
- }
+ if (this.query &&
+ isObject(this.query) &&
+ Object.keys(this.query).length) {
+ query = querystring.stringify(this.query);
+ }
- var name = arg.name || arg.tagName;
- var ret = this._nodes[name];
- if (!ret) {
- this.length++;
- ret = null;
- }
- arg._specified = true;
- this._nodes[name] = arg;
+ var search = this.search || (query && ('?' + query)) || '';
- // Avoid overwriting prototype methods etc.:
- if (this.hasOwnProperty(name) || !(name in this)) {
- this[name] = arg;
- }
- return ret;
- }, // raises: function(DOMException) {},
+ if (protocol && protocol.substr(-1) !== ':') protocol += ':';
- /* returns Node */
- removeNamedItem: function(/* string */ name) {
+ // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
+ // unless they had them to begin with.
+ if (this.slashes ||
+ (!protocol || slashedProtocol[protocol]) && host !== false) {
+ host = '//' + (host || '');
+ if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
+ } else if (!host) {
+ host = '';
+ }
- // readonly
- if (this._readonly === true) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
- }
+ if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
+ if (search && search.charAt(0) !== '?') search = '?' + search;
- if (!this._nodes[name]) {
- throw new core.DOMException(NOT_FOUND_ERR);
- }
+ pathname = pathname.replace(/[?#]/g, function(match) {
+ return encodeURIComponent(match);
+ });
+ search = search.replace('#', '%23');
- var prev = this._nodes[name] || null;
- delete this._nodes[name];
- delete this[name];
+ return protocol + host + pathname + search + hash;
+ };
- this.length--;
- return prev;
- }, // raises: function(DOMException) {},
+ function urlResolve(source, relative) {
+ return urlParse(source, false, true).resolve(relative);
+ }
- /* returns Node */
- item: function(/* int */ index) {
- var current = 0;
- for (var member in this._nodes) {
- if (current === index && this._nodes[member]) {
- return this._nodes[member];
- }
- current++;
- }
- return null;
- }
+ Url.prototype.resolve = function(relative) {
+ return this.resolveObject(urlParse(relative, false, true)).format();
};
- //
- // For historical reasons, AttributeList objects must allow accessing
- // attributes as if the object were an associative array. For
- // instance, if `attributes` is an AttributeList object then
- // `attributes.x` should evaluate to the attribute named `x` (which is
- // not in any namespace). The AttributeList class uses the dollar
- // symbol ($) to reduce the possibility of a clash between its field
- // names and possible attribute names. For instance, if the method
- // currently named `$set` were instead named `set` then it would not
- // be possible to access an attribute named `set` through
- // `attributes.set`. The dollar symbol is not valid in attribute names
- // so `$set` cannot clash.
- //
- // Some fields do not get the $ because:
- //
- // * They are part of the API (e.g. `setNamedItem`, `length`), so they
- // must be visible under a specific name.
- //
- // * Jsdom's code which traverses the DOM tree expects regularly named
- // fields (e.g. `_parentNode`).
- //
- function AttributeList(document, parentNode) {
- this._ownerDocument = document;
- this._parentNode = parentNode;
- this._readonly = false;
- this._$ns_to_attrs = Object.create(null);
- this._$name_to_attrs = Object.create(null);
- this.length = 0;
+ function urlResolveObject(source, relative) {
+ if (!source) return relative;
+ return urlParse(source, false, true).resolveObject(relative);
}
- AttributeList.prototype = {
- _$reserved: [], // Initialized later
+ Url.prototype.resolveObject = function(relative) {
+ if (isString(relative)) {
+ var rel = new Url();
+ rel.parse(relative, false, true);
+ relative = rel;
+ }
+ var result = new Url();
+ Object.keys(this).forEach(function(k) {
+ result[k] = this[k];
+ }, this);
- //
- // Code internal to jsdom and which manipulates an AttributeList
- // object should use the following methods rather than the methods
- // that provide the NamedNodeMap interface.
- //
+ // hash is always overridden, no matter what.
+ // even href="" will remove it.
+ result.hash = relative.hash;
- // This method *ignores* namespaces. This is *not* the same thing as
- // requesting an attribute with a null namespace.
- $getNoNS: function (name) {
- var attrs = this._$name_to_attrs[name];
- if (!attrs) {
- return null;
- }
+ // if the relative url is empty, then there's nothing left to do here.
+ if (relative.href === '') {
+ result.href = result.format();
+ return result;
+ }
- return attrs[0] || null;
- },
+ // hrefs like //foo/bar always cut to the protocol.
+ if (relative.slashes && !relative.protocol) {
+ // take everything except the protocol from relative
+ Object.keys(relative).forEach(function(k) {
+ if (k !== 'protocol')
+ result[k] = relative[k];
+ });
- $getNode: function (namespace, localName) {
- var attrs = this._$ns_to_attrs[namespace];
- if (!attrs) {
- return null;
+ //urlParse appends trailing / to urls like http://www.example.com
+ if (slashedProtocol[result.protocol] &&
+ result.hostname && !result.pathname) {
+ result.path = result.pathname = '/';
}
- var ret = attrs[localName];
- if (!ret) {
- return null;
- }
+ result.href = result.format();
+ return result;
+ }
- return ret;
- },
-
- // This method *ignores* namespaces. This is *not* the same thing as
- // requesting an attribute with a null namespace.
- $setNoNS: function (name, value) {
- var attr = this.$getNoNS(name);
- if (!attr) {
- this.$set(name, value);
- return;
+ if (relative.protocol && relative.protocol !== result.protocol) {
+ // if it's a known url protocol, then changing
+ // the protocol does weird things
+ // first, if it's not file:, then we MUST have a host,
+ // and if there was a path
+ // to begin with, then we MUST have a path.
+ // if it is file:, then the host is dropped,
+ // because that's known to be hostless.
+ // anything else is assumed to be absolute.
+ if (!slashedProtocol[relative.protocol]) {
+ Object.keys(relative).forEach(function(k) {
+ result[k] = relative[k];
+ });
+ result.href = result.format();
+ return result;
}
- var prev_val = attr.value;
- attr.value = value;
- attr._specified = true;
+ result.protocol = relative.protocol;
+ if (!relative.host && !hostlessProtocol[relative.protocol]) {
+ var relPath = (relative.pathname || '').split('/');
+ while (relPath.length && !(relative.host = relPath.shift()));
+ if (!relative.host) relative.host = '';
+ if (!relative.hostname) relative.hostname = '';
+ if (relPath[0] !== '') relPath.unshift('');
+ if (relPath.length < 2) relPath.unshift('');
+ result.pathname = relPath.join('/');
+ } else {
+ result.pathname = relative.pathname;
+ }
+ result.search = relative.search;
+ result.query = relative.query;
+ result.host = relative.host || '';
+ result.auth = relative.auth;
+ result.hostname = relative.hostname || relative.host;
+ result.port = relative.port;
+ // to support http.request
+ if (result.pathname || result.search) {
+ var p = result.pathname || '';
+ var s = result.search || '';
+ result.path = p + s;
+ }
+ result.slashes = result.slashes || relative.slashes;
+ result.href = result.format();
+ return result;
+ }
- this._parentNode._attrModified(attr.name, attr.value, prev_val);
- this._parentNode._modified();
- },
+ var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
+ isRelAbs = (
+ relative.host ||
+ relative.pathname && relative.pathname.charAt(0) === '/'
+ ),
+ mustEndAbs = (isRelAbs || isSourceAbs ||
+ (result.host && relative.pathname)),
+ removeAllDots = mustEndAbs,
+ srcPath = result.pathname && result.pathname.split('/') || [],
+ relPath = relative.pathname && relative.pathname.split('/') || [],
+ psychotic = result.protocol && !slashedProtocol[result.protocol];
+
+ // if the url is a non-slashed url, then relative
+ // links like ../.. should be able
+ // to crawl up to the hostname, as well. This is strange.
+ // result.protocol has already been set by now.
+ // Later on, put the first path part into the host field.
+ if (psychotic) {
+ result.hostname = '';
+ result.port = null;
+ if (result.host) {
+ if (srcPath[0] === '') srcPath[0] = result.host;
+ else srcPath.unshift(result.host);
+ }
+ result.host = '';
+ if (relative.protocol) {
+ relative.hostname = null;
+ relative.port = null;
+ if (relative.host) {
+ if (relPath[0] === '') relPath[0] = relative.host;
+ else relPath.unshift(relative.host);
+ }
+ relative.host = null;
+ }
+ mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
+ }
+
+ if (isRelAbs) {
+ // it's absolute.
+ result.host = (relative.host || relative.host === '') ?
+ relative.host : result.host;
+ result.hostname = (relative.hostname || relative.hostname === '') ?
+ relative.hostname : result.hostname;
+ result.search = relative.search;
+ result.query = relative.query;
+ srcPath = relPath;
+ // fall through to the dot-handling below.
+ } else if (relPath.length) {
+ // it's relative
+ // throw away the existing file, and take the new path instead.
+ if (!srcPath) srcPath = [];
+ srcPath.pop();
+ srcPath = srcPath.concat(relPath);
+ result.search = relative.search;
+ result.query = relative.query;
+ } else if (!isNullOrUndefined(relative.search)) {
+ // just pull out the search.
+ // like href='?foo'.
+ // Put this after the other two cases because it simplifies the booleans
+ if (psychotic) {
+ result.hostname = result.host = srcPath.shift();
+ //occationaly the auth can get stuck only in host
+ //this especialy happens in cases like
+ //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
+ var authInHost = result.host && result.host.indexOf('@') > 0 ?
+ result.host.split('@') : false;
+ if (authInHost) {
+ result.auth = authInHost.shift();
+ result.host = result.hostname = authInHost.shift();
+ }
+ }
+ result.search = relative.search;
+ result.query = relative.query;
+ //to support http.request
+ if (!isNull(result.pathname) || !isNull(result.search)) {
+ result.path = (result.pathname ? result.pathname : '') +
+ (result.search ? result.search : '');
+ }
+ result.href = result.format();
+ return result;
+ }
- $set: function (localName, value, name, prefix, namespace) {
- if (this._readonly) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
+ if (!srcPath.length) {
+ // no path at all. easy.
+ // we've already handled the other stuff above.
+ result.pathname = null;
+ //to support http.request
+ if (result.search) {
+ result.path = '/' + result.search;
+ } else {
+ result.path = null;
}
+ result.href = result.format();
+ return result;
+ }
- if (name === undefined) {
- name = localName;
- }
+ // if a url ENDs in . or .., then it must get a trailing slash.
+ // however, if it ends in anything else non-slashy,
+ // then it must NOT get a trailing slash.
+ var last = srcPath.slice(-1)[0];
+ var hasTrailingSlash = (
+ (result.host || relative.host) && (last === '.' || last === '..') ||
+ last === '');
- if (prefix === undefined) {
- prefix = null;
+ // strip single dots, resolve double dots to parent dir
+ // if the path tries to go above the root, `up` ends up > 0
+ var up = 0;
+ for (var i = srcPath.length; i >= 0; i--) {
+ last = srcPath[i];
+ if (last == '.') {
+ srcPath.splice(i, 1);
+ } else if (last === '..') {
+ srcPath.splice(i, 1);
+ up++;
+ } else if (up) {
+ srcPath.splice(i, 1);
+ up--;
}
+ }
- if (namespace === undefined) {
- namespace = null;
+ // if the path is allowed to go above the root, restore leading ..s
+ if (!mustEndAbs && !removeAllDots) {
+ for (; up--; up) {
+ srcPath.unshift('..');
}
+ }
- var prev_attr = this.$getNode(namespace, localName);
- var attr;
+ if (mustEndAbs && srcPath[0] !== '' &&
+ (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
+ srcPath.unshift('');
+ }
- var prev_val = null;
- if (prev_attr) {
- prev_val = prev_attr.value;
- prev_attr._prefix = prefix;
- prev_attr.value = value;
- attr = prev_attr;
- attr._specified = true;
+ if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
+ srcPath.push('');
+ }
- this._parentNode._attrModified(attr.name, attr.value, prev_val);
- this._parentNode._modified();
- }
- else {
- attr = this._ownerDocument.createAttribute(name);
- attr._ownerElement = this._parentNode;
- attr.value = value;
- attr._namespaceURI = namespace;
- attr._prefix = prefix;
- attr._localName = localName;
- attr._parentNode = this._parentNode;
- attr._created = true;
- this.$setNode(attr);
- // $setNode calls the parent node methods.
- }
- },
+ var isAbsolute = srcPath[0] === '' ||
+ (srcPath[0] && srcPath[0].charAt(0) === '/');
- $setNode: function (attr) {
- if (this._readonly) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
+ // put the host back
+ if (psychotic) {
+ result.hostname = result.host = isAbsolute ? '' :
+ srcPath.length ? srcPath.shift() : '';
+ //occationaly the auth can get stuck only in host
+ //this especialy happens in cases like
+ //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
+ var authInHost = result.host && result.host.indexOf('@') > 0 ?
+ result.host.split('@') : false;
+ if (authInHost) {
+ result.auth = authInHost.shift();
+ result.host = result.hostname = authInHost.shift();
}
+ }
- if (attr.nodeType !== ATTRIBUTE_NODE) {
- throw new core.DOMException(HIERARCHY_REQUEST_ERR);
- }
+ mustEndAbs = mustEndAbs || (result.host && srcPath.length);
- if (attr._ownerDocument !== this._ownerDocument) {
- throw new core.DOMException(WRONG_DOCUMENT_ERR);
- }
+ if (mustEndAbs && !isAbsolute) {
+ srcPath.unshift('');
+ }
- if (attr._parentNode && attr._parentNode !== this._parentNode) {
- throw new core.DOMException(INUSE_ATTRIBUTE_ERR);
- }
+ if (!srcPath.length) {
+ result.pathname = null;
+ result.path = null;
+ } else {
+ result.pathname = srcPath.join('/');
+ }
- var localName = attr._localName;
- var name = attr.name;
- var prefix = attr._prefix;
- var namespace = attr._namespaceURI;
+ //to support request.http
+ if (!isNull(result.pathname) || !isNull(result.search)) {
+ result.path = (result.pathname ? result.pathname : '') +
+ (result.search ? result.search : '');
+ }
+ result.auth = relative.auth || result.auth;
+ result.slashes = result.slashes || relative.slashes;
+ result.href = result.format();
+ return result;
+ };
- if (name === undefined) {
- name = localName;
+ Url.prototype.parseHost = function() {
+ var host = this.host;
+ var port = portPattern.exec(host);
+ if (port) {
+ port = port[0];
+ if (port !== ':') {
+ this.port = port.substr(1);
}
+ host = host.substr(0, host.length - port.length);
+ }
+ if (host) this.hostname = host;
+ };
- if (prefix === undefined) {
- prefix = null;
- }
+ function isString(arg) {
+ return typeof arg === "string";
+ }
- if (namespace === undefined) {
- namespace = null;
- }
+ function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+ }
- var prev_attr = this.$getNode(namespace, localName);
+ function isNull(arg) {
+ return arg === null;
+ }
+ function isNullOrUndefined(arg) {
+ return arg == null;
+ }
- var prev_val = null;
- if (prev_attr) {
- prev_val = prev_attr.value;
- // Remove the old attribute
- this._$onlyRemoveNode(prev_attr);
- }
- attr._parentNode = this._parentNode;
- attr._ownerElement = this._parentNode;
- attr._specified = true;
+/***/ },
+/* 16 */
+/***/ function(module, exports, __webpack_require__) {
- var attrs = this._$ns_to_attrs[namespace];
- if (!attrs) {
- attrs = this._$ns_to_attrs[namespace] = Object.create(null);
- }
- attrs[localName] = attr;
+ var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/punycode v1.3.2 by @mathias */
+ ;(function(root) {
- attrs = this._$name_to_attrs[name];
- if (!attrs) {
- attrs = this._$name_to_attrs[name] = [attr];
- }
- else {
- attrs.push(attr);
- }
+ /** Detect free variables */
+ var freeExports = typeof exports == 'object' && exports &&
+ !exports.nodeType && exports;
+ var freeModule = typeof module == 'object' && module &&
+ !module.nodeType && module;
+ var freeGlobal = typeof global == 'object' && global;
+ if (
+ freeGlobal.global === freeGlobal ||
+ freeGlobal.window === freeGlobal ||
+ freeGlobal.self === freeGlobal
+ ) {
+ root = freeGlobal;
+ }
- // Only attributes in the null namespace can be set this way.
- if (namespace === null) {
- // Make the node a field on this object but ONLY if it does not
- // clash with the reserved names.
- if (this._$reserved.indexOf(name) === -1) {
- this[name] = attr;
- }
- }
+ /**
+ * The `punycode` object.
+ * @name punycode
+ * @type Object
+ */
+ var punycode,
- this[this.length] = attr;
- this.length++;
+ /** Highest positive signed 32-bit float value */
+ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
- this._parentNode._attrModified(attr.name, attr.value, prev_val);
- this._parentNode._modified();
+ /** Bootstring parameters */
+ base = 36,
+ tMin = 1,
+ tMax = 26,
+ skew = 38,
+ damp = 700,
+ initialBias = 72,
+ initialN = 128, // 0x80
+ delimiter = '-', // '\x2D'
- return prev_attr;
- },
+ /** Regular expressions */
+ regexPunycode = /^xn--/,
+ regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
+ regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
- // This method *ignores* namespaces. This is *not* the same thing as
- // requesting an attribute with a null namespace.
- $removeNoNS: function (name) {
- var attr = this.$getNoNS(name);
- return attr ? this.$removeNode(attr) : null;
- },
+ /** Error messages */
+ errors = {
+ 'overflow': 'Overflow: input needs wider integers to process',
+ 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
+ 'invalid-input': 'Invalid input'
+ },
- $remove: function (namespace, localName) {
- var attr = this.$getNode(namespace, localName);
- return attr ? this.$removeNode(attr) : null;
- },
+ /** Convenience shortcuts */
+ baseMinusTMin = base - tMin,
+ floor = Math.floor,
+ stringFromCharCode = String.fromCharCode,
- /* Only removes the node, and does not add a default value. */
- _$onlyRemoveNode: function (attr) {
- var namespace = attr._namespaceURI;
- var localName = attr._localName;
+ /** Temporary variable */
+ key;
- var attrs = this._$ns_to_attrs[namespace];
- if (!attrs) {
- return null;
- }
+ /*--------------------------------------------------------------------------*/
- var found_attr = attrs[localName];
- if (found_attr !== attr) {
- return null;
- }
+ /**
+ * A generic error utility function.
+ * @private
+ * @param {String} type The error type.
+ * @returns {Error} Throws a `RangeError` with the applicable error message.
+ */
+ function error(type) {
+ throw RangeError(errors[type]);
+ }
- if (this._readonly) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
- }
+ /**
+ * A generic `Array#map` utility function.
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} callback The function that gets called for every array
+ * item.
+ * @returns {Array} A new array of values returned by the callback function.
+ */
+ function map(array, fn) {
+ var length = array.length;
+ var result = [];
+ while (length--) {
+ result[length] = fn(array[length]);
+ }
+ return result;
+ }
- attr._ownerElement = null;
- attr._parentNode = null;
- delete attrs[localName];
+ /**
+ * A simple `Array#map`-like wrapper to work with domain name strings or email
+ * addresses.
+ * @private
+ * @param {String} domain The domain name or email address.
+ * @param {Function} callback The function that gets called for every
+ * character.
+ * @returns {Array} A new string of characters returned by the callback
+ * function.
+ */
+ function mapDomain(string, fn) {
+ var parts = string.split('@');
+ var result = '';
+ if (parts.length > 1) {
+ // In email addresses, only the domain name should be punycoded. Leave
+ // the local part (i.e. everything up to `@`) intact.
+ result = parts[0] + '@';
+ string = parts[1];
+ }
+ // Avoid `split(regex)` for IE8 compatibility. See #17.
+ string = string.replace(regexSeparators, '\x2E');
+ var labels = string.split('.');
+ var encoded = map(labels, fn).join('.');
+ return result + encoded;
+ }
- attrs = this._$name_to_attrs[attr.name];
- attrs.splice(attrs.indexOf(attr), 1);
+ /**
+ * Creates an array containing the numeric code points of each Unicode
+ * character in the string. While JavaScript uses UCS-2 internally,
+ * this function will convert a pair of surrogate halves (each of which
+ * UCS-2 exposes as separate characters) into a single code point,
+ * matching UTF-16.
+ * @see `punycode.ucs2.encode`
+ * @see
+ * @memberOf punycode.ucs2
+ * @name decode
+ * @param {String} string The Unicode input string (UCS-2).
+ * @returns {Array} The new array of code points.
+ */
+ function ucs2decode(string) {
+ var output = [],
+ counter = 0,
+ length = string.length,
+ value,
+ extra;
+ while (counter < length) {
+ value = string.charCodeAt(counter++);
+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+ // high surrogate, and there is a next character
+ extra = string.charCodeAt(counter++);
+ if ((extra & 0xFC00) == 0xDC00) { // low surrogate
+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+ } else {
+ // unmatched surrogate; only append this code unit, in case the next
+ // code unit is the high surrogate of a surrogate pair
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
+ }
- var ix = Array.prototype.indexOf.call(this, attr);
- // Splice also modifies length.
- Array.prototype.splice.call(this, ix, 1);
+ /**
+ * Creates a string based on an array of numeric code points.
+ * @see `punycode.ucs2.decode`
+ * @memberOf punycode.ucs2
+ * @name encode
+ * @param {Array} codePoints The array of numeric code points.
+ * @returns {String} The new Unicode string (UCS-2).
+ */
+ function ucs2encode(array) {
+ return map(array, function(value) {
+ var output = '';
+ if (value > 0xFFFF) {
+ value -= 0x10000;
+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
+ value = 0xDC00 | value & 0x3FF;
+ }
+ output += stringFromCharCode(value);
+ return output;
+ }).join('');
+ }
- if (this[attr.name] === attr) {
- delete this[attr.name];
- }
+ /**
+ * Converts a basic code point into a digit/integer.
+ * @see `digitToBasic()`
+ * @private
+ * @param {Number} codePoint The basic numeric code point value.
+ * @returns {Number} The numeric value of a basic code point (for use in
+ * representing integers) in the range `0` to `base - 1`, or `base` if
+ * the code point does not represent a value.
+ */
+ function basicToDigit(codePoint) {
+ if (codePoint - 48 < 10) {
+ return codePoint - 22;
+ }
+ if (codePoint - 65 < 26) {
+ return codePoint - 65;
+ }
+ if (codePoint - 97 < 26) {
+ return codePoint - 97;
+ }
+ return base;
+ }
- this._parentNode._attrModified(attr.name);
- this._parentNode._modified();
+ /**
+ * Converts a digit/integer into a basic code point.
+ * @see `basicToDigit()`
+ * @private
+ * @param {Number} digit The numeric value of a basic code point.
+ * @returns {Number} The basic code point whose value (when used for
+ * representing integers) is `digit`, which needs to be in the range
+ * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
+ * used; else, the lowercase form is used. The behavior is undefined
+ * if `flag` is non-zero and `digit` has no uppercase form.
+ */
+ function digitToBasic(digit, flag) {
+ // 0..25 map to ASCII a..z or A..Z
+ // 26..35 map to ASCII 0..9
+ return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
+ }
- return attr;
- },
+ /**
+ * Bias adaptation function as per section 3.4 of RFC 3492.
+ * http://tools.ietf.org/html/rfc3492#section-3.4
+ * @private
+ */
+ function adapt(delta, numPoints, firstTime) {
+ var k = 0;
+ delta = firstTime ? floor(delta / damp) : delta >> 1;
+ delta += floor(delta / numPoints);
+ for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
+ delta = floor(delta / baseMinusTMin);
+ }
+ return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
+ }
- $removeNode: function (attr) {
- if (!this._$onlyRemoveNode(attr)) {
- return null;
- }
+ /**
+ * Converts a Punycode string of ASCII-only symbols to a string of Unicode
+ * symbols.
+ * @memberOf punycode
+ * @param {String} input The Punycode string of ASCII-only symbols.
+ * @returns {String} The resulting string of Unicode symbols.
+ */
+ function decode(input) {
+ // Don't use UCS-2
+ var output = [],
+ inputLength = input.length,
+ out,
+ i = 0,
+ n = initialN,
+ bias = initialBias,
+ basic,
+ j,
+ index,
+ oldi,
+ w,
+ k,
+ digit,
+ t,
+ /** Cached calculation results */
+ baseMinusT;
+
+ // Handle the basic code points: let `basic` be the number of input code
+ // points before the last delimiter, or `0` if there is none, then copy
+ // the first basic code points to the output.
+
+ basic = input.lastIndexOf(delimiter);
+ if (basic < 0) {
+ basic = 0;
+ }
+
+ for (j = 0; j < basic; ++j) {
+ // if it's not a basic code point
+ if (input.charCodeAt(j) >= 0x80) {
+ error('not-basic');
+ }
+ output.push(input.charCodeAt(j));
+ }
- // set default value if available
- var doc = this._ownerDocument;
- if (doc && doc._doctype && doc._doctype.name.toLowerCase() !== "html") {
- var elem =
- doc._doctype._attributes.getNamedItem(this._parentNode.nodeName);
-
- if (elem) {
- var defaultValue = elem.attributes.getNamedItemNS(attr._namespaceURI,
- attr._localName);
-
- if (defaultValue) {
- this.$set(attr._localName, defaultValue.value, attr.name, attr._prefix,
- attr._namespaceURI);
- var new_attr = this.$getNode(attr._namespaceURI, attr._localName);
- new_attr._specified = false;
- }
- }
- }
- return attr;
- },
-
- // Although http://dom.spec.whatwg.org/#concept-element-attribute
- // does not specify that the attributes field on an Element should
- // support NamedNodeMap, in practice browsers still support this
- // interface so we should support it for compatibility.
-
- getNamedItem: function (name) {
- return this.getNamedItemNS(null, name);
- },
- removeNamedItem: function (name) {
- return this.removeNamedItemNS(null, name);
- },
- item: function (i) {
- return this[i];
- },
- getNamedItemNS: function (namespaceURI, localName) {
- if (namespaceURI === "") {
- namespaceURI = null;
- }
+ // Main decoding loop: start just after the last delimiter if any basic code
+ // points were copied; start at the beginning otherwise.
- return this.$getNode(namespaceURI, localName);
- },
- removeNamedItemNS: function (namespaceURI, localName) {
- var ret = this.$remove(namespaceURI, localName);
+ for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
- if (ret === null) {
- throw new core.DOMException(NOT_FOUND_ERR);
- }
+ // `index` is the index of the next character to be consumed.
+ // Decode a generalized variable-length integer into `delta`,
+ // which gets added to `i`. The overflow checking is easier
+ // if we increase `i` as we go, then subtract off its starting
+ // value at the end to obtain `delta`.
+ for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
- return ret;
- }
- };
+ if (index >= inputLength) {
+ error('invalid-input');
+ }
- // Alias these methods.
- AttributeList.prototype.setNamedItem = AttributeList.prototype.$setNode;
- AttributeList.prototype.setNamedItemNS = AttributeList.prototype.$setNode;
-
- (function () {
- // Construct the list of reserved attribute names from a temporarily
- // created AttributeList and from the chain of prototypes. We need
- // this because JavaScript code running an a browser expects to be
- // able to do el.attributes.x to get the value of the attribute "x"
- // on an element. Unfortunately, JavaScript *currently* does not
- // allow us to elegantly provide such functionality without risking
- // a clash with the fields and methods set on the AttributeList
- // object. Hence we need a list of reserved field names.
-
- var reserved = Object.keys(new AttributeList());
- var prototype = AttributeList.prototype;
- while (prototype) {
- reserved = reserved.concat(Object.getOwnPropertyNames(prototype));
- prototype = Object.getPrototypeOf(prototype);
- }
- AttributeList.prototype._$reserved = reserved;
- })();
+ digit = basicToDigit(input.charCodeAt(index++));
- core.AttributeList = AttributeList;
+ if (digit >= base || digit > floor((maxInt - i) / w)) {
+ error('overflow');
+ }
- core.NotationNodeMap = function NotationNodeMap(document) {
- core.NamedNodeMap.call(this, document);
- this._readonly = false;
- for (var i=1;i= bias + tMax ? tMax : k - bias);
- core.EntityNodeMap = function EntityNodeMap(document) {
- core.NamedNodeMap.call(this,document);
- this._readonly = false;
- var i = 1, l = arguments.length;
+ if (digit < t) {
+ break;
+ }
- for (i=1; i floor(maxInt / baseMinusT)) {
+ error('overflow');
+ }
- core.Element = function Element(document, tagName) {
- this._ownerDocument = document;
- core.Node.call(this, document);
- this._nodeName = tagName;
- this._tagName = tagName;
- };
+ w *= baseMinusT;
- inheritFrom(core.Node, core.Element, {
-
- get nodeValue() { return null;},
- set nodeValue(value) { /* do nothing */ },
- get tagName() {
- if (this.nodeType === ELEMENT_NODE &&
- this._ownerDocument &&
- this._ownerDocument._doctype &&
- this._ownerDocument._doctype.name.toLowerCase().indexOf("html") !== -1)
- {
- return this.nodeName.toUpperCase();
- }
- return this.nodeName;
- },
- nodeType : ELEMENT_NODE,
- get attributes() {
- return this._attributes;
- },
-
- /* returns string */
- getAttribute: function(/* string */ name) {
- var attribute = this._attributes.$getNode(null, name);
- if (attribute) {
- return attribute.value;
- }
- return null;
- },
-
- setAttribute: function(/* string */ name, /* string */ value) {
- if (this._ownerDocument) {
- var attr = this._ownerDocument.createAttribute(name);
- attr.value = value;
- attr._ownerElement = this;
- attr._created = true;
- this._attributes.$setNode(attr);
- }
+ }
- }, //raises: function(DOMException) {},
+ out = output.length + 1;
+ bias = adapt(i - oldi, out, oldi == 0);
- removeAttribute: function(/* string */ name) {
- this._attributes.$remove(null, name);
- }, // raises: function(DOMException) {},
+ // `i` was supposed to wrap around from `out` to `0`,
+ // incrementing `n` each time, so we'll fix that now:
+ if (floor(i / out) > maxInt - n) {
+ error('overflow');
+ }
- /* returns Attr */
- getAttributeNode: function(/* string */ name) {
- return this._attributes.$getNode(null, name);
- },
+ n += floor(i / out);
+ i %= out;
- /* returns Attr */
- setAttributeNode: function(/* Attr */ newAttr) {
- var prevNode = this._attributes.$getNode(null, newAttr.name);
- if (prevNode) {
- prevNode._ownerElement = null;
- }
+ // Insert `n` at position `i` of the output
+ output.splice(i++, 0, n);
- newAttr._ownerElement = this;
- this._attributes.$setNode(newAttr);
+ }
- return (prevNode && prevNode.specified) ? prevNode : null;
- }, // raises: function(DOMException) {},
+ return ucs2encode(output);
+ }
- /* returns Attr */
- removeAttributeNode: function(/* Attr */ oldAttr) {
- var ret = this._attributes.$removeNode(oldAttr);
+ /**
+ * Converts a string of Unicode symbols (e.g. a domain name label) to a
+ * Punycode string of ASCII-only symbols.
+ * @memberOf punycode
+ * @param {String} input The string of Unicode symbols.
+ * @returns {String} The resulting Punycode string of ASCII-only symbols.
+ */
+ function encode(input) {
+ var n,
+ delta,
+ handledCPCount,
+ basicLength,
+ bias,
+ j,
+ m,
+ q,
+ k,
+ t,
+ currentValue,
+ output = [],
+ /** `inputLength` will hold the number of code points in `input`. */
+ inputLength,
+ /** Cached calculation results */
+ handledCPCountPlusOne,
+ baseMinusT,
+ qMinusT;
+
+ // Convert the input in UCS-2 to Unicode
+ input = ucs2decode(input);
+
+ // Cache the length
+ inputLength = input.length;
+
+ // Initialize the state
+ n = initialN;
+ delta = 0;
+ bias = initialBias;
+
+ // Handle the basic code points
+ for (j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
+ if (currentValue < 0x80) {
+ output.push(stringFromCharCode(currentValue));
+ }
+ }
- if (ret !== null) {
- return ret;
- }
+ handledCPCount = basicLength = output.length;
- throw new core.DOMException(NOT_FOUND_ERR);
- }, //raises: function(DOMException) {},
+ // `handledCPCount` is the number of code points that have been handled;
+ // `basicLength` is the number of basic code points.
- /* returns NodeList */
- getElementsByTagName: core.memoizeQuery(function(/* string */ name) {
- name = name.toLowerCase();
+ // Finish the basic string - if it is not empty - with a delimiter
+ if (basicLength) {
+ output.push(delimiter);
+ }
- function filterByTagName(child) {
- child = (child.nodeType === ENTITY_REFERENCE_NODE) ?
- child._entity :
- child;
+ // Main encoding loop:
+ while (handledCPCount < inputLength) {
- if (child.nodeName && child.nodeType === ELEMENT_NODE) {
- return name === "*" || (child.nodeName.toLowerCase() === name);
- }
+ // All non-basic code points < n have been handled already. Find the next
+ // larger one:
+ for (m = maxInt, j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
+ if (currentValue >= n && currentValue < m) {
+ m = currentValue;
+ }
+ }
- return false;
- }
- return new core.NodeList(this._ownerDocument || this, core.mapper(this, filterByTagName, true));
- }),
- });
+ // Increase `delta` enough to advance the decoder's state to ,
+ // but guard against overflow
+ handledCPCountPlusOne = handledCPCount + 1;
+ if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
+ error('overflow');
+ }
- core.DocumentFragment = function DocumentFragment(document) {
- core.Node.call(this, document);
- this._nodeName = this._tagName = "#document-fragment";
- };
- inheritFrom(core.Node, core.DocumentFragment, {
- nodeType : DOCUMENT_FRAGMENT_NODE,
- get nodeValue() { return null;},
- set nodeValue(unused) { /* do nothing */ },
- get attributes() { return null;}
- });
+ delta += (m - n) * handledCPCountPlusOne;
+ n = m;
- core.ProcessingInstruction = function ProcessingInstruction(document, target, data) {
- this._ownerDocument = document;
- core.Node.call(this, document);
- this._nodeName = target;
- this._tagName = target;
- this._target = target;
- this._nodeValue = data;
- }
- inheritFrom(core.Node, core.ProcessingInstruction, {
- nodeType : PROCESSING_INSTRUCTION_NODE,
- get target() { return this._target;},
- set target(value) { throw new core.DOMException(1);},
- get nodeValue() { return this._nodeValue;},
- set nodeValue(value) { this._nodeValue = value},
- get data() { return this._nodeValue;},
- set data(unused) { throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);},
- get attributes() { return null;}
+ for (j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
- });
+ if (currentValue < n && ++delta > maxInt) {
+ error('overflow');
+ }
- core.Document = function Document(options) {
- if (!options) {
- options = {};
- }
- else if (typeof options == 'string') {
- options = {
- name: options
- };
- }
- core.Node.call(this, "#document");
- this._nodeName = this._tagName = "#document";
- this._contentType = options.contentType || "text/xml";
- this._doctype = options._doctype;
- this._implementation = options.implementation || new (core.DOMImplementation)();
- this._documentElement = null;
- this._ids = Object.create(null);
- this._attached = true;
- this._ownerDocument = this;
- this._readonly = false;
- };
+ if (currentValue == n) {
+ // Represent delta as a generalized variable-length integer
+ for (q = delta, k = base; /* no condition */; k += base) {
+ t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
+ if (q < t) {
+ break;
+ }
+ qMinusT = q - t;
+ baseMinusT = base - t;
+ output.push(
+ stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
+ );
+ q = floor(qMinusT / baseMinusT);
+ }
+ output.push(stringFromCharCode(digitToBasic(q, 0)));
+ bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
+ delta = 0;
+ ++handledCPCount;
+ }
+ }
- var tagRegEx = /[^\w:\d_\.-]+/i;
- var entRegEx = /[^\w\d_\-&;]+/;
- var invalidAttrRegEx = /[\s"'>/=\u0000-\u001A]/;
-
- inheritFrom(core.Node, core.Document, {
- nodeType : DOCUMENT_NODE,
- _elementBuilders : { },
- _defaultElementBuilder: function(document, tagName) {
- return new core.Element(document, tagName);
- },
- get contentType() { return this._contentType;},
- get doctype() { return this._doctype || null;},
- set doctype(doctype) { this._doctype = doctype;},
- get documentElement() {
- if (this._documentElement) {
- return this._documentElement;
- } else {
- var children = this._childNodes, len = this._childNodes.length, i=0;
- for (i;i
+ * @memberOf punycode
+ * @type Object
+ */
+ 'ucs2': {
+ 'decode': ucs2decode,
+ 'encode': ucs2encode
+ },
+ 'decode': decode,
+ 'encode': encode,
+ 'toASCII': toASCII,
+ 'toUnicode': toUnicode
+ };
- if (tagName.length === 0 || (c = tagName.match(tagRegEx))) {
- throw new core.DOMException(INVALID_CHARACTER_ERR, 'Invalid character in tag name: ' + c.pop());
- }
+ /** Expose `punycode` */
+ // Some AMD build optimizers, like r.js, check for specific condition patterns
+ // like the following:
+ if (
+ true
+ ) {
+ !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
+ return punycode;
+ }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (freeExports && freeModule) {
+ if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
+ freeModule.exports = punycode;
+ } else { // in Narwhal or RingoJS v0.7.0-
+ for (key in punycode) {
+ punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
+ }
+ }
+ } else { // in Rhino or a web browser
+ root.punycode = punycode;
+ }
- return this._createElementNoTagNameValidation(tagName);
- }, //raises: function(DOMException) {},
+ }(this));
- /* returns DocumentFragment */
- createDocumentFragment: function() {
- return new core.DocumentFragment(this);
- },
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)(module), (function() { return this; }())))
- /* returns Text */
- createTextNode: function(/* string */ data) {
- return new core.Text(this,data);
- },
+/***/ },
+/* 17 */
+/***/ function(module, exports) {
- /* returns Comment */
- createComment: function(/* string */ data) {
- return new core.Comment(this,data);
- },
+ module.exports = function(module) {
+ if(!module.webpackPolyfill) {
+ module.deprecate = function() {};
+ module.paths = [];
+ // module.parent = undefined by default
+ module.children = [];
+ module.webpackPolyfill = 1;
+ }
+ return module;
+ }
- /* returns CDATASection */
- createCDATASection: function(/* string */ data) {
- if (this._doctype && this._doctype.name === "html") {
- throw new core.DOMException(NOT_SUPPORTED_ERR);
- }
- return new core.CDATASection(this,data);
- }, // raises: function(DOMException) {},
+/***/ },
+/* 18 */
+/***/ function(module, exports, __webpack_require__) {
- /* returns ProcessingInstruction */
- createProcessingInstruction: function(/* string */ target,/* string */ data) {
- if (target.match(tagRegEx) || !target || !target.length) {
- throw new core.DOMException(INVALID_CHARACTER_ERR);
- }
+ 'use strict';
- return new core.ProcessingInstruction(this, target, data);
- }, // raises: function(DOMException) {},
+ exports.decode = exports.parse = __webpack_require__(19);
+ exports.encode = exports.stringify = __webpack_require__(20);
- /* returns Attr */
- createAttribute: function(/* string */ name) {
- if (!name || !name.length || name.match(invalidAttrRegEx) ) {
- throw new core.DOMException(INVALID_CHARACTER_ERR, "attribute name: " + name);
- }
- return new core.Attr(this, name,false);
- }, // raises: function(DOMException) {},
- /* returns EntityReference */
- createEntityReference: function(/* string */ name) {
+/***/ },
+/* 19 */
+/***/ function(module, exports) {
- if (this._doctype && this._doctype.name === "html") {
- throw new core.DOMException(NOT_SUPPORTED_ERR);
- }
+ // Copyright Joyent, Inc. and other Node contributors.
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining a
+ // copy of this software and associated documentation files (the
+ // "Software"), to deal in the Software without restriction, including
+ // without limitation the rights to use, copy, modify, merge, publish,
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
+ // persons to whom the Software is furnished to do so, subject to the
+ // following conditions:
+ //
+ // The above copyright notice and this permission notice shall be included
+ // in all copies or substantial portions of the Software.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
- name = name.replace(/[&;]/g,"");
- if (!name || !name.length) {
- throw new core.DOMException(INVALID_CHARACTER_ERR);
- }
+ 'use strict';
- if (name.match(tagRegEx)) {
- throw new core.DOMException(INVALID_CHARACTER_ERR);
- }
+ // If obj.hasOwnProperty has been overridden, then calling
+ // obj.hasOwnProperty(prop) will break.
+ // See: https://github.com/joyent/node/issues/1707
+ function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+ }
- var entity;
- if (this._doctype && this._doctype.entities) {
- entity = this._doctype.entities.getNamedItem(name);
- } else {
- entity = null;
- }
+ module.exports = function(qs, sep, eq, options) {
+ sep = sep || '&';
+ eq = eq || '=';
+ var obj = {};
+
+ if (typeof qs !== 'string' || qs.length === 0) {
+ return obj;
+ }
- var ref = new core.EntityReference(this, entity);
+ var regexp = /\+/g;
+ qs = qs.split(sep);
- ref._entityName = name;
+ var maxKeys = 1000;
+ if (options && typeof options.maxKeys === 'number') {
+ maxKeys = options.maxKeys;
+ }
- return ref;
- }, //raises: function(DOMException) {},
+ var len = qs.length;
+ // maxKeys <= 0 means that we should not limit keys count
+ if (maxKeys > 0 && len > maxKeys) {
+ len = maxKeys;
+ }
- /* returns Entity */
- createEntityNode : function(/* string */ name)
- {
+ for (var i = 0; i < len; ++i) {
+ var x = qs[i].replace(regexp, '%20'),
+ idx = x.indexOf(eq),
+ kstr, vstr, k, v;
- if (name.match(entRegEx) || !name || !name.length) {
- throw new core.DOMException(INVALID_CHARACTER_ERR);
+ if (idx >= 0) {
+ kstr = x.substr(0, idx);
+ vstr = x.substr(idx + 1);
+ } else {
+ kstr = x;
+ vstr = '';
}
- var ret = new core.Entity(this, name);
- ret._readonly = false;// TODO: fix me please.
+ k = decodeURIComponent(kstr);
+ v = decodeURIComponent(vstr);
- for (var i=1;i this._nodeValue.length) {
- throw new core.DOMException(INDEX_SIZE_ERR);
+ http.request = function (params, cb) {
+ if (typeof params === 'string') {
+ params = url.parse(params)
}
-
- return (this._nodeValue.length < offset + count) ?
- this._nodeValue.substring(offset) :
- this._nodeValue.substring(offset, offset+count);
-
- }, // raises: function(DOMException) {},
-
- /* returns string */
- appendData: function(/* string */ arg) {
-
- // readonly
- if (this._readonly === true) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
+ if (!params) params = {};
+ if (!params.host && !params.port) {
+ params.port = parseInt(window.location.port, 10);
}
-
- this._nodeValue+=arg;
- return this._nodeValue;
- }, // raises: function(DOMException) {},
-
- /* returns string */
- insertData: function(/* int */ offset, /* string */ arg) {
-
- // readonly
- if (this._readonly === true) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
+ if (!params.host && params.hostname) {
+ params.host = params.hostname;
}
- if (offset < 0 || offset > this._nodeValue.length) {
- throw new core.DOMException(INDEX_SIZE_ERR);
+ if (!params.protocol) {
+ if (params.scheme) {
+ params.protocol = params.scheme + ':';
+ } else {
+ params.protocol = window.location.protocol;
+ }
}
- var start = this._nodeValue.substring(0,offset);
- var end = this._nodeValue.substring(offset);
-
- this._nodeValue = start + arg + end;
+ if (!params.host) {
+ params.host = window.location.hostname || window.location.host;
+ }
+ if (/:/.test(params.host)) {
+ if (!params.port) {
+ params.port = params.host.split(':')[1];
+ }
+ params.host = params.host.split(':')[0];
+ }
+ if (!params.port) params.port = params.protocol == 'https:' ? 443 : 80;
+
+ var req = new Request(new xhrHttp, params);
+ if (cb) req.on('response', cb);
+ return req;
+ };
- }, //raises: function(DOMException) {},
+ http.get = function (params, cb) {
+ params.method = 'GET';
+ var req = http.request(params, cb);
+ req.end();
+ return req;
+ };
- /* returns void */
- deleteData: function(/* int */ offset, /* int */ count) {
+ http.Agent = function () {};
+ http.Agent.defaultMaxSockets = 4;
- // readonly
- if (this._readonly === true) {
- throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
+ var xhrHttp = (function () {
+ if (typeof window === 'undefined') {
+ throw new Error('no window object present');
}
-
- if (offset < 0 ||
- offset > this._nodeValue.length ||
- count < 0)
- {
- throw new core.DOMException(INDEX_SIZE_ERR);
+ else if (window.XMLHttpRequest) {
+ return window.XMLHttpRequest;
+ }
+ else if (window.ActiveXObject) {
+ var axs = [
+ 'Msxml2.XMLHTTP.6.0',
+ 'Msxml2.XMLHTTP.3.0',
+ 'Microsoft.XMLHTTP'
+ ];
+ for (var i = 0; i < axs.length; i++) {
+ try {
+ var ax = new(window.ActiveXObject)(axs[i]);
+ return function () {
+ if (ax) {
+ var ax_ = ax;
+ ax = null;
+ return ax_;
+ }
+ else {
+ return new(window.ActiveXObject)(axs[i]);
+ }
+ };
+ }
+ catch (e) {}
+ }
+ throw new Error('ajax not supported in this browser')
+ }
+ else {
+ throw new Error('ajax not supported in this browser');
}
+ })();
- var start = this._nodeValue.substring(0,offset);
+ http.STATUS_CODES = {
+ 100 : 'Continue',
+ 101 : 'Switching Protocols',
+ 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
+ 200 : 'OK',
+ 201 : 'Created',
+ 202 : 'Accepted',
+ 203 : 'Non-Authoritative Information',
+ 204 : 'No Content',
+ 205 : 'Reset Content',
+ 206 : 'Partial Content',
+ 207 : 'Multi-Status', // RFC 4918
+ 300 : 'Multiple Choices',
+ 301 : 'Moved Permanently',
+ 302 : 'Moved Temporarily',
+ 303 : 'See Other',
+ 304 : 'Not Modified',
+ 305 : 'Use Proxy',
+ 307 : 'Temporary Redirect',
+ 400 : 'Bad Request',
+ 401 : 'Unauthorized',
+ 402 : 'Payment Required',
+ 403 : 'Forbidden',
+ 404 : 'Not Found',
+ 405 : 'Method Not Allowed',
+ 406 : 'Not Acceptable',
+ 407 : 'Proxy Authentication Required',
+ 408 : 'Request Time-out',
+ 409 : 'Conflict',
+ 410 : 'Gone',
+ 411 : 'Length Required',
+ 412 : 'Precondition Failed',
+ 413 : 'Request Entity Too Large',
+ 414 : 'Request-URI Too Large',
+ 415 : 'Unsupported Media Type',
+ 416 : 'Requested Range Not Satisfiable',
+ 417 : 'Expectation Failed',
+ 418 : 'I\'m a teapot', // RFC 2324
+ 422 : 'Unprocessable Entity', // RFC 4918
+ 423 : 'Locked', // RFC 4918
+ 424 : 'Failed Dependency', // RFC 4918
+ 425 : 'Unordered Collection', // RFC 4918
+ 426 : 'Upgrade Required', // RFC 2817
+ 428 : 'Precondition Required', // RFC 6585
+ 429 : 'Too Many Requests', // RFC 6585
+ 431 : 'Request Header Fields Too Large',// RFC 6585
+ 500 : 'Internal Server Error',
+ 501 : 'Not Implemented',
+ 502 : 'Bad Gateway',
+ 503 : 'Service Unavailable',
+ 504 : 'Gateway Time-out',
+ 505 : 'HTTP Version Not Supported',
+ 506 : 'Variant Also Negotiates', // RFC 2295
+ 507 : 'Insufficient Storage', // RFC 4918
+ 509 : 'Bandwidth Limit Exceeded',
+ 510 : 'Not Extended', // RFC 2774
+ 511 : 'Network Authentication Required' // RFC 6585
+ };
- this._nodeValue = (offset+count this._nodeValue.length) ?
- this.nodeValue.length-offset :
- count;
+ // Backwards-compat with node 0.10.x
+ EventEmitter.EventEmitter = EventEmitter;
- if (offset < 0 ||
- offset > this._nodeValue.length ||
- count < 0 /*||
- offset+count > this._nodeValue.length*/)
- {
- throw new core.DOMException(INDEX_SIZE_ERR);
- }
+ EventEmitter.prototype._events = undefined;
+ EventEmitter.prototype._maxListeners = undefined;
- var start = this._nodeValue.substring(0,offset);
- var end = this._nodeValue.substring(offset+count);
+ // By default EventEmitters will print a warning if more than 10 listeners are
+ // added to it. This is a useful default which helps finding memory leaks.
+ EventEmitter.defaultMaxListeners = 10;
- this._nodeValue = start + arg + end;
- } // raises: function(DOMException) {},
- });
+ // Obviously not all Emitters should be limited to 10. This function allows
+ // that to be increased. Set to zero for unlimited.
+ EventEmitter.prototype.setMaxListeners = function(n) {
+ if (!isNumber(n) || n < 0 || isNaN(n))
+ throw TypeError('n must be a positive number');
+ this._maxListeners = n;
+ return this;
+ };
+ EventEmitter.prototype.emit = function(type) {
+ var er, handler, len, args, i, listeners;
- core.Attr = function Attr(document, name, value) {
- core.Node.call(this, document);
- this._nodeValue = value;
- this._name = name;
- this._specified = (value) ? true : false;
- this._tagName = name;
- this._nodeName = name;
-
- // Proactively set some level 2 information so that AttributeList
- // can operate.
- this._namespaceURI = null;
- this._nodeName = name;
- this._localName = name;
- this._prefix = null;
- };
- inheritFrom(core.Node, core.Attr, {
- nodeType : ATTRIBUTE_NODE,
- get nodeValue() {
- var val = '';
- for (var i=0,len=this._childNodes.length;i this._nodeValue.length) {
- throw new core.DOMException(INDEX_SIZE_ERR);
- }
+ if (!this._events)
+ this._events = {};
- var newText = this._nodeValue.substring(offset);
- this._nodeValue = this._nodeValue.substring(0, offset);
- var newNode = this._ownerDocument.createTextNode(newText);
+ // To avoid recursion in the case that type === "newListener"! Before
+ // adding it to the listeners, first emit "newListener".
+ if (this._events.newListener)
+ this.emit('newListener', type,
+ isFunction(listener.listener) ?
+ listener.listener : listener);
- if(this._parentNode.lastChild === this) {
- this._parentNode.appendChild(newNode);
+ if (!this._events[type])
+ // Optimize the case of one listener. Don't need the extra array object.
+ this._events[type] = listener;
+ else if (isObject(this._events[type]))
+ // If we've already got an array, just append.
+ this._events[type].push(listener);
+ else
+ // Adding the second element, need to change to array.
+ this._events[type] = [this._events[type], listener];
+
+ // Check for listener leak
+ if (isObject(this._events[type]) && !this._events[type].warned) {
+ var m;
+ if (!isUndefined(this._maxListeners)) {
+ m = this._maxListeners;
} else {
- this._parentNode.insertBefore(newNode, this.nextSibling);
+ m = EventEmitter.defaultMaxListeners;
}
- return newNode;
- }, //raises: function(DOMException) {},
- toString: function() {
- return this.nodeName;
+ if (m && m > 0 && this._events[type].length > m) {
+ this._events[type].warned = true;
+ console.error('(node) warning: possible EventEmitter memory ' +
+ 'leak detected. %d listeners added. ' +
+ 'Use emitter.setMaxListeners() to increase limit.',
+ this._events[type].length);
+ if (typeof console.trace === 'function') {
+ // not supported in IE 10
+ console.trace();
+ }
+ }
}
- });
-
-
- core.Comment = function Comment(document, text) {
- core.Text.call(this, document, text);
- this._nodeName = "#comment";
- this._tagName = "#comment";
- };
- inheritFrom(core.Text, core.Comment, {
- nodeType : COMMENT_NODE
- });
-
- core.CDATASection = function CDATASection(document, value) {
- core.Text.call(this, document, value);
- this._nodeName = "#cdata-section";
+ return this;
};
- inheritFrom(core.Text, core.CDATASection, {
- nodeType : CDATA_SECTION_NODE
- });
- core.DocumentType = function DocumentType(document, name, entities, notations, attributes) {
- core.Node.call(this, document);
- this._name = name;
- this._tagName = name;
- this._nodeName = name;
- this._entities = entities || new core.EntityNodeMap(document);
- this._notations = notations || new core.NotationNodeMap(document);
- this._parentNode = document;
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
- core.markTreeReadonly(this._notations);
+ EventEmitter.prototype.once = function(type, listener) {
+ if (!isFunction(listener))
+ throw TypeError('listener must be a function');
- this._attributes = attributes || new AttributeList(document);
- };
- inheritFrom(core.Node, core.DocumentType, {
- nodeType : DOCUMENT_TYPE_NODE,
- get nodeValue() { return null;},
- set nodeValue(unused) { /* do nothing */ },
- get name() { return this._name;},
- get entities() { return this._entities;},
- get notations() { return this._notations;},
- get attributes() { return null;}
- });
+ var fired = false;
+ function g() {
+ this.removeListener(type, g);
- core.Notation = function Notation(document, name, publicId, systemId){
- core.Node.call(this, document);
- this._name = name;
- this._nodeName = name;
- this._publicId = publicId || null;
- this._systemId = systemId || null;
- this._nodeValue = null;
- };
- inheritFrom(core.Node, core.Notation, {
- nodeType : NOTATION_NODE,
- get publicId() { return this._publicId;},
- get systemId() { return this._systemId;},
- get name() { return this._name || this._nodeName;},
- get attributes() { /* as per spec */ return null;},
- set nodeValue(unused) { /* intentionally left blank */ },
- get nodeValue() { return this._nodeValue;},
- });
+ if (!fired) {
+ fired = true;
+ listener.apply(this, arguments);
+ }
+ }
+ g.listener = listener;
+ this.on(type, g);
- core.Entity = function Entity(document, name) {
- core.Node.call(this, document);
- this._name = name;
- this._nodeName = name;
- this._tagName = name;
- this._publicId = null;
- this._systemId = null;
- this._notationName = null;
- this._readonly = true;
+ return this;
};
- inheritFrom(core.Node, core.Entity, {
- nodeType : ENTITY_NODE,
- get nodeValue() { return null;},
- set nodeValue(unused) {
- // readonly
- if (this._readonly === true) {
- // TODO: is this needed?
- // throw new DOMException(NO_MODIFICATION_ALLOWED_ERR);
- }
- /* do nothing */
- },
- get name() { return this._name },
- get publicId() { return this._publicId;},
- get systemId() { return this._systemId;},
-
- set publicId(publicId) { this._publicId = publicId;},
- set systemId(systemId) { this._systemId = systemId;},
- set notationName(notationName) { this._notationName = notationName;},
- get notationName() { return this._notationName;},
- get attributes() { return null;},
+ // emits a 'removeListener' event iff the listener was removed
+ EventEmitter.prototype.removeListener = function(type, listener) {
+ var list, position, length, i;
- });
+ if (!isFunction(listener))
+ throw TypeError('listener must be a function');
+ if (!this._events || !this._events[type])
+ return this;
- core.EntityReference = function EntityReference(document, entity) {
- core.Node.call(this, document);
- this._entity = entity;
- this._nodeName = (entity) ? entity.name : null;
- this._readonly = true;
- };
- inheritFrom(core.Node, core.EntityReference, {
- nodeType : ENTITY_REFERENCE_NODE,
- get nodeValue() { return (this._entity) ? this._entity.nodeValue : null;},
- set nodeValue(unused) {
- // readonly
- if (this._readonly === true) {
- // TODO: is this needed?
- //throw new DOMException(NO_MODIFICATION_ALLOWED_ERR);
+ list = this._events[type];
+ length = list.length;
+ position = -1;
+
+ if (list === listener ||
+ (isFunction(list.listener) && list.listener === listener)) {
+ delete this._events[type];
+ if (this._events.removeListener)
+ this.emit('removeListener', type, listener);
+
+ } else if (isObject(list)) {
+ for (i = length; i-- > 0;) {
+ if (list[i] === listener ||
+ (list[i].listener && list[i].listener === listener)) {
+ position = i;
+ break;
+ }
}
- /* do nothing */
- },
- get attributes() { return null;},
-
- // Proxy to the entity
- get nodeName() { return this._entityName;},
- get firstChild() { return this._entity.firstChild || null;},
- get childNodes() { return this._entity.childNodes;},
- get lastChild() { return this._entity.lastChild || null;},
+ if (position < 0)
+ return this;
- });
+ if (list.length === 1) {
+ list.length = 0;
+ delete this._events[type];
+ } else {
+ list.splice(position, 1);
+ }
- exports.dom = { "level1" : { "core" : core }};
+ if (this._events.removeListener)
+ this.emit('removeListener', type, listener);
+ }
+ return this;
+ };
-/***/ },
-/* 18 */
-/***/ function(module, exports, __webpack_require__) {
+ EventEmitter.prototype.removeAllListeners = function(type) {
+ var key, listeners;
- var core = __webpack_require__(16).dom.level2.core,
- events = __webpack_require__(19).dom.level2.events,
- applyDocumentFeatures = __webpack_require__(20).applyDocumentFeatures,
- defineGetter = __webpack_require__(14).defineGetter,
- defineSetter = __webpack_require__(14).defineSetter,
- inheritFrom = __webpack_require__(14).inheritFrom,
- URL = __webpack_require__(13),
- Path = __webpack_require__(12),
- fs = __webpack_require__(11),
- http = __webpack_require__(21),
- https = __webpack_require__(22);
-
- // modify cloned instance for more info check: https://github.com/tmpvar/jsdom/issues/325
- core = Object.create(core);
-
- // Setup the javascript language processor
- core.languageProcessors = {
- javascript : __webpack_require__(23).javascript
- };
+ if (!this._events)
+ return this;
- // TODO its own package? Pull request to Node?
- function resolveHref(baseUrl, href) {
- if (baseUrl === resolveHref.memoizedUrl && resolveHref.cache && resolveHref.cache[href]) {
- return resolveHref.cache[href];
+ // not listening for removeListener, no need to emit
+ if (!this._events.removeListener) {
+ if (arguments.length === 0)
+ this._events = {};
+ else if (this._events[type])
+ delete this._events[type];
+ return this;
}
- // When switching protocols, the path doesn't get canonicalized (i.e. .s and ..s are still left):
- // https://github.com/joyent/node/issues/5453
- var intermediate = URL.resolve(baseUrl, href);
- // This canonicalizes the path, at the cost of overwriting the hash.
- var nextStep = URL.resolve(intermediate, '#');
+ // emit removeListener for all listeners on all events
+ if (arguments.length === 0) {
+ for (key in this._events) {
+ if (key === 'removeListener') continue;
+ this.removeAllListeners(key);
+ }
+ this.removeAllListeners('removeListener');
+ this._events = {};
+ return this;
+ }
- // So, insert the hash back in, if there was one.
- var parsed = URL.parse(intermediate);
- var fixed = nextStep.slice(0, -1) + (parsed.hash || '');
+ listeners = this._events[type];
- // Finally, fix file:/// URLs on Windows, where Node removes their drive letters:
- // https://github.com/joyent/node/issues/5452
- if (/^file\:\/\/\/[a-z]\:\//i.test(baseUrl) && /^file\:\/\/\//.test(fixed) && !/^file\:\/\/\/[a-z]\:\//i.test(fixed)) {
- fixed = fixed.replace(/^file\:\/\/\//, baseUrl.substring(0, 11));
+ if (isFunction(listeners)) {
+ this.removeListener(type, listeners);
+ } else {
+ // LIFO order
+ while (listeners.length)
+ this.removeListener(type, listeners[listeners.length - 1]);
}
+ delete this._events[type];
- // HORRIBLE HACK: encode \u00E4 correctly just so that we pass
- // https://github.com/w3c/web-platform-tests/blob/e75f01a689a3481f5c773315c2c2527712cf8c2c/dom/nodes/DOMImplementation-createHTMLDocument.html#L71-L72
- // Eventually we should replace this with a real URL parser based on the URL standard.
- fixed = fixed.replace(/\u00E4/, "%C3%A4");
+ return this;
+ };
- if (baseUrl !== resolveHref.memoizedUrl) {
- resolveHref.memoizedUrl = baseUrl;
- resolveHref.cache = {};
- }
- resolveHref.cache[href] = fixed;
- return fixed;
- }
+ EventEmitter.prototype.listeners = function(type) {
+ var ret;
+ if (!this._events || !this._events[type])
+ ret = [];
+ else if (isFunction(this._events[type]))
+ ret = [this._events[type]];
+ else
+ ret = this._events[type].slice();
+ return ret;
+ };
- core.resourceLoader = {
- load: function(element, href, callback) {
- var ownerImplementation = element._ownerDocument.implementation;
+ EventEmitter.listenerCount = function(emitter, type) {
+ var ret;
+ if (!emitter._events || !emitter._events[type])
+ ret = 0;
+ else if (isFunction(emitter._events[type]))
+ ret = 1;
+ else
+ ret = emitter._events[type].length;
+ return ret;
+ };
- if (ownerImplementation.hasFeature('FetchExternalResources', element.tagName.toLowerCase())) {
- var full = this.resolve(element._ownerDocument, href);
- var url = URL.parse(full);
- if (ownerImplementation.hasFeature('SkipExternalResources', full)) {
- return false;
- }
- if (url.hostname) {
- this.download(url, element._ownerDocument._cookie, element._ownerDocument._cookieDomain, this.baseUrl(element._ownerDocument), this.enqueue(element, callback, full));
- }
- else {
- this.readFile(url.pathname, this.enqueue(element, callback, full));
- }
- }
- },
- enqueue: function(element, callback, filename) {
- var loader = this,
- doc = element.nodeType === core.Node.DOCUMENT_NODE ?
- element :
- element._ownerDocument;
-
- if (!doc._queue) {
- return function() {};
- }
+ function isFunction(arg) {
+ return typeof arg === 'function';
+ }
- return doc._queue.push(function(err, data) {
- var ev = doc.createEvent('HTMLEvents');
+ function isNumber(arg) {
+ return typeof arg === 'number';
+ }
- if (!err) {
- try {
- callback.call(element, data, filename || doc.URL);
- ev.initEvent('load', false, false);
- }
- catch(e) {
- err = e;
- }
- }
+ function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+ }
- if (err) {
- ev.initEvent('error', false, false);
- ev.error = err;
- }
+ function isUndefined(arg) {
+ return arg === void 0;
+ }
- element.dispatchEvent(ev);
- });
- },
- baseUrl: function(document) {
- var baseElements = document.getElementsByTagName('base');
- var baseUrl = document.URL;
+/***/ },
+/* 23 */
+/***/ function(module, exports, __webpack_require__) {
- if (baseElements.length > 0) {
- var baseHref = baseElements.item(0).href;
- if (baseHref) {
- baseUrl = resolveHref(baseUrl, baseHref);
- }
- }
+ var Stream = __webpack_require__(24);
+ var Response = __webpack_require__(41);
+ var Base64 = __webpack_require__(45);
+ var inherits = __webpack_require__(46);
- return baseUrl;
- },
- resolve: function(document, href) {
- // if getAttribute returns null, there is no href
- // lets resolve to an empty string (nulls are not expected farther up)
- if (href === null) {
- return '';
- }
+ var Request = module.exports = function (xhr, params) {
+ var self = this;
+ self.writable = true;
+ self.xhr = xhr;
+ self.body = [];
+
+ self.uri = (params.protocol || 'http:') + '//'
+ + params.host
+ + (params.port ? ':' + params.port : '')
+ + (params.path || '/')
+ ;
+
+ if (typeof params.withCredentials === 'undefined') {
+ params.withCredentials = true;
+ }
+
+ try { xhr.withCredentials = params.withCredentials }
+ catch (e) {}
+
+ if (params.responseType) try { xhr.responseType = params.responseType }
+ catch (e) {}
+
+ xhr.open(
+ params.method || 'GET',
+ self.uri,
+ true
+ );
- var baseUrl = this.baseUrl(document);
-
- return resolveHref(baseUrl, href);
- },
- download: function(url, cookie, cookieDomain, referrer, callback) {
- var path = url.pathname + (url.search || ''),
- options = {'method': 'GET', 'host': url.hostname, 'path': path},
- request;
- if (url.protocol === 'https:') {
- options.port = url.port || 443;
- request = https.request(options);
- } else {
- options.port = url.port || 80;
- request = http.request(options);
- }
+ xhr.onerror = function(event) {
+ self.emit('error', new Error('Network error'));
+ };
- // set header.
- if (referrer) {
- request.setHeader('Referer', referrer);
+ self._headers = {};
+
+ if (params.headers) {
+ var keys = objectKeys(params.headers);
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ if (!self.isSafeRequestHeader(key)) continue;
+ var value = params.headers[key];
+ self.setHeader(key, value);
+ }
}
- if (cookie) {
- var host = url.host.split(':')[0];
- if (host.indexOf(cookieDomain, host.length - cookieDomain.length) !== -1) {
- request.setHeader('cookie', cookie);
- }
+
+ if (params.auth) {
+ //basic auth
+ this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth));
}
- request.on('response', function (response) {
- var data = '';
- function success () {
- if ([301, 302, 303, 307].indexOf(response.statusCode) > -1) {
- var redirect = URL.resolve(url, response.headers["location"]);
- core.resourceLoader.download(URL.parse(redirect), cookie, cookieDomain, referrer, callback);
- } else {
- callback(null, data);
- }
- }
- response.setEncoding('utf8');
- response.on('data', function (chunk) {
- data += chunk.toString();
- });
- response.on('end', function() {
- // According to node docs, 'close' can fire after 'end', but not
- // vice versa. Remove 'close' listener so we don't call success twice.
- response.removeAllListeners('close');
- success();
- });
- response.on('close', function (err) {
- if (err) {
- callback(err);
- } else {
- success();
- }
- });
+ var res = new Response;
+ res.on('close', function () {
+ self.emit('close');
+ });
+
+ res.on('ready', function () {
+ self.emit('response', res);
});
- request.on('error', callback);
- request.end();
- },
- readFile: function(url, callback) {
- fs.readFile(url.replace(/^file:\/\//, "").replace(/^\/([a-z]):\//i, '$1:/').replace(/%20/g, ' '), 'utf8', callback);
- }
+ res.on('error', function (err) {
+ self.emit('error', err);
+ });
+
+ xhr.onreadystatechange = function () {
+ // Fix for IE9 bug
+ // SCRIPT575: Could not complete the operation due to error c00c023f
+ // It happens when a request is aborted, calling the success callback anyway with readyState === 4
+ if (xhr.__aborted) return;
+ res.handle(xhr);
+ };
};
- function define(elementClass, def) {
- var tagName = def.tagName,
- tagNames = def.tagNames || (tagName? [tagName] : []),
- parentClass = def.parentClass || core.HTMLElement,
- attrs = def.attributes || [],
- proto = def.proto || {};
-
- var elem = core[elementClass] = function(document, name) {
- parentClass.call(this, document, name || tagName.toUpperCase());
- if (elem._init) {
- elem._init.call(this);
- }
- };
- elem._init = def.init;
-
- inheritFrom(parentClass, elem, proto);
-
- attrs.forEach(function(n) {
- var prop = n.prop || n,
- attr = n.attr || prop.toLowerCase();
-
- if (!n.prop || n.read !== false) {
- defineGetter(elem.prototype, prop, function() {
- var s = this.getAttribute(attr);
- if (n.type && n.type === 'boolean') {
- return s !== null;
- }
- if (n.type && n.type === 'long') {
- return +s;
- }
- if (typeof n === 'object' && n.normalize) { // see GH-491
- return n.normalize(s);
- }
- if (s === null) {
- s = '';
- }
- return s;
- });
- }
-
- if (!n.prop || n.write !== false) {
- defineSetter(elem.prototype, prop, function(val) {
- if (!val) {
- this.removeAttribute(attr);
- }
- else {
- var s = val.toString();
- if (typeof n === 'object' && n.normalize) {
- s = n.normalize(s);
- }
- this.setAttribute(attr, s);
- }
- });
- }
- });
-
- tagNames.forEach(function(tag) {
- core.Document.prototype._elementBuilders[tag.toLowerCase()] = function(doc, s) {
- var el = new elem(doc, s);
-
- if (def.elementBuilder) {
- return def.elementBuilder(el, doc, s);
- }
+ inherits(Request, Stream);
- return el;
- };
- });
- }
+ Request.prototype.setHeader = function (key, value) {
+ this._headers[key.toLowerCase()] = value
+ };
+ Request.prototype.getHeader = function (key) {
+ return this._headers[key.toLowerCase()]
+ };
+ Request.prototype.removeHeader = function (key) {
+ delete this._headers[key.toLowerCase()]
+ };
- core.HTMLCollection = function HTMLCollection(element, query) {
- this._keys = [];
- core.NodeList.call(this, element, query);
+ Request.prototype.write = function (s) {
+ this.body.push(s);
};
- inheritFrom(core.NodeList, core.HTMLCollection, {
- namedItem: function(name) {
- // Try property shortcut; should work in most cases
- if (Object.prototype.hasOwnProperty.call(this, name)) {
- return this[name];
- }
- var results = this._toArray(),
- l = results.length,
- node,
- matchingName = null;
-
- for (var i=0; i 0 ? c[0] : null;
- }
-
- function ResourceQueue(paused) {
- this.paused = !!paused;
- }
- ResourceQueue.prototype = {
- push: function(callback) {
- var q = this;
- var item = {
- prev: q.tail,
- check: function() {
- if (!q.paused && !this.prev && this.fired){
- callback(this.err, this.data);
- if (this.next) {
- this.next.prev = null;
- this.next.check();
- }else{//q.tail===this
- q.tail = null;
+ else if (typeof this.body[0] === 'string') {
+ this.xhr.send(this.body.join(''));
}
+ else if (isArray(this.body[0])) {
+ var body = [];
+ for (var i = 0; i < this.body.length; i++) {
+ body.push.apply(body, this.body[i]);
}
- }
- };
- if (q.tail) {
- q.tail.next = item;
+ this.xhr.send(body);
}
- q.tail = item;
- return function(err, data) {
- item.fired = 1;
- item.err = err;
- item.data = data;
- item.check();
- };
- },
- resume: function() {
- if(!this.paused){
- return;
+ else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) {
+ var len = 0;
+ for (var i = 0; i < this.body.length; i++) {
+ len += this.body[i].length;
+ }
+ var body = new(this.body[0].constructor)(len);
+ var k = 0;
+
+ for (var i = 0; i < this.body.length; i++) {
+ var b = this.body[i];
+ for (var j = 0; j < b.length; j++) {
+ body[k++] = b[j];
+ }
+ }
+ this.xhr.send(body);
}
- this.paused = false;
- var head = this.tail;
- while(head && head.prev){
- head = head.prev;
+ else if (isXHR2Compatible(this.body[0])) {
+ this.xhr.send(this.body[0]);
}
- if(head){
- head.check();
+ else {
+ var body = '';
+ for (var i = 0; i < this.body.length; i++) {
+ body += this.body[i].toString();
+ }
+ this.xhr.send(body);
}
- }
- };
-
- core.HTMLDocument = function HTMLDocument(options) {
- options = options || {};
- if (!options.contentType) {
- options.contentType = 'text/html';
- }
- core.Document.call(this, options);
- this._referrer = options.referrer;
- this._cookie = options.cookie;
- this._cookieDomain = options.cookieDomain || '127.0.0.1';
- this._URL = options.url || '/';
- this._documentRoot = options.documentRoot || Path.dirname(this._URL);
- this._queue = new ResourceQueue(options.deferClose);
- this.readyState = 'loading';
-
- // Add level2 features
- this.implementation.addFeature('core' , '2.0');
- this.implementation.addFeature('html' , '2.0');
- this.implementation.addFeature('xhtml' , '2.0');
- this.implementation.addFeature('xml' , '2.0');
};
- inheritFrom(core.Document, core.HTMLDocument, {
- _referrer : "",
- get referrer() {
- return this._referrer || '';
- },
- get domain() {
- return "";
- },
- _URL : "",
- get URL() {
- return this._URL;
- },
- get images() {
- return this.getElementsByTagName('IMG');
- },
- get applets() {
- return new core.HTMLCollection(this, core.mapper(this, function(el) {
- if (el && el.tagName) {
- var upper = el.tagName.toUpperCase();
- if (upper === "APPLET") {
- return true;
- } else if (upper === "OBJECT" &&
- el.getElementsByTagName('APPLET').length > 0)
- {
- return true;
- }
- }
- }));
- },
- get links() {
- return new core.HTMLCollection(this, core.mapper(this, function(el) {
- if (el && el.tagName) {
- var upper = el.tagName.toUpperCase();
- if (upper === "AREA" || (upper === "A" && el.href)) {
- return true;
- }
- }
- }));
- },
- get forms() {
- return this.getElementsByTagName('FORM');
- },
- get anchors() {
- return this.getElementsByTagName('A');
- },
- open : function() {
- this._childNodes = new core.NodeList();
- this._documentElement = null;
- this._modified();
- },
- close : function() {
- this._queue.resume();
- // Set the readyState to 'complete' once all resources are loaded.
- // As a side-effect the document's load-event will be dispatched.
- core.resourceLoader.enqueue(this, function() {
- this.readyState = 'complete';
- var ev = this.createEvent('HTMLEvents');
- ev.initEvent('DOMContentLoaded', false, false);
- this.dispatchEvent(ev);
- })(null, true);
- },
-
- // document.write is defined in browser/index.js.
-
- writeln : function(text) {
- this.write(text + '\n');
- },
-
- getElementsByName : function(elementName) {
- return new core.HTMLCollection(this, core.mapper(this, function(el) {
- return (el.getAttribute && el.getAttribute("name") === elementName);
- }));
- },
-
- get title() {
- var head = this.head,
- title = head ? firstChild(head, 'TITLE') : null;
- return title ? title.textContent : '';
- },
-
- set title(val) {
- var title = firstChild(this.head, 'TITLE');
- if (!title) {
- title = this.createElement('TITLE');
- var head = this.head;
- if (!head) {
- head = this.createElement('HEAD');
- this.documentElement.insertBefore(head, this.documentElement.firstChild);
- }
- head.appendChild(title);
- }
- title.textContent = val;
- },
-
- get head() {
- return firstChild(this.documentElement, 'HEAD');
- },
-
- set head(unused) { /* noop */ },
-
- get body() {
- var body = firstChild(this.documentElement, 'BODY');
- if (!body) {
- body = firstChild(this.documentElement, 'FRAMESET');
- }
- return body;
- },
-
- get documentElement() {
- if (!this._documentElement) {
- this._documentElement = firstChild(this, 'HTML');
- }
- return this._documentElement;
- },
-
- _cookie : "",
- get cookie() {
- var cookies = Array.isArray(this._cookie) ?
- this._cookie :
- (this._cookie && this._cookie.length > 0 ? [this._cookie] : []);
-
- return cookies.map(function (x) {
- return x.split(';')[0];
- }).join('; ');
- },
- set cookie(val) {
- if (val == null) return val;
- var key = val.split('=')[0];
- var cookies = Array.isArray(this._cookie) ?
- this._cookie :
- (this._cookie && this._cookie.length > 0 ? [this._cookie] : []);
- for (var i = 0; i < cookies.length; i++) {
- if (cookies[i].lastIndexOf(key + '=', 0) === 0) {
- cookies[i] = val;
- key = null;
- break;
- }
- }
- if (key) {
- cookies.push(val);
- }
- if (cookies.length === 1) {
- this._cookie = cookies[0];
- } else {
- this._cookie = cookies;
- }
- return val;
- }
- });
-
- define('HTMLElement', {
- parentClass: core.Element,
- proto : {
- // Add default event behavior (click link to navigate, click button to submit
- // form, etc). We start by wrapping dispatchEvent so we can forward events to
- // the element's _eventDefault function (only events that did not incur
- // preventDefault).
- dispatchEvent : function (event) {
- var outcome = core.Node.prototype.dispatchEvent.call(this, event)
-
- if (!event._preventDefault &&
- event.target._eventDefaults[event.type] &&
- typeof event.target._eventDefaults[event.type] === 'function')
- {
- event.target._eventDefaults[event.type](event)
- }
- return outcome;
- },
- getBoundingClientRect: function () {
- return {
- bottom: 0,
- height: 0,
- left: 0,
- right: 0,
- top: 0,
- width: 0
- };
- },
- _eventDefaults : {}
- },
- attributes: [
- 'id',
- 'title',
- 'lang',
- 'dir',
- {prop: 'className', attr: 'class', normalize: function(s) { return s || ''; }}
- ]
- });
+ // Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html
+ Request.unsafeHeaders = [
+ "accept-charset",
+ "accept-encoding",
+ "access-control-request-headers",
+ "access-control-request-method",
+ "connection",
+ "content-length",
+ "cookie",
+ "cookie2",
+ "content-transfer-encoding",
+ "date",
+ "expect",
+ "host",
+ "keep-alive",
+ "origin",
+ "referer",
+ "te",
+ "trailer",
+ "transfer-encoding",
+ "upgrade",
+ "user-agent",
+ "via"
+ ];
- core.Document.prototype._defaultElementBuilder = function(document, tagName) {
- return new core.HTMLElement(document, tagName);
+ Request.prototype.isSafeRequestHeader = function (headerName) {
+ if (!headerName) return false;
+ return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1;
};
- // http://www.whatwg.org/specs/web-apps/current-work/#category-listed
- var listedElements = /button|fieldset|input|keygen|object|select|textarea/i;
-
- define('HTMLFormElement', {
- tagName: 'FORM',
- proto: {
- get elements() {
- return new core.HTMLCollection(this._ownerDocument, core.mapper(this, function(e) {
- return listedElements.test(e.nodeName) ; // TODO exclude
- }));
- },
- get length() {
- return this.elements.length;
- },
- _dispatchSubmitEvent: function() {
- var ev = this._ownerDocument.createEvent('HTMLEvents');
- ev.initEvent('submit', true, true);
- if (!this.dispatchEvent(ev)) {
- this.submit();
- };
- },
- submit: function() {
- },
- reset: function() {
- this.elements._toArray().forEach(function(el) {
- el.value = el.defaultValue;
- });
- }
- },
- attributes: [
- 'name',
- {prop: 'acceptCharset', attr: 'accept-charset'},
- 'action',
- 'enctype',
- 'method',
- 'target'
- ]
- });
-
- define('HTMLLinkElement', {
- tagName: 'LINK',
- proto: {
- get href() {
- return core.resourceLoader.resolve(this._ownerDocument, this.getAttribute('href'));
- }
- },
- attributes: [
- {prop: 'disabled', type: 'boolean'},
- 'charset',
- 'href',
- 'hreflang',
- 'media',
- 'rel',
- 'rev',
- 'target',
- 'type'
- ]
- });
-
- define('HTMLMetaElement', {
- tagName: 'META',
- attributes: [
- 'content',
- {prop: 'httpEquiv', attr: 'http-equiv'},
- 'name',
- 'scheme'
- ]
- });
-
- define('HTMLHtmlElement', {
- tagName: 'HTML',
- attributes: [
- 'version'
- ]
- });
+ var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) keys.push(key);
+ return keys;
+ };
- define('HTMLHeadElement', {
- tagName: 'HEAD',
- attributes: [
- 'profile'
- ]
- });
+ var isArray = Array.isArray || function (xs) {
+ return Object.prototype.toString.call(xs) === '[object Array]';
+ };
- define('HTMLTitleElement', {
- tagName: 'TITLE',
- proto: {
- get text() {
- return this.innerHTML;
- },
- set text(s) {
- this.innerHTML = s;
+ var indexOf = function (xs, x) {
+ if (xs.indexOf) return xs.indexOf(x);
+ for (var i = 0; i < xs.length; i++) {
+ if (xs[i] === x) return i;
}
- }
- });
-
- define('HTMLBaseElement', {
- tagName: 'BASE',
- attributes: [
- 'href',
- 'target'
- ]
- });
+ return -1;
+ };
+ var isXHR2Compatible = function (obj) {
+ if (typeof Blob !== 'undefined' && obj instanceof Blob) return true;
+ if (typeof ArrayBuffer !== 'undefined' && obj instanceof ArrayBuffer) return true;
+ if (typeof FormData !== 'undefined' && obj instanceof FormData) return true;
+ };
- //**Deprecated**
- define('HTMLIsIndexElement', {
- tagName : 'ISINDEX',
- parentClass : core.Element,
- proto : {
- get form() {
- return closest(this, 'FORM');
- }
- },
- attributes : [
- 'prompt'
- ]
- });
+/***/ },
+/* 24 */
+/***/ function(module, exports, __webpack_require__) {
- define('HTMLStyleElement', {
- tagName: 'STYLE',
- attributes: [
- {prop: 'disabled', type: 'boolean'},
- 'media',
- 'type',
- ]
- });
+ // Copyright Joyent, Inc. and other Node contributors.
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining a
+ // copy of this software and associated documentation files (the
+ // "Software"), to deal in the Software without restriction, including
+ // without limitation the rights to use, copy, modify, merge, publish,
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
+ // persons to whom the Software is furnished to do so, subject to the
+ // following conditions:
+ //
+ // The above copyright notice and this permission notice shall be included
+ // in all copies or substantial portions of the Software.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
- define('HTMLBodyElement', {
- proto: (function() {
- var proto = {};
- // The body element's "traditional" event handlers are proxied to the
- // window object.
- // See: http://www.whatwg.org/specs/web-apps/current-work/#the-body-element
- ['onafterprint', 'onbeforeprint', 'onbeforeunload', 'onblur', 'onerror',
- 'onfocus', 'onhashchange', 'onload', 'onmessage', 'onoffline', 'ononline',
- 'onpagehide', 'onpageshow', 'onpopstate', 'onresize', 'onscroll',
- 'onstorage', 'onunload'].forEach(function (name) {
- defineSetter(proto, name, function (handler) {
- this._ownerDocument.parentWindow[name] = handler;
- });
- defineGetter(proto, name, function () {
- return this._ownerDocument.parentWindow[name];
- });
- });
- return proto;
- })(),
- tagName: 'BODY',
- attributes: [
- 'aLink',
- 'background',
- 'bgColor',
- 'link',
- 'text',
- 'vLink'
- ]
- });
+ module.exports = Stream;
- define('HTMLSelectElement', {
- tagName: 'SELECT',
- proto: {
- get options() {
- return new core.HTMLOptionsCollection(this, core.mapper(this, function(n) {
- return n.nodeName === 'OPTION';
- }));
- },
+ var EE = __webpack_require__(22).EventEmitter;
+ var inherits = __webpack_require__(25);
- get length() {
- return this.options.length;
- },
+ inherits(Stream, EE);
+ Stream.Readable = __webpack_require__(26);
+ Stream.Writable = __webpack_require__(37);
+ Stream.Duplex = __webpack_require__(38);
+ Stream.Transform = __webpack_require__(39);
+ Stream.PassThrough = __webpack_require__(40);
- get selectedIndex() {
- return this.options._toArray().reduceRight(function(prev, option, i) {
- return option.selected ? i : prev;
- }, -1);
- },
+ // Backwards-compat with node 0.4.x
+ Stream.Stream = Stream;
- set selectedIndex(index) {
- this.options._toArray().forEach(function(option, i) {
- option.selected = i === index;
- });
- },
- get value() {
- var i = this.selectedIndex;
- if (this.options.length && (i === -1)) {
- i = 0;
- }
- if (i === -1) {
- return '';
- }
- return this.options[i].value;
- },
- set value(val) {
- var self = this;
- this.options._toArray().forEach(function(option) {
- if (option.value === val) {
- option.selected = true;
- } else {
- if (!self.hasAttribute('multiple')) {
- // Remove the selected bit from all other options in this group
- // if the multiple attr is not present on the select
- option.selected = false;
- }
- }
- });
- },
+ // old-style streams. Note that the pipe method (the only relevant
+ // part of this class) is overridden in the Readable class.
- get form() {
- return closest(this, 'FORM');
- },
+ function Stream() {
+ EE.call(this);
+ }
- get type() {
- return this.multiple ? 'select-multiple' : 'select-one';
- },
+ Stream.prototype.pipe = function(dest, options) {
+ var source = this;
- add: function(opt, before) {
- if (before) {
- this.insertBefore(opt, before);
- }
- else {
- this.appendChild(opt);
+ function ondata(chunk) {
+ if (dest.writable) {
+ if (false === dest.write(chunk) && source.pause) {
+ source.pause();
}
- },
+ }
+ }
- remove: function(index) {
- var opts = this.options._toArray();
- if (index >= 0 && index < opts.length) {
- var el = opts[index];
- el._parentNode.removeChild(el);
- }
- },
+ source.on('data', ondata);
- blur : function() {
- this._ownerDocument.activeElement = this._ownerDocument.body;
- },
- focus : function() {
- this._ownerDocument.activeElement = this;
+ function ondrain() {
+ if (source.readable && source.resume) {
+ source.resume();
}
+ }
- },
- attributes: [
- {prop: 'disabled', type: 'boolean'},
- {prop: 'multiple', type: 'boolean'},
- 'name',
- {prop: 'size', type: 'long'},
- {prop: 'tabIndex', type: 'long'},
- ]
- });
-
- define('HTMLOptGroupElement', {
- tagName: 'OPTGROUP',
- attributes: [
- {prop: 'disabled', type: 'boolean'},
- 'label'
- ]
- });
+ dest.on('drain', ondrain);
- define('HTMLOptionElement', {
- tagName: 'OPTION',
- proto: {
- _attrModified: function(name, value) {
- if (name === 'selected') {
- this.selected = this.defaultSelected;
- }
- core.HTMLElement.prototype._attrModified.call(this, arguments);
- },
- get form() {
- return closest(this, 'FORM');
- },
- get defaultSelected() {
- return this.getAttribute('selected') !== null;
- },
- set defaultSelected(s) {
- if (s) this.setAttribute('selected', 'selected');
- else this.removeAttribute('selected');
- },
- get text() {
- return this.innerHTML;
- },
- get value() {
- return (this.hasAttribute('value')) ? this.getAttribute('value') : this.innerHTML;
- },
- set value(val) {
- this.setAttribute('value', val);
- },
- get index() {
- return closest(this, 'SELECT').options._toArray().indexOf(this);
- },
- get selected() {
- if (this._selected === undefined) {
- this._selected = this.defaultSelected;
- }
+ // If the 'end' option is not supplied, dest.end() will be called when
+ // source gets the 'end' or 'close' events. Only dest.end() once.
+ if (!dest._isStdio && (!options || options.end !== false)) {
+ source.on('end', onend);
+ source.on('close', onclose);
+ }
- if (!this._selected && this.parentNode) {
- var select = closest(this, 'SELECT');
+ var didOnEnd = false;
+ function onend() {
+ if (didOnEnd) return;
+ didOnEnd = true;
- if (select) {
- var options = select.options;
+ dest.end();
+ }
- if (options.item(0) === this && !select.hasAttribute('multiple')) {
- var found = false, optArray = options._toArray();
- for (var i = 1, l = optArray.length; i*/
+ var isArray = __webpack_require__(28);
+ /**/
- define('HTMLObjectElement', {
- tagName: 'OBJECT',
- proto: {
- get form() {
- return closest(this, 'FORM');
- },
- get contentDocument() {
- return null;
- }
- },
- attributes: [
- 'code',
- 'align',
- 'archive',
- 'border',
- 'codeBase',
- 'codeType',
- 'data',
- {prop: 'declare', type: 'boolean'},
- {prop: 'height', type: 'long'},
- {prop: 'hspace', type: 'long'},
- 'name',
- 'standby',
- {prop: 'tabIndex', type: 'long'},
- 'type',
- 'useMap',
- {prop: 'vspace', type: 'long'},
- {prop: 'width', type: 'long'}
- ]
- });
- define('HTMLParamElement', {
- tagName: 'PARAM',
- attributes: [
- 'name',
- 'type',
- 'value',
- 'valueType'
- ]
- });
+ /**/
+ var Buffer = __webpack_require__(7).Buffer;
+ /**/
- define('HTMLAppletElement', {
- tagName: 'APPLET',
- attributes: [
- 'align',
- 'alt',
- 'archive',
- 'code',
- 'codeBase',
- 'height',
- {prop: 'hspace', type: 'long'},
- 'name',
- 'object',
- {prop: 'vspace', type: 'long'},
- 'width'
- ]
- });
+ Readable.ReadableState = ReadableState;
- define('HTMLMapElement', {
- tagName: 'MAP',
- proto: {
- get areas() {
- return this.getElementsByTagName("AREA");
- }
- },
- attributes: [
- 'name'
- ]
- });
+ var EE = __webpack_require__(22).EventEmitter;
- define('HTMLAreaElement', {
- tagName: 'AREA',
- attributes: [
- 'accessKey',
- 'alt',
- 'coords',
- 'href',
- {prop: 'noHref', type: 'boolean'},
- 'shape',
- {prop: 'tabIndex', type: 'long'},
- 'target'
- ]
- });
+ /**/
+ if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
+ return emitter.listeners(type).length;
+ };
+ /**/
- define('HTMLScriptElement', {
- tagName: 'SCRIPT',
- init: function() {
- this.addEventListener('DOMNodeInsertedIntoDocument', function() {
- if (this.src) {
- core.resourceLoader.load(this, this.src, this._eval);
- }
- else {
- var src = this.sourceLocation || {},
- filename = src.file || this._ownerDocument.URL;
+ var Stream = __webpack_require__(24);
- if (src) {
- filename += ':' + src.line + ':' + src.col;
- }
- filename += '