code
stringlengths
2
1.05M
ace.define("ace/mode/vala_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ValaHighlightRules = function() { this.$rules = { start: [ { token: [ 'meta.using.vala', 'keyword.other.using.vala', 'meta.using.vala', 'storage.modifier.using.vala', 'meta.using.vala', 'punctuation.terminator.vala' ], regex: '^(\\s*)(using)\\b(?:(\\s*)([^ ;$]+)(\\s*)((?:;)?))?' }, { include: '#code' } ], '#all-types': [ { include: '#primitive-arrays' }, { include: '#primitive-types' }, { include: '#object-types' } ], '#annotations': [ { token: [ 'storage.type.annotation.vala', 'punctuation.definition.annotation-arguments.begin.vala' ], regex: '(@[^ (]+)(\\()', push: [ { token: 'punctuation.definition.annotation-arguments.end.vala', regex: '\\)', next: 'pop' }, { token: [ 'constant.other.key.vala', 'text', 'keyword.operator.assignment.vala' ], regex: '(\\w*)(\\s*)(=)' }, { include: '#code' }, { token: 'punctuation.seperator.property.vala', regex: ',' }, { defaultToken: 'meta.declaration.annotation.vala' } ] }, { token: 'storage.type.annotation.vala', regex: '@\\w*' } ], '#anonymous-classes-and-new': [ { token: 'keyword.control.new.vala', regex: '\\bnew\\b', push_disabled: [ { token: 'text', regex: '(?<=\\)|\\])(?!\\s*{)|(?<=})|(?=;)', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<=\\)|\\])(?!\\s*{)|(?<=})|(?=;)', next: 'pop' }, { token: [ 'storage.type.vala', 'text' ], regex: '(\\w+)(\\s*)(?=\\[)', push: [ { token: 'text', regex: '}|(?=;|\\))', next: 'pop' }, { token: 'text', regex: '\\[', push: [ { token: 'text', regex: '\\]', next: 'pop' }, { include: '#code' } ] }, { token: 'text', regex: '{', push: [ { token: 'text', regex: '(?=})', next: 'pop' }, { include: '#code' } ] } ] }, { token: 'text', regex: '(?=\\w.*\\()', push: [ { token: 'text', regex: '(?<=\\))', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<=\\))', next: 'pop' }, { include: '#object-types' }, { token: 'text', regex: '\\(', push: [ { token: 'text', regex: '\\)', next: 'pop' }, { include: '#code' } ] } ] }, { token: 'meta.inner-class.vala', regex: '{', push: [ { token: 'meta.inner-class.vala', regex: '}', next: 'pop' }, { include: '#class-body' }, { defaultToken: 'meta.inner-class.vala' } ] } ] } ], '#assertions': [ { token: [ 'keyword.control.assert.vala', 'meta.declaration.assertion.vala' ], regex: '\\b(assert|requires|ensures)(\\s)', push: [ { token: 'meta.declaration.assertion.vala', regex: '$', next: 'pop' }, { token: 'keyword.operator.assert.expression-seperator.vala', regex: ':' }, { include: '#code' }, { defaultToken: 'meta.declaration.assertion.vala' } ] } ], '#class': [ { token: 'meta.class.vala', regex: '(?=\\w?[\\w\\s]*(?:class|(?:@)?interface|enum|struct|namespace)\\s+\\w+)', push: [ { token: 'paren.vala', regex: '}', next: 'pop' }, { include: '#storage-modifiers' }, { include: '#comments' }, { token: [ 'storage.modifier.vala', 'meta.class.identifier.vala', 'entity.name.type.class.vala' ], regex: '(class|(?:@)?interface|enum|struct|namespace)(\\s+)([\\w\\.]+)' }, { token: 'storage.modifier.extends.vala', regex: ':', push: [ { token: 'meta.definition.class.inherited.classes.vala', regex: '(?={|,)', next: 'pop' }, { include: '#object-types-inherited' }, { include: '#comments' }, { defaultToken: 'meta.definition.class.inherited.classes.vala' } ] }, { token: [ 'storage.modifier.implements.vala', 'meta.definition.class.implemented.interfaces.vala' ], regex: '(,)(\\s)', push: [ { token: 'meta.definition.class.implemented.interfaces.vala', regex: '(?=\\{)', next: 'pop' }, { include: '#object-types-inherited' }, { include: '#comments' }, { defaultToken: 'meta.definition.class.implemented.interfaces.vala' } ] }, { token: 'paren.vala', regex: '{', push: [ { token: 'paren.vala', regex: '(?=})', next: 'pop' }, { include: '#class-body' }, { defaultToken: 'meta.class.body.vala' } ] }, { defaultToken: 'meta.class.vala' } ], comment: 'attempting to put namespace in here.' } ], '#class-body': [ { include: '#comments' }, { include: '#class' }, { include: '#enums' }, { include: '#methods' }, { include: '#annotations' }, { include: '#storage-modifiers' }, { include: '#code' } ], '#code': [ { include: '#comments' }, { include: '#class' }, { token: 'text', regex: '{', push: [ { token: 'text', regex: '}', next: 'pop' }, { include: '#code' } ] }, { include: '#assertions' }, { include: '#parens' }, { include: '#constants-and-special-vars' }, { include: '#anonymous-classes-and-new' }, { include: '#keywords' }, { include: '#storage-modifiers' }, { include: '#strings' }, { include: '#all-types' } ], '#comments': [ { token: 'punctuation.definition.comment.vala', regex: '/\\*\\*/' }, { include: 'text.html.javadoc' }, { include: '#comments-inline' } ], '#comments-inline': [ { token: 'punctuation.definition.comment.vala', regex: '/\\*', push: [ { token: 'punctuation.definition.comment.vala', regex: '\\*/', next: 'pop' }, { defaultToken: 'comment.block.vala' } ] }, { token: [ 'text', 'punctuation.definition.comment.vala', 'comment.line.double-slash.vala' ], regex: '(\\s*)(//)(.*$)' } ], '#constants-and-special-vars': [ { token: 'constant.language.vala', regex: '\\b(?:true|false|null)\\b' }, { token: 'variable.language.vala', regex: '\\b(?:this|base)\\b' }, { token: 'constant.numeric.vala', regex: '\\b(?:0(?:x|X)[0-9a-fA-F]*|(?:[0-9]+\\.?[0-9]*|\\.[0-9]+)(?:(?:e|E)(?:\\+|-)?[0-9]+)?)(?:[LlFfUuDd]|UL|ul)?\\b' }, { token: [ 'keyword.operator.dereference.vala', 'constant.other.vala' ], regex: '((?:\\.)?)\\b([A-Z][A-Z0-9_]+)(?!<|\\.class|\\s*\\w+\\s*=)\\b' } ], '#enums': [ { token: 'text', regex: '^(?=\\s*[A-Z0-9_]+\\s*(?:{|\\(|,))', push: [ { token: 'text', regex: '(?=;|})', next: 'pop' }, { token: 'constant.other.enum.vala', regex: '\\w+', push: [ { token: 'meta.enum.vala', regex: '(?=,|;|})', next: 'pop' }, { include: '#parens' }, { token: 'text', regex: '{', push: [ { token: 'text', regex: '}', next: 'pop' }, { include: '#class-body' } ] }, { defaultToken: 'meta.enum.vala' } ] } ] } ], '#keywords': [ { token: 'keyword.control.catch-exception.vala', regex: '\\b(?:try|catch|finally|throw)\\b' }, { token: 'keyword.control.vala', regex: '\\?|:|\\?\\?' }, { token: 'keyword.control.vala', regex: '\\b(?:return|break|case|continue|default|do|while|for|foreach|switch|if|else|in|yield|get|set|value)\\b' }, { token: 'keyword.operator.vala', regex: '\\b(?:typeof|is|as)\\b' }, { token: 'keyword.operator.comparison.vala', regex: '==|!=|<=|>=|<>|<|>' }, { token: 'keyword.operator.assignment.vala', regex: '=' }, { token: 'keyword.operator.increment-decrement.vala', regex: '\\-\\-|\\+\\+' }, { token: 'keyword.operator.arithmetic.vala', regex: '\\-|\\+|\\*|\\/|%' }, { token: 'keyword.operator.logical.vala', regex: '!|&&|\\|\\|' }, { token: 'keyword.operator.dereference.vala', regex: '\\.(?=\\S)', originalRegex: '(?<=\\S)\\.(?=\\S)' }, { token: 'punctuation.terminator.vala', regex: ';' }, { token: 'keyword.operator.ownership', regex: 'owned|unowned' } ], '#methods': [ { token: 'meta.method.vala', regex: '(?!new)(?=\\w.*\\s+)(?=[^=]+\\()', push: [ { token: 'paren.vala', regex: '}|(?=;)', next: 'pop' }, { include: '#storage-modifiers' }, { token: [ 'entity.name.function.vala', 'meta.method.identifier.vala' ], regex: '([\\~\\w\\.]+)(\\s*\\()', push: [ { token: 'meta.method.identifier.vala', regex: '\\)', next: 'pop' }, { include: '#parameters' }, { defaultToken: 'meta.method.identifier.vala' } ] }, { token: 'meta.method.return-type.vala', regex: '(?=\\w.*\\s+\\w+\\s*\\()', push: [ { token: 'meta.method.return-type.vala', regex: '(?=\\w+\\s*\\()', next: 'pop' }, { include: '#all-types' }, { defaultToken: 'meta.method.return-type.vala' } ] }, { include: '#throws' }, { token: 'paren.vala', regex: '{', push: [ { token: 'paren.vala', regex: '(?=})', next: 'pop' }, { include: '#code' }, { defaultToken: 'meta.method.body.vala' } ] }, { defaultToken: 'meta.method.vala' } ] } ], '#namespace': [ { token: 'text', regex: '^(?=\\s*[A-Z0-9_]+\\s*(?:{|\\(|,))', push: [ { token: 'text', regex: '(?=;|})', next: 'pop' }, { token: 'constant.other.namespace.vala', regex: '\\w+', push: [ { token: 'meta.namespace.vala', regex: '(?=,|;|})', next: 'pop' }, { include: '#parens' }, { token: 'text', regex: '{', push: [ { token: 'text', regex: '}', next: 'pop' }, { include: '#code' } ] }, { defaultToken: 'meta.namespace.vala' } ] } ], comment: 'This is not quite right. See the class grammar right now' } ], '#object-types': [ { token: 'storage.type.generic.vala', regex: '\\b(?:[a-z]\\w*\\.)*[A-Z]+\\w*<', push: [ { token: 'storage.type.generic.vala', regex: '>|[^\\w\\s,\\?<\\[()\\]]', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '>|[^\\w\\s,\\?<\\[(?:[,]+)\\]]', next: 'pop' }, { include: '#object-types' }, { token: 'storage.type.generic.vala', regex: '<', push: [ { token: 'storage.type.generic.vala', regex: '>|[^\\w\\s,\\[\\]<]', next: 'pop' }, { defaultToken: 'storage.type.generic.vala' } ], comment: 'This is just to support <>\'s with no actual type prefix' }, { defaultToken: 'storage.type.generic.vala' } ] }, { token: 'storage.type.object.array.vala', regex: '\\b(?:[a-z]\\w*\\.)*[A-Z]+\\w*(?=\\[)', push: [ { token: 'storage.type.object.array.vala', regex: '(?=[^\\]\\s])', next: 'pop' }, { token: 'text', regex: '\\[', push: [ { token: 'text', regex: '\\]', next: 'pop' }, { include: '#code' } ] }, { defaultToken: 'storage.type.object.array.vala' } ] }, { token: [ 'storage.type.vala', 'keyword.operator.dereference.vala', 'storage.type.vala' ], regex: '\\b(?:([a-z]\\w*)(\\.))*([A-Z]+\\w*\\b)' } ], '#object-types-inherited': [ { token: 'entity.other.inherited-class.vala', regex: '\\b(?:[a-z]\\w*\\.)*[A-Z]+\\w*<', push: [ { token: 'entity.other.inherited-class.vala', regex: '>|[^\\w\\s,<]', next: 'pop' }, { include: '#object-types' }, { token: 'storage.type.generic.vala', regex: '<', push: [ { token: 'storage.type.generic.vala', regex: '>|[^\\w\\s,<]', next: 'pop' }, { defaultToken: 'storage.type.generic.vala' } ], comment: 'This is just to support <>\'s with no actual type prefix' }, { defaultToken: 'entity.other.inherited-class.vala' } ] }, { token: [ 'entity.other.inherited-class.vala', 'keyword.operator.dereference.vala', 'entity.other.inherited-class.vala' ], regex: '\\b(?:([a-z]\\w*)(\\.))*([A-Z]+\\w*)' } ], '#parameters': [ { token: 'storage.modifier.vala', regex: 'final' }, { include: '#primitive-arrays' }, { include: '#primitive-types' }, { include: '#object-types' }, { token: 'variable.parameter.vala', regex: '\\w+' } ], '#parens': [ { token: 'text', regex: '\\(', push: [ { token: 'text', regex: '\\)', next: 'pop' }, { include: '#code' } ] } ], '#primitive-arrays': [ { token: 'storage.type.primitive.array.vala', regex: '\\b(?:bool|byte|sbyte|char|decimal|double|float|int|uint|long|ulong|object|short|ushort|string|void|int8|int16|int32|int64|uint8|uint16|uint32|uint64)(?:\\[\\])*\\b' } ], '#primitive-types': [ { token: 'storage.type.primitive.vala', regex: '\\b(?:var|bool|byte|sbyte|char|decimal|double|float|int|uint|long|ulong|object|short|ushort|string|void|signal|int8|int16|int32|int64|uint8|uint16|uint32|uint64)\\b', comment: 'var is not really a primitive, but acts like one in most cases' } ], '#storage-modifiers': [ { token: 'storage.modifier.vala', regex: '\\b(?:public|private|protected|internal|static|final|sealed|virtual|override|abstract|readonly|volatile|dynamic|async|unsafe|out|ref|weak|owned|unowned|const)\\b', comment: 'Not sure about unsafe and readonly' } ], '#strings': [ { token: 'punctuation.definition.string.begin.vala', regex: '@"', push: [ { token: 'punctuation.definition.string.end.vala', regex: '"', next: 'pop' }, { token: 'constant.character.escape.vala', regex: '\\\\.|%[\\w\\.\\-]+|\\$(?:\\w+|\\([\\w\\s\\+\\-\\*\\/]+\\))' }, { defaultToken: 'string.quoted.interpolated.vala' } ] }, { token: 'punctuation.definition.string.begin.vala', regex: '"', push: [ { token: 'punctuation.definition.string.end.vala', regex: '"', next: 'pop' }, { token: 'constant.character.escape.vala', regex: '\\\\.' }, { token: 'constant.character.escape.vala', regex: '%[\\w\\.\\-]+' }, { defaultToken: 'string.quoted.double.vala' } ] }, { token: 'punctuation.definition.string.begin.vala', regex: '\'', push: [ { token: 'punctuation.definition.string.end.vala', regex: '\'', next: 'pop' }, { token: 'constant.character.escape.vala', regex: '\\\\.' }, { defaultToken: 'string.quoted.single.vala' } ] }, { token: 'punctuation.definition.string.begin.vala', regex: '"""', push: [ { token: 'punctuation.definition.string.end.vala', regex: '"""', next: 'pop' }, { token: 'constant.character.escape.vala', regex: '%[\\w\\.\\-]+' }, { defaultToken: 'string.quoted.triple.vala' } ] } ], '#throws': [ { token: 'storage.modifier.vala', regex: 'throws', push: [ { token: 'meta.throwables.vala', regex: '(?={|;)', next: 'pop' }, { include: '#object-types' }, { defaultToken: 'meta.throwables.vala' } ] } ], '#values': [ { include: '#strings' }, { include: '#object-types' }, { include: '#constants-and-special-vars' } ] };; this.normalizeRules(); }; ValaHighlightRules.metaData = { comment: 'Based heavily on the Java bundle\'s language syntax. TODO:\n* Closures\n* Delegates\n* Properties: Better support for properties.\n* Annotations\n* Error domains\n* Named arguments\n* Array slicing, negative indexes, multidimensional\n* construct blocks\n* lock blocks?\n* regex literals\n* DocBlock syntax highlighting. (Currently importing javadoc)\n* Folding rule for comments.\n', fileTypes: [ 'vala' ], foldingStartMarker: '(\\{\\s*(//.*)?$|^\\s*// \\{\\{\\{)', foldingStopMarker: '^\\s*(\\}|// \\}\\}\\}$)', name: 'Vala', scopeName: 'source.vala' };; oop.inherits(ValaHighlightRules, TextHighlightRules); exports.ValaHighlightRules = ValaHighlightRules; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string|escape/.test(token.type); var stringAfter = !rightToken || /string|escape/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/vala",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/vala_highlight_rules","ace/mode/folding/cstyle","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/mode/matching_brace_outdent"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ValaHighlightRules = require("./vala_highlight_rules").ValaHighlightRules; var FoldMode = require("./folding/cstyle").FoldMode; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Mode = function() { this.HighlightRules = ValaHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.$id = "ace/mode/vala" }).call(Mode.prototype); exports.Mode = Mode; });
describe('Eraser Method TEST', function() { describe('Eraser.prototype.getX', function() { // Positive it('should return 0.5', function() { var eraser = new Eraser(new Mocks.ArtCanvas.Point(0.5, 1)); expect(eraser.getX()).toEqual(0.5); }); // Negative it('should return 0', function() { var eraser = new Eraser(null); expect(eraser.getX()).toEqual(0); }); }); });
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'cert'; var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })();
function priceFilter(price) { if (!price) { return null } if (price.value) { return price.value } return Number( String(price) .trim() .replace(/^Kr\.\s*/, '') .replace(/\s*kr/i, '') .replace(/\./g, '') .replace(/,-$/, '') .replace(/,/g, '.') .replace(/\s/g, '') .replace(/(\d+(\.\d*)?)[\s\S]*/, '$1') ) } module.exports = priceFilter
console.log("Begin NodeFindBall"); var lwip = require('lwip'); lwip.open('ballimage.jpg', function(err, image){ var batch = image.batch(); for(var i = 1; i < image.width()-1; i+=1) { for(var j = 1; j < image.height()-1; j+=1) { var tolerance = 5; var previousTop = image.getPixel(i-1,j-1).r; var previousBottom = image.getPixel(i-1,j+1).r; var nextTop = image.getPixel(i+1,j-1).r; var nextBottom = image.getPixel(i+1,j+1).r; var current = image.getPixel(i, j).r; if(previousTop - current > tolerance || nextTop - current > tolerance || previousBottom - current > tolerance || nextBottom - current > tolerance ) { batch.setPixel(i, j, "red"); } } } batch.writeFile('output.jpg', function(err, image){ // do stuff }); });
self.port.emit("performance/timing", window.performance.timing); self.port.emit("dom", window.performance);
import React, { PropTypes } from 'react'; const ProductRow = ({ data }) => <div> <p>{data.name} = {data.price} </p> </div>; ProductRow.propTypes = { data: PropTypes.object }; export default ProductRow;
/* * Rebate Bus Client API demo * * Note that the AJAX should be run server side in production applications. It only works on demo.rebatebus.com because the * Rebate Bus server sets the Access-Control-Allow-Origin header on requests from that domain. Including it here so that the * entire API process will be visible in this demo. * * Also note that stealing this API key and UID won't do you much good - they're tied to the products in the inventory managed by user 1 * Feel free to use this API key and UID with these products to develop and debug your own apps. * * Mitch Vogel, 9/30/16 */ var API_KEY = "VmOJXmww6eBGT3XW"; var PUB_API_KEY = "EUrkzJacyAeSnH5f"; var initial_price1 = 5.99; var initial_price2 = 111.99; var UID = 1; var bus = { downstream: {}, midstream: {}, utilityDict: {} }; var TEST_REBATE_ID = 5401; var TEST_PRODUCT_ID1 = 1013; var TEST_PRODUCT_ID2 = 1001; var MIDSTREAM_UID = 129; function getUtilities() { $.ajax({ type: "POST", url: "https://www.rebatebus.com/api/getutilities", data: {"uid": UID, "apikey": API_KEY}, crossDomain: true, complete: function(response, stat) { bus.utilityDict = JSON.parse(response.responseText); getRebates(); }, error: function(response, stat) { console.log("error retrieving utilities data from Rebate Bus"); } }); } function getRebates() { $.ajax({ type: "POST", url: "https://www.rebatebus.com/api/getrebates", data: {"uid": UID, "apikey": API_KEY}, crossDomain: true, complete: function(response, stat) { var rebates = JSON.parse(response.responseText); bus.downstream = rebates.downstream; bus.midstream = rebates.midstream; localizeRebateOffers(); }, error: function(response, stat) { console.log("error retrieving rebates data from Rebate Bus"); } }); } /* * Infer a local program by finding the programid at the closest zip code to the geolocated location * After the program has been identified, call setProgramRebates to localize the page to this program */ function localizeRebateOffers() { var curProgramId; var curUtility; var closestProgram = -1; var closestDifference = 999999999; var curDifference; var curLatDiff, curLngDiff; var i, j; var browseProgramId; var applicablePrograms = []; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { for (curProgramId in bus.utilityDict) { for (i = 0; i < bus.utilityDict[curProgramId].length; i++) { curUtility = bus.utilityDict[curProgramId][i]; if (curUtility.zips) { for (j = 0; j < curUtility.zips.length; j++) { curLatDiff = (curUtility.zips[j].latitude - position.coords.latitude); curLngDiff = (curUtility.zips[j].longitude - position.coords.longitude); curDifference = curLatDiff * curLatDiff + curLngDiff * curLngDiff; if (curDifference < closestDifference) { closestProgram = curProgramId; closestDifference = curDifference; } } } } } if (closestProgram < 0) { alert("Geolocation failed - rebate demos will not work properly"); } else { setProgramRebates(closestProgram); } }); } else { alert("Geolocation is not supported by this browser - rebate demos will not work properly!"); } } /* * Here we have identified closestProgram as a rebate program with offerings in the inferred zip code * * Now alter the displayed prices and discounts to reflect those available in closestProgram */ function setProgramRebates(closestProgram) { var i, j; var found; var curProduct; var maxIncentive; for (j = 0; j < bus.downstream.length; j++) { curProduct = bus.downstream[j]; rebatemap({'utilityDict': bus.utilityDict, 'rebates': bus.downstream}, curProduct.productid, curProduct.productid + 'map'); found = 0; maxIncentive = {"rebateAmount": -1}; // Look for a prescriptive incentive, then a custom. for (i = 0; i < curProduct.rebates.prescriptive.length; i++) { if (curProduct.rebates.prescriptive[i].programid == closestProgram) { if (curProduct.rebates.prescriptive[i].rebateAmount > maxIncentive.rebateAmount) { maxIncentive = curProduct.rebates.prescriptive[i]; found = 1; } } } for (i = 0; i < curProduct.rebates.custom.length; i++) { if (curProduct.rebates.custom[i].programid == closestProgram) { if (curProduct.rebates.custom[i].rebateAmount > maxIncentive.rebateAmount) { maxIncentive = curProduct.rebates.custom[i]; found = 1; } } } if (found) { updateRebatePriceQuotes(curProduct.productid, maxIncentive); } } } /* * We've found a rebate that applies to productid in the program we're localizing to - update the DOM to reflect the discount */ function updateRebatePriceQuotes(productid, incentive) { $("#" + productid + " .pric1").append("<del>$" + incentive.msrp + "</del>"); $("#" + productid + " .pric2").text("$" + (incentive.msrp - incentive.rebateAmount).toFixed(2)); $("#" + productid + " .disc").text("$" + incentive.rebateAmount.toFixed(2) + " rebate from " + incentive.program); } function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } window.onload = function() { getUtilities(); MidstreamWidget.configure({ "uid": UID, "apikey": PUB_API_KEY, "products": [TEST_PRODUCT_ID1,TEST_PRODUCT_ID2], "verified": function(data) { $("#discount-label").val("Rebate Amount:"); var totalRebate = 0; for (var datidx = 0; datidx < data.length; datidx++) { totalRebate += data[datidx].amount; } $("#discount-value").val("$" + totalRebate); $("#final-price").val((initial_price1 + initial_price2) - totalRebate); } }); $("#initial-price").val("$" + (initial_price1 + initial_price2)); $("#final-price").val("$" + (initial_price1 + initial_price2)); }
/** * SVGTransformList * * Licensed under the Apache License, Version 2 * * Copyright(c) 2010 Alexis Deveria * Copyright(c) 2010 Jeff Schiller */ // Dependencies: // 1) browser.js var svgedit = svgedit || {}; (function() { if (!svgedit.transformlist) { svgedit.transformlist = {}; } var svgroot = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); // Helper function. function transformToString(xform) { var m = xform.matrix, text = ""; switch(xform.type) { case 1: // MATRIX text = "matrix(" + [m.a,m.b,m.c,m.d,m.e,m.f].join(",") + ")"; break; case 2: // TRANSLATE text = "translate(" + m.e + "," + m.f + ")"; break; case 3: // SCALE if (m.a == m.d) text = "scale(" + m.a + ")"; else text = "scale(" + m.a + "," + m.d + ")"; break; case 4: // ROTATE var cx = 0, cy = 0; // this prevents divide by zero if (xform.angle != 0) { var K = 1 - m.a; cy = ( K * m.f + m.b*m.e ) / ( K*K + m.b*m.b ); cx = ( m.e - m.b * cy ) / K; } text = "rotate(" + xform.angle + " " + cx + "," + cy + ")"; break; } return text; }; /** * Map of SVGTransformList objects. */ var listMap_ = {}; // ************************************************************************************** // SVGTransformList implementation for Webkit // These methods do not currently raise any exceptions. // These methods also do not check that transforms are being inserted. This is basically // implementing as much of SVGTransformList that we need to get the job done. // // interface SVGEditTransformList { // attribute unsigned long numberOfItems; // void clear ( ) // SVGTransform initialize ( in SVGTransform newItem ) // SVGTransform getItem ( in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR) // SVGTransform insertItemBefore ( in SVGTransform newItem, in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR) // SVGTransform replaceItem ( in SVGTransform newItem, in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR) // SVGTransform removeItem ( in unsigned long index ) (DOES NOT THROW DOMException, INDEX_SIZE_ERR) // SVGTransform appendItem ( in SVGTransform newItem ) // NOT IMPLEMENTED: SVGTransform createSVGTransformFromMatrix ( in SVGMatrix matrix ); // NOT IMPLEMENTED: SVGTransform consolidate ( ); // } // ************************************************************************************** svgedit.transformlist.SVGTransformList = function(elem) { this._elem = elem || null; this._xforms = []; // TODO: how do we capture the undo-ability in the changed transform list? this._update = function() { var tstr = ""; var concatMatrix = svgroot.createSVGMatrix(); for (var i = 0; i < this.numberOfItems; ++i) { var xform = this._list.getItem(i); tstr += transformToString(xform) + " "; } this._elem.setAttribute("transform", tstr); }; this._list = this; this._init = function() { // Transform attribute parser var str = this._elem.getAttribute("transform"); if(!str) return; // TODO: Add skew support in future var re = /\s*((scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/; var arr = []; var m = true; while(m) { m = str.match(re); str = str.replace(re,''); if(m && m[1]) { var x = m[1]; var bits = x.split(/\s*\(/); var name = bits[0]; var val_bits = bits[1].match(/\s*(.*?)\s*\)/); val_bits[1] = val_bits[1].replace(/(\d)-/g, "$1 -"); var val_arr = val_bits[1].split(/[, ]+/); var letters = 'abcdef'.split(''); var mtx = svgroot.createSVGMatrix(); $.each(val_arr, function(i, item) { val_arr[i] = parseFloat(item); if(name == 'matrix') { mtx[letters[i]] = val_arr[i]; } }); var xform = svgroot.createSVGTransform(); var fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1); var values = name=='matrix'?[mtx]:val_arr; if (name == 'scale' && values.length == 1) { values.push(values[0]); } else if (name == 'translate' && values.length == 1) { values.push(0); } else if (name == 'rotate' && values.length == 1) { values.push(0); values.push(0); } xform[fname].apply(xform, values); this._list.appendItem(xform); } } }; this._removeFromOtherLists = function(item) { if (item) { // Check if this transform is already in a transformlist, and // remove it if so. var found = false; for (var id in listMap_) { var tl = listMap_[id]; for (var i = 0, len = tl._xforms.length; i < len; ++i) { if(tl._xforms[i] == item) { found = true; tl.removeItem(i); break; } } if (found) { break; } } } }; this.numberOfItems = 0; this.clear = function() { this.numberOfItems = 0; this._xforms = []; }; this.initialize = function(newItem) { this.numberOfItems = 1; this._removeFromOtherLists(newItem); this._xforms = [newItem]; }; this.getItem = function(index) { if (index < this.numberOfItems && index >= 0) { return this._xforms[index]; } throw {code: 1}; // DOMException with code=INDEX_SIZE_ERR }; this.insertItemBefore = function(newItem, index) { var retValue = null; if (index >= 0) { if (index < this.numberOfItems) { this._removeFromOtherLists(newItem); var newxforms = new Array(this.numberOfItems + 1); // TODO: use array copying and slicing for ( var i = 0; i < index; ++i) { newxforms[i] = this._xforms[i]; } newxforms[i] = newItem; for ( var j = i+1; i < this.numberOfItems; ++j, ++i) { newxforms[j] = this._xforms[i]; } this.numberOfItems++; this._xforms = newxforms; retValue = newItem; this._list._update(); } else { retValue = this._list.appendItem(newItem); } } return retValue; }; this.replaceItem = function(newItem, index) { var retValue = null; if (index < this.numberOfItems && index >= 0) { this._removeFromOtherLists(newItem); this._xforms[index] = newItem; retValue = newItem; this._list._update(); } return retValue; }; this.removeItem = function(index) { if (index < this.numberOfItems && index >= 0) { var retValue = this._xforms[index]; var newxforms = new Array(this.numberOfItems - 1); for (var i = 0; i < index; ++i) { newxforms[i] = this._xforms[i]; } for (var j = i; j < this.numberOfItems-1; ++j, ++i) { newxforms[j] = this._xforms[i+1]; } this.numberOfItems--; this._xforms = newxforms; this._list._update(); return retValue; } else { throw {code: 1}; // DOMException with code=INDEX_SIZE_ERR } }; this.appendItem = function(newItem) { this._removeFromOtherLists(newItem); this._xforms.push(newItem); this.numberOfItems++; this._list._update(); return newItem; }; }; svgedit.transformlist.resetListMap = function() { listMap_ = {}; }; /** * Removes transforms of the given element from the map. * Parameters: * elem - a DOM Element */ svgedit.transformlist.removeElementFromListMap = function(elem) { if (elem.id && listMap_[elem.id]) { delete listMap_[elem.id]; } }; // Function: getTransformList // Returns an object that behaves like a SVGTransformList for the given DOM element // // Parameters: // elem - DOM element to get a transformlist from svgedit.transformlist.getTransformList = function(elem) { if (elem.transform) { return elem.transform.baseVal; } else if (elem.gradientTransform) { return elem.gradientTransform.baseVal; } else if (elem.patternTransform) { return elem.patternTransform.baseVal; } return null; }; })();
import { A } from '@ember/array'; import EmberObject from '@ember/object'; import IoMixin from '../../../mixins/io'; import AudioService from 'ember-audio/services/audio-service'; import { module, test } from 'qunit'; module('Unit | Mixin | io'); var audioService = AudioService.create(); test('it works', function(assert) { var IoObject = EmberObject.extend(IoMixin); var subject = IoObject.create(); assert.ok(subject); }); test('inputs and outputs are reset on init', function(assert) { assert.expect(2); const inputs = [1,2,3]; const outputs = [1,2,3]; var IoObject = EmberObject.extend(IoMixin, { inputs, outputs }); var subject = IoObject.create(); assert.equal(subject.get('inputs.length'), 0, 'inputs.length should be 0'); assert.equal(subject.get('outputs.length'), 0, 'outputs.length should be 0'); }); test('connect method', function(assert) { assert.expect(3); var IoObject = EmberObject.extend(IoMixin, { processor: { connect: function (obj) { assert.ok(true, `'processor.connect' method has been called`); assert.equal(obj.name, 'output', `processor is connected to output`); } } }); var subject = IoObject.create(); subject.connect({name: 'output'}); assert.ok(subject); }); test('disconnect method', function(assert) { assert.expect(3); var IoObject = EmberObject.extend(IoMixin, { processor: { name: 'processor', disconnect: function (obj) { assert.ok(true, `'processor.disconnect' method has been called`); assert.equal(obj.name, 'output', `processor is disconnected from output`); } } }); var subject = IoObject.create(); subject.disconnect({name: 'output'}); assert.ok(subject); }); test('registerInput method', function(assert) { assert.expect(7); var source1 = audioService.createGain({id:1}); var source2 = audioService.createGain({id:2}); var IoObject = EmberObject.extend(IoMixin, { inputs: A() }); var subject = IoObject.create(); assert.equal(subject.get('inputs.length'), 0, 'inputs.length should be 0'); subject.registerInput(source1, 3); assert.equal(subject.get('inputs.length'), 1, 'inputs.length should be 1'); assert.equal(subject.get('inputs').objectAt(0).get('node.id'), 1, 'inputs[0].node.id should be 1'); assert.equal(subject.get('inputs').objectAt(0).get('output'), 3, 'inputs[0].output should be 3'); subject.registerInput(source2, 0); assert.equal(subject.get('inputs.length'), 2, 'inputs.length should be 1'); assert.equal(subject.get('inputs').objectAt(1).get('node.id'), 2, 'inputs[1].node.id should be 1'); assert.equal(subject.get('inputs').objectAt(1).get('output'), 0, 'inputs[1].output should be 0'); }); test('unregisterInput method', function(assert) { assert.expect(7); var source1 = audioService.createGain({id:1}); var source2 = audioService.createGain({id:2}); var IoObject = EmberObject.extend(IoMixin, { inputs: A() }); var subject = IoObject.create(); assert.equal(subject.get('inputs.length'), 0, 'inputs.length should be 0'); subject.registerInput(source1, 3); assert.equal(subject.get('inputs.length'), 1, 'inputs.length should be 1'); assert.equal(subject.get('inputs').findBy('node', source1).get('output'), 3); subject.registerInput(source2, 0); assert.equal(subject.get('inputs.length'), 2, 'inputs.length should be 1'); subject.unregisterInput(source1); assert.equal(subject.get('inputs.length'), 1, 'inputs.length should be 1'); assert.equal(subject.get('inputs').findBy('node', source2).get('output'), 0); subject.unregisterInput(source2); assert.equal(subject.get('inputs.length'), 0, 'inputs.length should be 0'); }); test('connectOutput method - pass audioNode', function(assert) { assert.expect(5); var destination = audioService.createGain(); var processor = destination.get('processor'); processor.id = 1; var IoObject = EmberObject.extend(IoMixin, { outputs: [], connectNode: function (obj) { assert.ok(true, `'input.connect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 1, `'obj.id' is 1`); assert.equal(obj.gain.value, 1, `'obj.gain.value' should be 1`); }, disconnect: function () { assert.ok(true, `'input.disconnect' method has been called`); } }); var subject = IoObject.create(); subject.connectOutput(destination.get('processor')); assert.equal(subject.get('outputs')[0].id, 1, 'outputs[0].id should be 1'); }); test('connectOutput method calls registerInput', function(assert) { assert.expect(3); var destination = audioService.createGain(); var IoObject = EmberObject.extend(IoMixin, { outputs: [] }); var subject = IoObject.create(); destination.set('registerInput', (outputNode, outputNumber) => { assert.ok(true, `'registerInput' method was called`); assert.equal(outputNode, subject, `'outputNode' should be 'subject'`); assert.equal(outputNumber, 0, `'outputNumber' should be 0`); }); subject.connectOutput(destination); }); test('disconnectOutput method calls unregisterInput', function(assert) { assert.expect(2); var destination = audioService.createGain(); var IoObject = EmberObject.extend(IoMixin, { outputs: [] }); var subject = IoObject.create(); destination.set('unregisterInput', (node) => { assert.ok(true, `'registerInput' method was called`); assert.equal(node, subject, `'node' should be 'subject'`); }); subject.connectOutput(destination); subject.disconnectOutput(destination); }); test('connectOutput method does not break when audioNode is passed in', function(assert) { assert.expect(1); var destination = audioService.createGain(); var IoObject = EmberObject.extend(IoMixin, { outputs: [] }); var subject = IoObject.create(); subject.connectOutput(destination.get('processor')); assert.ok(subject); }); test('disconnectOutput method does not break when audioNode is passed in', function(assert) { assert.expect(1); var destination = audioService.createGain(); var IoObject = EmberObject.extend(IoMixin, { outputs: [] }); var subject = IoObject.create(); subject.connectOutput(destination.get('processor')); subject.disconnectOutput(destination.get('processor')); assert.ok(subject); }); test('connectOutput method - pass object instead of audioNode', function(assert) { assert.expect(5); var destination = audioService.createGain({id:1}); var processor = destination.get('processor'); processor.id = 2; var IoObject = EmberObject.extend(IoMixin, { outputs: [], connectNode: function (obj) { assert.ok(true, `'input.connect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 1, `'obj.id' is 1`); assert.equal(obj.get('processor.gain.value'), 1, `'obj.gain.value' should be 1`); }, disconnect: function () { assert.ok(true, `'input.disconnect' method has been called`); } }); var subject = IoObject.create(); subject.connectOutput(destination); assert.equal(subject.get('outputs')[0].get('id'), 1, 'outputs[0].id should be 1'); }); test('connectOutput method - check destination inputs reference', function(assert) { assert.expect(4); var destination = audioService.createGain(); var IoObject = EmberObject.extend(IoMixin); var subject = IoObject.create(); subject.connectOutput(destination, 2); var output = subject.get('outputs')[2]; assert.equal(output, destination, `'output' should be 'destination'`); assert.equal(output.get('inputs.firstObject.node'), subject, `'inputs.firstObject.node' should be 'destination'`); assert.equal(output.get('inputs.firstObject.output'), 2, `'inputs.firstObject.output' should be 2`); assert.equal(output.get('inputs').findBy('output', 2).get('node'), subject); }); test('connectOutput method - pass null', function(assert) { assert.expect(4); var destination = audioService.createGain({id:1}); var IoObject = EmberObject.extend(IoMixin, { outputs: [] }); var subject = IoObject.create(); subject.connectOutput(destination); assert.equal(subject.get('outputs.length'), 1, 'outputs.length should be 1'); assert.equal(subject.get('outputs')[0].id, 1, 'outputs[0].id should be 1'); subject.connectOutput(); assert.equal(subject.get('outputs.length'), 1, 'outputs.length should be 1'); assert.equal(subject.get('outputs')[0], null, 'outputs[0] should be null'); }); test('connectOutput method - pass null, output 2', function(assert) { assert.expect(6); var destination1 = audioService.createGain(); var destination2 = audioService.createGain(); var destination3 = audioService.createGain(); var destination4 = audioService.createGain(); var IoObject = EmberObject.extend(IoMixin, { outputs: [] }); var subject = IoObject.create(); subject.connectOutput(destination1, 0); subject.connectOutput(destination2, 1); subject.connectOutput(destination3, 2); subject.connectOutput(destination4, 3); assert.equal(subject.get('outputs.length'), 4, 'outputs.length should be 4'); // assert.equal(subject.get('outputs')[0].id, 1, 'outputs[0].id should be 1'); subject.connectOutput(null, 2); assert.equal(subject.get('outputs.length'), 4, 'outputs.length should be 4'); assert.ok(subject.get('outputs')[0], 'outputs[0] should not be null'); assert.ok(subject.get('outputs')[1], 'outputs[1] should not be null'); assert.equal(subject.get('outputs')[2], null, 'outputs[2] should be null'); assert.ok(subject.get('outputs')[3], 'outputs[3] should not be null'); }); test('connectOutput method disconnects existing output at same index', function(assert) { assert.expect(8); var IoObject = EmberObject.extend(IoMixin, { outputs: [], connect: function (obj) { assert.ok(true, `'input.connect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 2, `'obj.id' should be 2`); }, disconnect: function (obj) { assert.ok(true, `'input.disconnect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 1, `'obj.id' should be 1`); } }); var subject = IoObject.create(); subject.set('outputs', [{id:1}]); assert.equal(subject.get('outputs')[0].id, 1, 'outputs[0].id should be 1'); subject.connectOutput({id:2}); assert.equal(subject.get('outputs')[0].id, 2, 'outputs[0].id should be 2'); }); test('connectOutput method does not disconnect other outputs', function(assert) { assert.expect(12); var IoObject = EmberObject.extend(IoMixin, { connect: function (obj) { assert.ok(true, `'input.connect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 4, `'obj.id' should be 4`); }, disconnect: function (obj) { assert.ok(true, `'input.disconnect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 2, `'obj.id' should be 2`); } }); var subject = IoObject.create(); subject.set('outputs', [ {id:1}, {id:2}, {id:3} ]); assert.equal(subject.get('outputs')[0].id, 1, 'outputs[0].id should be 1'); assert.equal(subject.get('outputs')[1].id, 2, 'outputs[1].id should be 2'); assert.equal(subject.get('outputs')[2].id, 3, 'outputs[2].id should be 3'); subject.connectOutput({id:4}, 1); assert.equal(subject.get('outputs')[0].id, 1, 'outputs[0].id should be 1'); assert.equal(subject.get('outputs')[1].id, 4, 'outputs[1].id should be 4'); assert.equal(subject.get('outputs')[2].id, 3, 'outputs[2].id should be 3'); }); test('disconnectOutput method', function(assert) { assert.expect(3); var destination = audioService.createGain(); var processor = destination.get('processor'); processor.id = 1; var IoObject = EmberObject.extend(IoMixin, { outputs: [], disconnectNode: function () { assert.ok(true, `'input.disconnectNode' method has been called`); } }); var subject = IoObject.create(); subject.connectOutput(destination.get('processor')); assert.equal(subject.get('outputs')[0].id, 1, 'outputs[0].id should be 1'); subject.disconnectOutput(); assert.equal(subject.get('outputs')[0], null, 'outputs[0] should be null'); }); test('connectNode method', function(assert) { assert.expect(4); var destination = audioService.createGain(); var processor = destination.get('processor'); processor.id = 1; var IoObject = EmberObject.extend(IoMixin, { outputs: [], connect: function (obj) { assert.ok(true, `'input.connect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 1, `'obj.id' is 1`); assert.equal(obj.gain.value, 1, `'obj.gain.value' should be 1`); } }); var subject = IoObject.create(); subject.connectNode(destination.get('processor')); }); test('disconnectNode method', function(assert) { assert.expect(4); var destination = audioService.createGain(); var processor = destination.get('processor'); processor.id = 1; var IoObject = EmberObject.extend(IoMixin, { outputs: [], disconnect: function (obj) { assert.ok(true, `'input.disconnect' method has been called`); assert.equal(typeof obj, 'object', `typeof 'obj' is an object`); assert.equal(obj.id, 1, `'obj.id' is 1`); assert.equal(obj.gain.value, 1, `'obj.gain.value' should be 1`); } }); var subject = IoObject.create(); subject.disconnectNode(destination.get('processor')); }); // test('bypassProcessor method', function(assert) { // assert.expect(5); // var source = audioService.createGain({name: 'source'}); // var destination = audioService.createGain({id:1}); // var processor = destination.get('processor'); // processor.id = 2; // // var bypassNode = { // name: 'bypassNode', // connect: function (node) { // assert.ok(true, `'connect' method has been called`); // assert.equal(node.get('name'), 'destination', `'node.name' should be 'destination'`); // }, // }; // // var IoObject = Ember.Object.extend(IoMixin, { // outputs: [], // bypassNode: bypassNode, // processor: audioService.get('audioContext').createGain(), // inputChanged: Ember.observer('input', 'processor', function() { // this.changeInput(); // }) // }); // // var subject = IoObject.create(); // // source.connectOutput(subject); // subject.set('input', source); // subject.connectOutput(destination); // // source.set('connectOutput', (node) => { // assert.ok(true, `'connectOutput' method has been called`); // assert.equal(node.name, 'bypassNode', `'node.name' should be 'bypassNode'`); // }); // // assert.equal(subject.get('outputs')[0].get('id'), 1, 'outputs[0].id should be 1'); // // subject.bypassProcessor(true); // }); test('changeInput method', function (assert) { assert.expect(3); var input = audioService.createGain({id:1}); var gain = audioService.get('audioContext').createGain({id:2}); var IoObject = EmberObject.extend(IoMixin); var subject = IoObject.create({ input: input }); subject.set('processor', gain); input.set('connectOutput', (obj) => { assert.ok(true, `'connectOutput' method has been called`); assert.equal(obj.get('processor.gain.value'), 1, `'obj.gain.value' should be 1`); }); subject.changeInput(); assert.ok(subject); }); test('changeOutput method', function (assert) { assert.expect(3); var IoObject = EmberObject.extend(IoMixin, { output: {id:1}, connectOutput: function (obj) { assert.ok(true, `'connectOutput' method has been called`); assert.equal(obj.id, 1, `obj.id should be 1`); } }); var subject = IoObject.create(); subject.changeOutput(); assert.ok(subject); });
define(function(require, exports, module) { "use strict"; //Includes Famous Repositories var Engine = require('famous/core/Engine'); var Surface = require('famous/core/Surface'); var RenderNode = require("famous/core/RenderNode"); var Modifier = require("famous/core/Modifier"); var Transform = require("famous/core/Transform"); var View = require("famous/core/View"); var Rectangle = require("famous/physics/bodies/Rectangle"); var PhysicsEngineFactory = require("app/PhysicsEngineFactory"); var Plant = require("app/Plant"); /** @constructor */ function Pipe(options){ View.apply(this, arguments); _create.call(this); }; Pipe.prototype = Object.create(View.prototype); Pipe.prototype.constructor = Pipe; Pipe.DEFAULT_OPTIONS = { velocity : -.3, pipeHeight : 480, pipeWidth : 113, initPipePos : 700 }; function _create(){ this.physicsEngine = PhysicsEngineFactory.getEngine(); var pipeSizeAndPos = _calcPipePositionAndSize.call(this); var upperPipe = pipeSizeAndPos[0]; var lowerPipe = pipeSizeAndPos[1]; this.surfaces = [ new Surface({ size : [this.options.pipeWidth, upperPipe.height], classes : ['pipe','upper', 'unselectable'] }), new Surface({ size : [this.options.pipeWidth, lowerPipe.height], classes : ['pipe','lower'] }) ]; this.particles = [ //upper pipe new Rectangle({ mass: 0, size : [this.options.pipeWidth, upperPipe.height], position : [this.options.initPipePos, upperPipe.y, -2], velocity : [this.options.velocity,0,0] }), //lower pipe new Rectangle({ mass : 0, size : [this.options.pipeWidth, lowerPipe.height], position : [this.options.initPipePos, lowerPipe.y, -2], velocity : [this.options.velocity,0,0] }) ]; //set a property on the pipe used for scoring this.particles[0].pipeNumber = this.options.id; //create render nodes for the pipes this.pipeNodes = {}; this.pipeNodes["upper"] = new RenderNode(); this.pipeNodes["lower"] = new RenderNode(); this.pipeNodes["upper"].add(this.surfaces[0]); this.pipeNodes["lower"].add(this.surfaces[1]); //add the particles as modifiers //NOTE: It is important to add the origin modifier after adding the particle so that the //particle is in the middle of the surface this._add(this.particles[0]) .add(new Modifier({origin:[.5,.5]})) .add(this.pipeNodes["upper"]); this._add(this.particles[1]) .add(new Modifier({origin:[.5,.5]})) .add(this.pipeNodes["lower"]); //add the particles to the physics engine this.physicsEngine.addBody(this.particles[0]); this.physicsEngine.addBody(this.particles[1]); //pipe events so clicks on the pipes will bubble up this.surfaces[0].pipe(this._eventOutput); this.surfaces[1].pipe(this._eventOutput); //add the plants this.plants = {}; this.plants["upper"] = new Plant({ pipeHeight: upperPipe.height, type: "upper", particle: this.particles[0] }); this.plants["lower"] = new Plant({ pipeHeight: lowerPipe.height, type: "lower", particle: this.particles[1] }); this.pipeNodes["upper"].add(this.plants["upper"]); this.pipeNodes["lower"].add(this.plants["lower"]); this.plants["upper"].pipe(this._eventOutput); this.plants["lower"].pipe(this._eventOutput); _attack.call(this) }//end create Pipe.prototype.restart = function(opts){ var pipeSizeAndPos = _calcPipePositionAndSize.call(this); var upperPipe = pipeSizeAndPos[0]; var lowerPipe = pipeSizeAndPos[1]; //change the pipe number this.particles[0].pipeNumber = opts.id; //reset the pipes surface/particle size and position this.surfaces[0].size = [this.options.pipeWidth, upperPipe.height]; this.particles[0].setSize(this.surfaces[0].size); this.particles[0].setPosition([this.options.initPipePos, upperPipe.y, -2]); this.surfaces[1].size = [this.options.pipeWidth, lowerPipe.height]; this.particles[1].setSize(this.surfaces[1].size); this.particles[1].setPosition([this.options.initPipePos, lowerPipe.y, -2]); this.plants["upper"].restart(upperPipe.height); this.plants["lower"].restart(lowerPipe.height); _attack.call(this) }; function _attack(){ //reset the plants var threshold = 1;//a value of 1 turns off the plant attacks to start var currentPipe = this.particles[0].pipeNumber; //set the threshold if (currentPipe > 6) {threshold = .8}; if (currentPipe > 20) {threshold = .6}; if (currentPipe > 50) {threshold = .4}; if (currentPipe > 100) {threshold = .2}; if(Math.random() > threshold) {this.plants["upper"].attack();} if(Math.random() > threshold) {this.plants["lower"].attack();} } function _calcGapOffset(){ var gapHeight = -100 + Math.random() * 300; var gapDirection = (Math.random() * 100 % 2) == 0 ? -1: 1; return gapHeight * gapDirection; } function _calcPipePositionAndSize(){ var gapOffset = _calcGapOffset(); var upperPipeHeight = (this.options.pipeHeight-200) + gapOffset; var lowerPipeHeight = (this.options.pipeHeight-200) - gapOffset; var upperPipeYPos = upperPipeHeight/2; var lowerPipeYPos = 480 + gapOffset + lowerPipeHeight/2; return [ {height: upperPipeHeight, y: upperPipeYPos}, {height: lowerPipeHeight, y: lowerPipeYPos} ]; } module.exports = Pipe; });
function stringify(data) { return JSON.parse(JSON.stringify(data)); } /* A collection of db records i.e. a database table. */ class DbCollection { constructor(name, initialData) { this.name = name; this._records = []; if (initialData) { this.insert(initialData); } } /* Returns a copy of the data, to prevent inadvertant data manipulation. */ all() { return stringify(this._records); } insert(data) { let copy = data ? stringify(data) : {}; let records = this._records; let returnData; if (!_.isArray(copy)) { let attrs = copy; if (attrs.id === undefined || attrs.id === null) { attrs.id = records.length + 1; } records.push(attrs); returnData = stringify(attrs); } else { returnData = []; copy.forEach(data => { if (data.id === undefined || data.id === null) { data.id = records.length + 1; } records.push(data); returnData.push(data); returnData = returnData.map( r => stringify(r) ); }); } return returnData; } find(ids) { if (_.isArray(ids)) { let records = this._findRecords(ids) .filter(r => r !== undefined); // Return a copy return records.map(r => stringify(r) ); } else { let record = this._findRecord(ids); if (!record) { return null; } // Return a copy return stringify(record); } } where(query) { let records = this._findRecordsWhere(query); return records.map( r => stringify(r) ); } firstOrCreate(query, attributesForNew={}) { let queryResult = this.where(query); let record = queryResult[0]; if (record) { return record; } else { let mergedAttributes = _.assign(attributesForNew, query); let createdRecord = this.insert(mergedAttributes); return createdRecord; } } update(target, attrs) { let records; if (typeof attrs === 'undefined') { attrs = target; let changedRecords = []; this._records.forEach(function(record) { let oldRecord = _.assign({}, record); for (let attr in attrs) { record[attr] = attrs[attr]; } if (!_.isEqual(oldRecord, record)) { changedRecords.push(record); } }); return changedRecords; } else if (typeof target === 'number' || typeof target === 'string') { let id = target; let record = this._findRecord(id); for (let attr in attrs) { record[attr] = attrs[attr]; } return record; } else if (_.isArray(target)) { let ids = target; records = this._findRecords(ids); records.forEach(record => { for (let attr in attrs) { record[attr] = attrs[attr]; } }); return records; } else if (typeof target === 'object') { let query = target; records = this._findRecordsWhere(query); records.forEach(record => { for (let attr in attrs) { record[attr] = attrs[attr]; } }); return records; } } remove(target) { let records; if (typeof target === 'undefined') { this._records = []; } else if (typeof target === 'number' || typeof target === 'string') { let record = this._findRecord(target); let index = this._records.indexOf(record); this._records.splice(index, 1); } else if (_.isArray(target)) { records = this._findRecords(target); records.forEach(record => { let index = this._records.indexOf(record); this._records.splice(index, 1); }); } else if (typeof target === 'object') { records = this._findRecordsWhere(target); records.forEach(record => { let index = this._records.indexOf(record); this._records.splice(index, 1); }); } } /* Private methods. These return the actual db objects, whereas the public API query methods return copies. */ _findRecord(id) { let allDigitsRegex = /^\d+$/; // If parses, coerce to integer if (typeof id === 'string' && allDigitsRegex.test(id)) { id = parseInt(id, 10); } let record = this._records.filter(obj => obj.id === id)[0]; return record; } _findRecords(ids) { let records = ids.map(id => this._findRecord(id)); return records; } _findRecordsWhere(query) { let records = this._records; for (let queryKey in query) { records = records.filter( r => String(r[queryKey]) === String(query[queryKey]) ); } return records; } } export default DbCollection;
/** * Created by chenjianjun on 16/2/25. */ var env=require("../../../config"); var type=env.Thinky.type; // 婚礼租车--品牌 /* { "success": true, "message": null, "data": [ { "id": 4, "createTime": "2016-01-21 19:41:31", "updateTime": "2016-01-21 19:41:31", "operater": 1, "isUsed": 1, "name": "马自达", "description": "", "brandId": 4 } ], "code": 200, "count": 0 } * */ // 酒店类型模型 const FilterConditionCarBrand = env.Thinky.createModel('filterConditionCarBrand', { // Id id: type.number(), // 品牌ID brandId: type.number(), // 创建时间 createTime: type.string(), // 修改时间 updateTime: type.string(), // 操作员 operater: type.number(), // 是否有效 有效0:无效 1:有效 isUsed: type.number(), // 型号名 name: type.string(), // 描述 description: type.string() //// 权重 //weight: type.number() }) //FilterConditionCarBrand.ensureIndex('weight'); module.exports=FilterConditionCarBrand;
var Answer = require('../models/answer'); var User = require('../models/user'); var Question = require('../models/question'); var Tag = require('../models/tag'); var Badge = require('../models/badge'); var Favorite = require('../models/favorite'); var QuestionTag = require('../models/questiontag'); var Vote = require('../models/vote'); var nodemailer = require('nodemailer'); var randtoken = require('rand-token'); var async = require('async'); var crypto = require('crypto'); // Tạo đối tượng tái sử dụng transporter dùng SMTP transport var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'azquestion.com@gmail.com', pass: 'fit@dhcn123!@#' } }); var fs = require('fs'); module.exports = function (app, passport) { app.post('/api/user/upload/avatar',function(req, res) { var fstream; req.pipe(req.busboy); req.busboy.on('file', function (fieldname, file, filename) { console.log("Uploading: " + filename); var extension=(/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined; var strand= randtoken.generate(20); fstream = fs.createWriteStream('public/uploads/users/'+strand+'.'+ extension); file.pipe(fstream); fstream.on('close', function (err) { if(err) res.send(err); res.send(strand+'.'+extension); }); }); }); app.get('/api/user/edit/avatar/:avatar', function(req, res){ User.findById(req.user._id,function(err, user){ if(err) res.send(err); user.avatar="/uploads/users/"+req.params.avatar; user.save(function(err, user){ if(err) res.send(err); res.json(user); }); }); }); app.get('/api/user', function(req, res) { User.find(function(err, user){ if (err) res.send(err); res.json(user); }); }); // Get User Admin app.get('/api/admin',function(req,res) { User.find({role:'admin'}).select('_id').exec(function(err,user) { if(err) res.send(err); res.json(user); }); }); app.get('/api/people', function(req, res) { User.find({},'-_id displayName',function(err, user){ if (err) res.send(err); res.json(user); }); }); app.get('/api/countUser', function(req, res) { User.find({status: 1}).count(function(err, user){ if (err) res.send(err); res.json(user); }); }); app.get('/api/user/count/question/:user_id', function(req, res) { var id= req.params.user_id; Question.count({userId:id},function(err, c){ if (err) res.send(err); res.json(c); }); }); app.get('/api/user/count/answer/:user_id', function(req, res) { var id= req.params.user_id; Answer.count({userId:id},function(err, c){ if (err) res.send(err); res.json(c); }); }); app.get('/api/user/profile/:user_id', function(req, res) { User.findById(req.params.user_id,function(err, user){ if (err) res.send(err); res.json(user); }); }); app.delete('/api/user/delete/:user_id', function(req, res){ var id= req.params.user_id; if(id==req.user._id){ res.send({"error_msg":"Lỗi. Bạn không thể xóa chính mình."}); } else{ //Tìm tất cả các câu hỏi được đăng bởi thành viên này Question.find({userId: id}, function(err, questions){ if(err) res.send(err); questions.forEach(function(item){ QuestionTag.remove({questionId: item._id}, function(err, tags){ if(err) res.send(err); }); Answer.find({questionId: item._id}, function(err, answers){ answers.forEach(function(i){ Vote.remove({answerId: i._id}, function(err){ if(err) res.send(err); }); }); }); //Xóa tất cả các câu trả lời trong câu hỏi này Answer.remove({questionId: item._id}, function(err, answers){ if(err) res.send(err); }); Vote.remove({questionId: item._id}, function(err, vote){ if(err) res.send(err); }); Favorite.remove({questionId: item._id}, function(err, favorite){ if(err) res.send(err); }); }); }); //Sau khi loại bỏ hết các liên kết tới câu hỏi đó thì xóa nó Question.remove({userId: id}, function(err, questions){ if(err) res.send(err); }); //Tìm tất cả các câu trả lời của thành viên này và xóa hết các vote liên quan Answer.find({userId: id}, function(err, answers){ if(err) res.send(err); answers.forEach(function(item){ Vote.remove({answerId: item._id}, function(err,a){ if(err) res.send(err); }); }); }); //Xóa tất cả các câu trả lời của thành viên này Answer.remove({ userId: id }, function(err, answers){ if(err) res.send(err); }); //Xóa đánh giá Vote.remove({ userId: id }, function(err, votes){ if(err) res.send(err); }); //Xóa mục yêu thích Favorite.remove({userId: id}, function(err, favorites){ if(err) res.send(err); }); User.remove({ _id: id }, function(err, users){ if(err) res.send(err); User.find(function(err, users) { if (err) res.send(err) res.json(users); }); }); } }); app.get('/api/user/favorite', function(req, res){ Favorite.find({userId: req.user._id}, function(err, list){ if(err) res.send(err); res.json(list); }); }); app.get('/api/user/favorite/all', function(req, res){ Favorite.find({}, function(err, list){ if(err) res.send(err); res.json(list); }); }); app.get('/api/user/vote', function(req, res){ Vote.find({userId: req.user._id}, function(err, list){ if(err) res.send(err); res.json(list); }); }); app.get('/api/user/vote/all', function(req, res){ Vote.find({}, function(err, list){ if(err) res.send(err); res.json(list); }); }); app.get('/api/user/active/:user_id/:token', function(req, res){ User.findById(req.params.user_id,function(err, user){ if (err) res.send(err); var token = req.params.token; if(user.activeToken==token) user.status=1; user.save(function(err, u){ if(err) res.send(err); res.json(u); }); }); }); app.post('/api/user/getUserbyEmail', function(req, res){ User.find({email: req.body.email}, function(err, user){ if(err) res.send(err); res.send(user); }); }); app.post('/api/user/edit', function(req, res){ User.findById(req.body._id, function(err, user){ if(err) res.send(err); user.displayName=req.body.displayName; user.location=req.body.location; user.website = req.body.website; user.birthday = req.body.birthday; user.save(function(err, u){ if(err) res.send(err); res.json(u); }); }); }); app.post('/api/user/changePassword', function(req, res, done){ User.findById(req.body._id, function(err, user){ if(err) res.send(err); if (!user || !user.validPassword(req.body.CurrentPassword)) return done(null, false); else{ user.password =user.generateHash(req.body.NewPassword); user.lastEditDate=new Date(); user.save(function(err, u){ if(err) res.send(err); res.json(u); }); } }); }); app.post('/forgot', function(req,res){ async.waterfall([ function(done) { crypto.randomBytes(20, function(err, buf) { var token = buf.toString('hex'); done(err, token); }); }, function(token, done) { User.findOne({ email: req.body.email }, function(err, user) { if (!user) { req.flash('error', 'No account with that email address exists.'); return res.redirect('/forgot'); } user.resetPasswordToken = token; user.resetPasswordExpires = Date.now() + 3600000; // thời gian hết hạn tính theo ms user.save(function(err) { done(err, token, user); }); }); }, function(token, user, done) { var domain =req.headers.host || "azquestion.com"; var mailOptions = { to: user.email, from: 'Mạng xã hội hỏi đáp <azquestion.com@gmail.com>', subject: 'Email khôi phục mật khẩu', text: 'Bạn nhận được email này là vì bạn (hoặc ai đó) đã yêu cầu thay đổi mật khẩu tài khoản của bạn.\n\n' + 'Hãy click vào đường link dưới hoặc chép và dán vào khung nhập địa chỉ của trình duyệt để hoàn tất xử lý:\n\n' + 'http://' + domain + '/users/reset-password/' + token + '\n\n' + 'Nếu không phải bạn yêu cầu thay đổi tài khoản thì chỉ đơn giản bỏ qua email này.\n'+ 'Lưu ý, email này chỉ có giá trị trong vòng 1 giờ đồng hồ kể từ lúc yêu cầu xử lý.' }; transporter.sendMail(mailOptions, function(err) { done(err, 'done'); }); } ], function(err) { if (err) return next(err); res.redirect('/forgot'); }); }); app.post('/api/user/resetPassword', function(req, res) { User.findOne({ resetPasswordToken: req.body.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) { if (!user) { res.send({"error_msg":"Mã khôi phục mật khẩu không hợp lệ hoặc đã hết hạn. Vui lòng yêu cầu mã khác!"}); } else{ user.password = user.generateHash(req.body.NewPassword); user.resetPasswordToken = undefined; user.resetPasswordExpires = undefined; user.save(function(err) { var mailOptions = { to: user.email, from: 'Mạng xã hội hỏi đáp <azquestion.com@gmail.com>', subject: 'Mật khẩu đã được thay đổi', text: 'Đây là email xác nhận mật khẩu tài khoản '+user.displayName+' đã được thay đổi.' }; transporter.sendMail(mailOptions, function(err, info) { if(err){ console.log(err); }else{ console.log('Message sent: ' + info.response); } }); req.logIn(user, function(err) { res.json(user); }); }); } }); }); app.post('/api/user/updatePermission', function(req, res){ User.findById(req.body._id, function(err, user){ if(err) res.send(err); user.role=req.body.role; user.lastEditDate=new Date(); user.save(function(err, u){ if(err) res.send(err); res.json(user); }); }); }); app.post('/api/user/upload',function(req, res) { var fstream; req.pipe(req.busboy); req.busboy.on('file', function (fieldname, file, filename) { console.log("Uploading: " + filename); var extension=(/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined; var strand= randtoken.generate(20); fstream = fs.createWriteStream('public/uploads/images/'+strand+'.'+ extension); file.pipe(fstream); fstream.on('close', function (err) { if(err) res.send(err); res.send(strand+'.'+extension); }); }); }); app.get('/api/user/online/:user_id', function(req, res){ var id= req.params.user_id; User.findById(id, function(err, user){ if(err) res.send(err); user.online="true"; user.save(function(err, u){ if(err) res.send(err); res.json(user); }); }); }); app.get('/api/user/offline/:user_id', function(req, res){ var id= req.params.user_id; User.findById(id, function(err, user){ if(err) res.send(err); user.online="false"; user.save(function(err, u){ if(err) res.send(err); res.json(user); }); }); }); }
import * as types from './mutation-types' import * as actions from './actions' import * as getters from './getters' const state = { allPosts: [], isLoaded: false } const mutations = { [types.INIT_POSTS] (state, posts) { state.allPosts = posts state.isLoaded = true } } export default { state, mutations, actions, getters }
/* eslint-disable jsx-a11y/no-static-element-interactions */ import React from 'react' import PropTypes from 'prop-types' import DeleteIcon from 'components/DeleteIcon' import store from 'utils/store' export default function GroupTile ({ onClick, label, handle, isActive, onDelete }) { const { dispatch } = store return ( <a onClick={onClick} className={`panel__col__tile ${isActive ? 'is-active' : ''}`} > {label} {handle && <span className="panel__col__handle">{handle}</span>} {onDelete && <DeleteIcon onClick={() => onDelete(label)} dispatch={dispatch} />} </a> ) } GroupTile.propTypes = { onClick: PropTypes.func.isRequired, label: PropTypes.string.isRequired, handle: PropTypes.string, isActive: PropTypes.bool.isRequired, onDelete: PropTypes.func } GroupTile.defaultProps = { onDelete: null, handle: null }
module.exports = bicubic function bicubic( xf , yf , p00, p01, p02, p03 , p10, p11, p12, p13 , p20, p21, p22, p23 , p30, p31, p32, p33 ) { var yf2 = yf * yf var xf2 = xf * xf var xf3 = xf * xf2 var x00 = p03 - p02 - p00 + p01 var x01 = p00 - p01 - x00 var x02 = p02 - p00 var x0 = x00*xf3 + x01*xf2 + x02*xf + p01 var x10 = p13 - p12 - p10 + p11 var x11 = p10 - p11 - x10 var x12 = p12 - p10 var x1 = x10*xf3 + x11*xf2 + x12*xf + p11 var x20 = p23 - p22 - p20 + p21 var x21 = p20 - p21 - x20 var x22 = p22 - p20 var x2 = x20*xf3 + x21*xf2 + x22*xf + p21 var x30 = p33 - p32 - p30 + p31 var x31 = p30 - p31 - x30 var x32 = p32 - p30 var x3 = x30*xf3 + x31*xf2 + x32*xf + p31 var y0 = x3 - x2 - x0 + x1 var y1 = x0 - x1 - y0 var y2 = x2 - x0 return y0*yf*yf2 + y1*yf2 + y2*yf + x1 }
let apiKey = '' const callGoogleAPI = async url => { const response = await fetch(url).then(res => res.json()) if (response.status === 'OK' && response.results.length) { return response.results[0] } else { return null } } export const setApiKey = key => { apiKey = key } export const autocomplete = async query => { const url = `https://maps.googleapis.com/maps/api/place/queryautocomplete/json?key=${apiKey}&input=${encodeURI(query)}` const result = await fetch(url) .then(response => response.json()) .catch(err => console.log(err)) return result } export const geocode = async (placeId, address) => { let query = '' if (placeId) { query = `place_id=${placeId}` } else if (address) { query = `address=${encodeURI(address)}` } const url = `https://maps.googleapis.com/maps/api/geocode/json?key=${apiKey}&${query}` const result = await callGoogleAPI(url) return result } export const getPlaceByLocation = async location => { const url = `https://maps.googleapis.com/maps/api/geocode/json?key=${apiKey}&latlng=${location.latitude},${location.longitude}` const result = await callGoogleAPI(url) return result } export const extractAddressParts = response => { const addressParts = response.formatted_address.split(',') const zipCity = addressParts[1].trim().split(' ') const zip = zipCity.length ? zipCity[0] : '' const city = zipCity.slice(1).join(' ') const address = { full_address: response.formatted_address, street: addressParts[0] ? addressParts[0].trim() : '', zipCode: zip.trim(), city: city.trim(), country: addressParts[2] ? addressParts[2].trim() : '', } return address }
'use strict'; var mongoose = require('mongoose'); var messageSchema = mongoose.Schema({ id: String, channelID: String, text: String, user: Object, time: String }); module.exports = mongoose.model('Message', messageSchema);
/** * MySQL data adapter */ 'use strict'; var q = require('q'); var moment = require('moment-timezone'); var Table = require('../table'); var GenericDbAdapter = require('./genericdb'); function MysqlAdapter() { /** * mysql connection */ this.mysqlConnection = null; GenericDbAdapter.call(this); } MysqlAdapter.prototype = new GenericDbAdapter(); MysqlAdapter.prototype.constructor = MysqlAdapter; /** * mysql connection setter * * @param {object} client * @return {object} */ MysqlAdapter.prototype.setConnection = function (conn) { this.mysqlConnection = conn; return this; }; /** * mysql connection getter * * @return {object} */ MysqlAdapter.prototype.getConnection = function () { return this.mysqlConnection; }; /** * Paginate and return result * * @param {object} table * @return {object} Returns promise */ MysqlAdapter.prototype.paginate = function (table) { var ands = []; for (var filter in this.sqlAnds) { var ors = this.sqlAnds[filter]; ands.push('(' + ors.join(') OR (') + ')'); } var where = ''; if (this.initialWhere.length > 0) { where = ' WHERE (' + this.initialWhere + ')'; if (ands.length) where += ' AND (' + ands.join(') AND (') + ')'; } else if (ands.length) { where = ' WHERE (' + ands.join(') AND (') + ')'; } var me = this; var db = this.getConnection(); var mapper = table.getMapper(); if (!mapper) throw new Error("Data 'mapper' is required when using MysqlAdapter"); var defer = q.defer(); db.connect(); db.query( "SELECT COUNT(*) AS count" + " FROM " + me.initialFrom + " " + where + " ", me.sqlParams, function (err, rows, fields) { if (err) { db.end(); defer.reject(err); return; } var count = rows[0].count; table.calculatePageParams(count); if (me.sqlOrderBy.length) where += ' ORDER BY ' + me.sqlOrderBy + ' '; if (table.getPageSize() > 0) { where += ' LIMIT ' + table.getPageSize() + ' '; where += ' OFFSET ' + (table.getPageSize() * (table.getPageNumber() - 1)) + ' '; } db.query( "SELECT " + me.initialSelect + " " + " FROM " + me.initialFrom + " " + where + " ", me.sqlParams, function (err, rows, fields) { if (err) { db.end(); defer.reject(err); return; } db.end(); var result = []; for (var i = 0; i < rows.length; i++) { var columns = table.getColumns(); for (var columnId in columns) { var column = columns[columnId]; if (column.type == Table.TYPE_DATETIME && rows[i][columnId]) { var m; if (me.getDbTimezone()) { if (typeof rows[i][columnId] == 'number') { m = moment.unix(rows[i][columnId]); } else { var tmp = moment(rows[i][columnId]); m = moment.tz(tmp.format("YYYY-MM-DD HH:mm:ss"), me.getDbTimezone()); } } else { if (typeof rows[i][columnId] == 'number') m = moment.unix(rows[i][columnId]); else m = moment(rows[i][columnId]); } rows[i][columnId] = m.local(); } } result.push(mapper(rows[i])); } defer.resolve(result); } ); } ); return defer.promise; }; /** * Build SQL query for a filter * * @param {string} field * @param {string} type * @param {string} filter * @param {string} value * @return {boolean} True on success */ MysqlAdapter.prototype.buildFilter = function (field, type, filter, value) { if (field.length == 0) throw new Error("Empty 'field'"); if (type.length == 0) throw new Error("Empty 'type'"); if (type == Table.TYPE_DATETIME) { if (filter == Table.FILTER_BETWEEN && Array.isArray(value) && value.length == 2) { value = [ value[0] ? moment.unix(value[0]) : null, value[1] ? moment.unix(value[1]) : null, ]; if (value[0]) { if (this.getDbTimezone()) value[0].tz(this.getDbTimezone()); value[0] = value[0].format("YYYY-MM-DD HH:mm:ss"); } if (value[1]) { if (this.getDbTimezone()) value[1].tz(this.getDbTimezone()); value[1] = value[1].format("YYYY-MM-DD HH:mm:ss"); } } else if (filter != Table.FILTER_BETWEEN && !Array.isArray(value)) { value = moment.unix(value); if (this.getDbTimezone()) value.tz(this.getDbTimezone()); value = value.format("YYYY-MM-DD HH:mm:ss"); } else { return false; } } else { if (filter == Table.FILTER_BETWEEN) { if (!Array.isArray(value) || value.length != 2) return false; } else if (Array.isArray(value)) { return false; } } if (typeof this.sqlAnds[field] == 'undefined') this.sqlAnds[field] = []; switch (filter) { case Table.FILTER_LIKE: this.sqlAnds[field].push(field + " LIKE ?"); this.sqlParams.push('%' + value + '%'); break; case Table.FILTER_EQUAL: this.sqlAnds[field].push(field + " = ?"); this.sqlParams.push(value); break; case Table.FILTER_BETWEEN: var ands = []; if (value[0] !== null) { ands.push(field + " >= ?"); this.sqlParams.push(value[0]); } if (value[1] !== null) { ands.push(field + " <= ?"); this.sqlParams.push(value[1]); } this.sqlAnds[field].push(ands.join(' AND ')); break; case Table.FILTER_NULL: this.sqlAnds[field].push(field + " IS NULL"); break; default: throw new Error("Unknown filter: " + filter); } return true; }; module.exports = MysqlAdapter;
'use strict'; const common = require('../common.js'); const bench = common.createBenchmark(main, { len: [0, 1, 64, 1024], n: [1e7] }); function main({ len, n }) { const buf = Buffer.alloc(len); var i; for (i = 0; i < buf.length; i++) buf[i] = i & 0xff; const hex = buf.toString('hex'); bench.start(); for (i = 0; i < n; i += 1) Buffer.from(hex, 'hex'); bench.end(n); }
/** * @author mrdoob / http://mrdoob.com/ */ function WebAudio( context ) { if ( context === undefined ) { context = WebAudio.context; } var scope = this; var source, buffer, binary; var currentTime = 0; var loop = false; var playbackRate = 1; var paused = true; var startAt = 0; var volume; if ( context ) { createVolume(); } function load( url ) { var request = new XMLHttpRequest(); request.open( 'GET', url, true ); request.responseType = 'arraybuffer'; request.addEventListener( 'load', function ( event ) { binary = event.target.response; if ( context ) { decode(); } } ); request.send(); } function decode() { context.decodeAudioData( binary, function ( data ) { buffer = data; if ( paused === false ) play(); } ); } function createVolume() { if ( !context.volume ) { context.volume = context.createGain(); context.volume.connect( context.destination ); context.volume.gain.value = 1; } volume = context.createGain(); volume.connect( context.volume ); volume.gain.value = 1; } function getCurrentTime() { if ( buffer === undefined || paused === true ) return currentTime; return currentTime + ( context.currentTime - startAt ) * playbackRate; } function play() { if ( context === undefined ) { context = WebAudio.getContext(); createVolume(); paused = false; decode(); } if ( buffer === undefined ) return; source = context.createBufferSource(); source.buffer = buffer; source.loop = loop; source.playbackRate.value = playbackRate; source.start( 0, currentTime ); source.connect( volume ); startAt = context.currentTime; } function stop() { if ( buffer === undefined ) return; source.stop(); source.disconnect( volume ); currentTime = getCurrentTime(); } return { play: function () { if ( paused ) { play(); paused = false; } }, pause: function () { if ( paused === false ) { stop(); paused = true; } }, get volume() { return volume.gain.value; }, set volume(v) { volume.gain.value = v; }, get currentTime() { return getCurrentTime(); }, set currentTime( value ) { if ( paused === false ) stop(); currentTime = value; if ( paused === false ) play(); }, get playbackRate() { return playbackRate; }, set playbackRate( value ) { if ( paused === false ) stop(); playbackRate = value; if ( paused === false ) play(); }, set src( url ) { load( url ); }, get loop() { return loop; }, set loop( value ) { loop = value; }, get paused() { return paused; }, get buffer() { return buffer; } } } WebAudio.getContext = function() { if ( WebAudio.context ) { return WebAudio.context; } WebAudio.context = new ( window.AudioContext || window.webkitAudioContext )(); return WebAudio.context; };
// The MIT License (MIT) // // Copyright (c) 2017-2021 Camptocamp SA // // 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. const {merge} = require('webpack-merge'); module.exports = (env, args) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment const nodeEnv = args.mode || 'production'; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment process.env['NODE_ENV'] = nodeEnv; let common_config = {}; switch (process.env.TARGET) { case 'dist': common_config.nodll = true; break; case 'ngeo-examples': case 'gmf-examples': common_config.browsers = ['> 0.5% in CH', '> 0.5% in FR', 'Firefox ESR', 'ie 11']; } let config = require('./buildtools/webpack.commons')(common_config); switch (nodeEnv) { case 'development': config = merge(config, require('./buildtools/webpack.dev')()); break; case 'production': config = merge(config, require('./buildtools/webpack.prod')()); break; default: console.log(`The 'NODE_ENV' environment variable is set to an invalid value: ${process.env.NODE_ENV}.`); process.exit(2); } switch (process.env.TARGET) { case 'ngeo-examples': config = merge(config, require('./buildtools/webpack.ngeoexamples')); break; case 'gmf-examples': config = merge(config, require('./buildtools/webpack.gmfexamples')); break; case 'gmf-apps': config = merge(config, require('./buildtools/webpack.gmfapps')); break; case 'dist': // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment config = merge(config, require(`./buildtools/webpack.dist`)); break; default: console.log(`The 'TARGET' environment variable is set to an invalid value: ${process.env.TARGET}.`); process.exit(2); } return config; };
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Alert, Modal } from 'antd'; import { RekitSteps } from './'; export default class DemoAlert extends Component { static propTypes = { onClose: PropTypes.func, }; static defaultProps = { onClose() {}, }; render() { return ( <Modal visible maskClosable title="" footer="" width="700px" onClose={this.props.onClose} > <div className="home-demo-alert"> <Alert message="The demo is readonly!" description="This site is only for demo purpose. So Rekit portal is running on readonly mode. You can't perform any action that alters the project data." type="warning" showIcon /> <RekitSteps /> </div> </Modal> ); } }
var express = require('express'); var mongoose = require('mongoose'); var workflow = require('./workflow'), PUBLISHED = workflow.PUBLISHED, util = require('./util'); // serve express app exports = module.exports = function(dirname, config, meta) { var app = express(); app.set('view engine', 'ejs'); app.set('views', dirname + '/views'); app.use(express.static(dirname + '/public')); //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(express.urlencoded()); app.use(express.json()); var Page = meta.model('Page'); var News = meta.model('News'); // endpoints app.get('/', function (req, res, next) { util.getSiteMapData(Page, function (err, site) { if (err) return next(err); var resources = util.getResources(site); News.find({}, function (err, news) { if (err) return next(err); res.render('index', {site: site, news: news, images: resources, next_page: site.pages[0].pages[0], resource_basepath: util.get_res_bp(config)}); }); }); }); app.get('/*', function (req, res, next) { util.getSiteMapData(Page, function (err, site) { if (err) return next(err); Page.findOne({url: req.path}).populate("resources").exec(function (err, page) { //state: PUBLISHED if (err) return next(err); if (!page) return next(new Error('no such page')); page = util.findById(site, page.id); var next_page = util.getNextNode(page); res.render('page', {page: page, site: site, next_page: next_page, resource_basepath: get_res_bp()}); }); }); }); return app; }
{ let closeCallback; return { stdout: { on: jest.fn().mockImplementation((event, callback) => { if (event === "data") { setTimeout(() => { callback(mockResponse); setTimeout(closeCallback, 0); }, 0); } else if (event === "close") { closeCallback = callback; } }), setEncoding: jest.fn() } }; }
// Ratio app.directive('ngRatio', function () { return { restric: 'A', link: function (scope, element, attr) { var ratio = +(attr.ngRatio); element.css('width', ratio + '%'); } }; }); // Enter Key app.directive('ngEnterKey', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { var keyCode = event.which || event.keyCode; // If enter key is pressed if (keyCode === 13) { scope.$apply(function () { // Evaluate the expression scope.$eval(attrs.ngEnterKey); }); event.preventDefault(); } }); }; }); // Field Validator app.directive('ngValidField', function () { return { restric: 'A', scope: { ngValidField: '=' }, link: function (scope, element, attr) { var event = function (event) { setTimeout(function () { var keyCode = event.which || event.keyCode; var field = scope.ngValidField; if (field.$touched && field.$invalid) element.addClass('has-error'); else element.removeClass('has-error'); }, 20); }; element.bind("focusout", event); } }; }); // Form Validator app.directive('ngValidate', function () { return { restric: 'A', scope: { ngValidate: '=' }, link: function (scope, element, attr) { var event = function (event) { setTimeout(function () { var keyCode = event.which || event.keyCode; var form = scope.ngValidate; angular.forEach(form, function (field, name) { if (name.indexOf("$") != 0) { var control = angular.element('[name=' + form.$name + '] [data-valid=' + name + ']'); if ((form.$submitted || field.$touched) && field.$invalid) { control.addClass('has-error'); } else { control.removeClass('has-error'); } control.removeClass('required-error'); control.removeClass('maxlength-error'); control.removeClass('minlength-error'); control.removeClass('email-error'); control.removeClass('pattern-error'); control.removeClass('date-error'); angular.forEach(field.$error, function (value, error) { if(value) { control.addClass(error + '-error'); } }); } }); }, 20); }; element.bind("focusout", event); element.bind("submit", event); } }; }); // Only Number - Allow only number in input app.directive('onlyNumber', function () { return function (scope, element, attrs) { var keyCode = [8, 9, 13, 37, 39, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110, 188, 190]; element.bind("keydown", function (event) { if ($.inArray(event.which, keyCode) == -1) { scope.$apply(function () { scope.$eval(attrs.onlyNum); event.preventDefault(); }); event.preventDefault(); } }); }; }); // Only Digits - Allow only digits in input app.directive('onlyDigits', function () { return function (scope, element, attrs) { var keyCode = [8, 9, 13, 37, 39, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105]; element.bind("keydown", function (event) { if ($.inArray(event.which, keyCode) == -1) { scope.$apply(function () { scope.$eval(attrs.onlyNum); event.preventDefault(); }); event.preventDefault(); } }); }; }); // Submit On app.directive('submitOn', function () { return { link: function (scope, elm, attrs) { scope.$on(attrs.submitOn, function () { //We can't trigger submit immediately, or we get $digest already in progress error :-[ (because ng-submit does an $apply of its own) setTimeout(function () { elm.trigger('submit'); }); }); } } });
(function (angular) { "use strict"; angular .module('folderPluginDesign') .controller('folderPluginCtrl', ['$scope', 'Utility', function ($scope, Utility) { $scope.availableLayouts = Utility.getLayouts(); $scope.data = Utility.getDefaultScopeData(); $scope.datastoreInitialized = false; //Go pull any previously saved data buildfire.datastore.getWithDynamicData(function (err, result) { if (!err) { $scope.datastoreInitialized = true; } else { console.error("Error: ", err); return; } if (result && result.data && !angular.equals({}, result.data)) { $scope.data = result.data; $scope.id = result.id; if (!$scope.data._buildfire) { $scope.data._buildfire = { plugins: { dataType: "pluginInstance", data: [] } }; } if (!$scope.data.design) { $scope.data.design = { backgroundImage: null, selectedLayout: 1, backgroundblur: 0, hideText: false }; } } /* * watch for changes in data and trigger the saveData function on change * */ $scope.$watch('data', saveData, true); Utility.digest($scope); }); /* * Call the datastore to save the data object * */ var saveData = function (newObj, oldObj) { if (!$scope.datastoreInitialized) { console.error("Error with datastore didn't get called"); return; } if (newObj == undefined) return; if (angular.equals(newObj, oldObj)) return; if (newObj.default) { newObj = Utility.getDefaultScopeBlankData(); } if ($scope.frmMain.$invalid) { console.warn('invalid data, details will not be saved'); return; } Utility.save(newObj); }; /* * Open a dailog to change the background image * */ $scope.changeBackground = function () { buildfire.imageLib.showDialog({ showIcons: false, multiSelection: false }, function (error, result) { if (result && result.selectedFiles && result.selectedFiles.length > 0) { if (!$scope.data.design) { $scope.data.design = {}; } $scope.data.design.backgroundImage = result.selectedFiles[0]; Utility.digest($scope); } }); }; /* * Get background image thumbnail * */ $scope.resizeImage = function (url) { if (!url) { return ""; } else { return buildfire.imageLib.resizeImage(url, { width: 88 }); } }; /* * Delete the background and back to the default white background * */ $scope.deleteBackground = function () { $scope.data.design.backgroundImage = ""; Utility.digest($scope); }; $scope.changeLayout = function (layoutId) { var newLayout = layoutId + 1; if (newLayout != $scope.data.design.selectedLayout) { $scope.data.design.selectedLayout = newLayout; Utility.digest($scope); } }; var digest = function () { if (!$scope.$$phase && !$scope.$root.$$phase) { $scope.$apply(); } }; }]); })(window.angular);
import needle from 'needle'; import { SiteConf } from '../../src/base'; export const postApiHandler = async (req, res) => { const { slug } = req.params; const url = `${ SiteConf.PostApi.replace(':slug', slug) }`; const postDetail = await needle('get', url); const { body } = postDetail; if (body.errors) res.status(404).json({}); else { const post = body.posts[0]; const tag = post.tags[0].slug; const tag2 = post.tags[1] && post.tags[1].slug; const relatedPost = await needle('get', `${ SiteConf.RelatedApiUrl }${ post.slug }/${ tag }/${ tag2 }`); const related = relatedPost.body; post['related'] = related; res.json(post); } };
'use strict'; const getChannelURL = require('ember-source-channel-url'); module.exports = function() { return Promise.all([ getChannelURL('release'), getChannelURL('beta'), getChannelURL('canary') ]).then(urls => { return { useYarn: true, scenarios: [ { name: 'ember-lts-2.12', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }) }, npm: { devDependencies: { 'ember-source': '~2.12.0' } } }, { name: 'ember-lts-2.16', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }) }, npm: { devDependencies: { '@ember/jquery': '^0.5.1', 'ember-source': '~2.16.0' } } }, { name: 'ember-lts-2.18', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }) }, npm: { devDependencies: { '@ember/jquery': '^0.5.1', 'ember-source': '~2.18.0' } } }, { name: 'ember-lts-3.4', npm: { devDependencies: { 'ember-source': '~3.4.0' } } }, { name: 'ember-release', npm: { devDependencies: { 'ember-source': urls[0] } } }, { name: 'ember-beta', npm: { devDependencies: { 'ember-source': urls[1] } } }, { name: 'ember-canary', npm: { devDependencies: { 'ember-source': urls[2] } } }, // The default `.travis.yml` runs this scenario via `yarn test`, // not via `ember try`. It's still included here so that running // `ember try:each` manually or from a customized CI config will run it // along with all the other scenarios. { name: 'ember-default', npm: { devDependencies: {} } }, { name: 'ember-default-with-jquery', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }) }, npm: { devDependencies: { '@ember/jquery': '^0.5.1' } } } ] }; }); };
(function () { 'use strict'; var scripts = document.getElementsByTagName("script"); var currentScriptPath = scripts[scripts.length - 1].src; angular.module('alcance', ['ngRoute']) .controller('AlcanceController', AlcanceController); AlcanceController.$inject = ['$scope', '$location']; function AlcanceController($scope, $location) { var vm = this; } })();
/** * Client Webpack Development Configuration */ /** * Webpack */ const webpack = require('webpack'); /** * Helpers */ const helpers = require('../helpers.utils'); const path = require('path'); /** * Webpack Plugins */ const AssetsPlugin = require('assets-webpack-plugin'); const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin'); const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin; const HtmlElementsPlugin = require('../modules/html-elements.util.js'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); /** * postcss-loader */ const autoprefixer = require('autoprefixer'); const precss = require('precss'); /** * Webpack Constants */ const HMR = helpers.hasProcessFlag('hot'); const METADATA = { title: 'Codezinger', baseUrl: '/', isDevServer: helpers.isWebpackDevServer(), }; /** * Webpack Configuration * * @see: http://webpack.github.io/docs/configuration.html#cli */ module.exports = function(options) { /** * Production option */ isProd = options.env === 'production'; return { /** * Cache generated modules and chunks to improve performance for multiple * incremental builds * This is enabled by default in watch mode * You can pass false to disable it * * @see: http://webpack.github.io/docs/configuration.html#cache */ // cache: false, /** * The entry point for the bundle; the location of our Angular.js app * * @see: http://webpack.github.io/docs/configuration.html#entry */ entry: { /** * Our primary Angular 2 application */ 'main': './src/client/config/main.browser.ts', 'polyfills': './src/client/config/polyfills.browser.ts', 'vendor': './src/client/config/vendor.browser.ts', }, /** * Options affecting the resolving of modules * * @see: http://webpack.github.io/docs/configuration.html#resolve */ resolve: { /** * An array of extensions that should be used to resolve modules * * @see: http://webpack.github.io/docs/configuration.html#resolve-extensions */ extensions: ['.js', '.json', '.scss', '.ts'], /** * An array of directory names to be resolved to the current directory */ modules: [helpers.root('src/client'), 'node_modules'], }, /** * Options affecting the normal modules * * @see: http://webpack.github.io/docs/configuration.html#module */ module: { rules: [ /** * TypeScript loaders support for .ts and Angular 2 async routes via .async.ts * * @see https://github.com/s-panferov/awesome-typescript-loader * @see https://github.com/TheLarkInn/angular2-template-loader */ { test: /\.ts$/, loaders: [ 'awesome-typescript-loader', 'angular2-template-loader', 'angular2-router-loader', '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd ], exclude: [/\.(spec|e2e)\.ts$/] }, /** * JSON loader support for *.json files * * @see https://github.com/webpack/json-loader */ { test: /\.json$/, loader: 'json-loader' }, /** * to-string and css-loader support for *.css files * Returns file content as string * * @see https://github.com/gajus/to-string-loader * @see https://github.com/webpack/css-loader */ { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] }, /** * Raw loader support for *.html * Returns file content as a string * * @see https://github.com/webpack/raw-loader */ { test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/client/index.html')] }, /** * Support for Sass imports * * @see get postcss-loader working */ { test: /\.scss$/, loaders: ['raw-loader', 'sass-loader'], exclude: [ helpers.root('node_modules') ] }, /** * Files loader for supporting images, for example, in CSS files */ { test: /\.(jpg|png|gif)$/, loader: 'file' } ] }, /** * Add additional plugins to the compiler * * @see: http://webpack.github.io/docs/configuration.html#plugins */ plugins: [ /** * Plugin: AssetsPlugin * Description: Emits a json file with assets paths. * * @see https://github.com/kossnocorp/assets-webpack-plugin */ new AssetsPlugin({ path: helpers.root('dist/client'), filename: 'webpack-assets.json', prettyPrint: true }), /** * Plugin: ForkCheckerPlugin * Description: Perform type checking in a separate process, so webpack * doesn't need to wait * * @see https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse */ new ForkCheckerPlugin(), /** * Plugin: CommonsChunkPlugin * Description: Shares common code between the pages * Identifies common modules and put them into a commons chunk * * @see https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin * @see https://github.com/webpack/docs/wiki/optimization#multi-page-app */ new CommonsChunkPlugin({ name: ['polyfills', 'vendor'].reverse() }), /** * Plugin: ContextReplacementPlugin * Description: Provides context to Angular's use of System.import * * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin * See: https://github.com/angular/angular/issues/11580 */ new ContextReplacementPlugin( // The (\\|\/) piece accounts for path separators in *nix and Windows /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/, helpers.root('src') // location of your src ), /** * Plugin: CopyWebpackPlugin * Description: Copy files and directories in webpack * Copies project static assets * * @see https://www.npmjs.com/package/copy-webpack-plugin */ new CopyWebpackPlugin([{ from: 'src/client/assets', to: 'assets' },{ from: 'src/client/meta' }]), /** * Plugin: HtmlElementsPlugin * Description: Generate html tags based on javascript maps. * * If a publicPath is set in the webpack output configuration, it will be automatically added to * href attributes, you can disable that by adding a "=href": false property. * You can also enable it to other attribute by settings "=attName": true. * * The configuration supplied is map between a location (key) and an element definition object (value) * The location (key) is then exported to the template under then htmlElements property in webpack configuration. * * Example: * Adding this plugin configuration * new HtmlElementsPlugin({ * headTags: { ... } * }) * * Means we can use it in the template like this: * <%= webpackConfig.htmlElements.headTags %> * * Dependencies: HtmlWebpackPlugin */ new HtmlElementsPlugin({ headTags: require('../head.conf') }), /** * Plugin: HtmlWebpackPlugin * Description: Simplifies creation of HTML files to serve your webpack * bundles. This is especially useful for webpack bundles that include a * hash in the filename which changes upon every compilation * * @see https://github.com/ampedandwired/html-webpack-plugin */ new HtmlWebpackPlugin({ chunksSortMode: 'dependency', inject: 'head', metadata: METADATA, template: 'src/client/index.html', title: METADATA.title, }), /* * Plugin: ScriptExtHtmlWebpackPlugin * Description: Enhances html-webpack-plugin functionality * with different deployment options for your scripts including: * * See: https://github.com/numical/script-ext-html-webpack-plugin */ new ScriptExtHtmlWebpackPlugin({ defaultAttribute: 'defer' }), /** * Plugin LoaderOptionsPlugin (experimental) * * @see: https://gist.github.com/sokra/27b24881210b56bbaff7 */ new LoaderOptionsPlugin({ /** * postcss-loader * * CSS postprocessor * * @see: https://github.com/postcss/postcss-loader */ postcss: function () { return [precss, autoprefixer]; } }) ], /** * Include polyfills or mocks for various node stuff * Description: Node configuration * * @see https://webpack.github.io/docs/configuration.html#node */ node: { global: true, crypto: 'empty', process: true, module: false, clearImmediate: false, setImmediate: false } } };
'use strict'; var settings = require('../../settings'); var studentModel = require('../../studentModel'); /** * Model for a student in the database. * @param {mongoose} mongoose Mongoose instance. * @param {class} Schema Schema class. * @function models.student */ module.exports = function (mongoose, Schema) { var StudentModel; var Student = new Schema(studentModel.schema); Student.methods.toRealObject = function(req, res, fields, next){ var self = this.toObject(); studentModel.runRunTime(self, req, res, function(err, data){ if(err){ next(err, null); return; } var finalObj = {}; studentModel .fields(fields) .map(function(k, idx){ finalObj[k] = data[k]; }); next(null, finalObj); }); }; StudentModel = mongoose.model('Student', Student); return StudentModel; };
import expect from 'expect'; import createSwitchAction from '../src'; describe('createSwitchAction', () => { it('should exist', () => { expect(typeof createSwitchAction !== 'undefined').toBe(true); }); const ADD = 'ADD'; const SUB = 'SUB'; const OTHER = 'OTHER'; const INC = 'INC'; const RETURN_THIS = 'RETURN_THIS'; function addReducer(state, {payload}) { return state + payload.amount; } function subReducer(state, {payload}) { return state - payload.amount; } function incReducer(state) { return state + 1; } function returnThisReducer() { return this; } const switchAction = createSwitchAction({ [ADD]: addReducer, [SUB]: subReducer, [INC]: incReducer, [RETURN_THIS]: returnThisReducer, }); it('should call a reducer according to an action type', () => { const addAction = { type: ADD, payload: { amount: 2, }, }; const subAction = { type: SUB, payload: { amount: 2, }, }; expect(switchAction(5, addAction)).toBe(7); expect(switchAction(5, subAction)).toBe(3); }); it('should return the state for an unknown action', () => { const otherAction = { type: OTHER, payload: { other: 'data', }, }; expect(switchAction(5, otherAction)).toBe(5); }); it('should accept actions without payload', () => { const incAction = { type: INC, }; expect(switchAction(5, incAction)).toBe(6); }); it('should retain the `this` context', () => { const returnThisAction = { type: RETURN_THIS, }; expect(switchAction.call('thisContext', 5, returnThisAction)).toBe('thisContext'); }); });
const test = require('tape') const nlp = require('./_lib') test('sanity-check case:', function(t) { let str = 'John xoo, John fredman' let r = nlp(str) str = r.toUpperCase().out('text') t.equal(str, 'JOHN XOO, JOHN FREDMAN', 'uppercase') str = r.toLowerCase().out('text') t.equal(str, 'john xoo, john fredman', 'lowercase') str = r.toCamelCase().out('text') t.equal(str, 'johnXooJohnFredman', 'camelcase') //removes comma t.end() }) test('camel case:', function(t) { let doc = nlp('and check this out! a walk-in microwave.') doc.hyphenated().toCamelCase() t.equal(doc.text(), 'and check this out! a walkIn microwave.', 'hyphenated-camelcase') t.end() }) test('tricky case:', function(t) { let str = 'i am spencer kelly here with Amy Adams.' let r = nlp(str) r.match('#Person').toUpperCase() str = r.out('text') t.equal(str, 'i am SPENCER KELLY here with AMY ADAMS.', 'tricky-uppercase') str = 'the Spencer Kelly Festival of Silly Walks' r = nlp(str) r.match('@titleCase+').toCamelCase() t.equal(r.out('text'), 'the SpencerKellyFestival of SillyWalks', 'tricky-camelcase') t.end() }) test('unicode case:', function(t) { let doc = nlp(`ümasdfs`) doc.toTitleCase() t.equal(doc.text(), 'Ümasdfs', 'unicode-titlecase') doc = nlp(`Ümasdfs`) doc.toUpperCase() t.equal(doc.text(), 'ÜMASDFS', 'unicode-uppercase') doc.toLowerCase() t.equal(doc.text(), 'ümasdfs', 'unicode-lowercase') t.end() })
import { createRequests } from '../lib/index'; test('Check requests created by createRequests function', () => { const requests = createRequests('http://wordpress.test/wp-json/', ['books', 'authors']); expect(typeof requests.requestBooks).toBe('function'); expect(typeof requests.requestBooksEndpoint).toBe('function'); expect(typeof requests.requestBooksById).toBe('function'); expect(typeof requests.requestBooksEndpointById).toBe('function'); expect(typeof requests.requestAllBooks).toBe('function'); expect(typeof requests.requestAllBooksEndpoint).toBe('function'); expect(typeof requests.requestAllBooksEndpointById).toBe('function'); expect(typeof requests.requestAuthors).toBe('function'); expect(typeof requests.requestAuthorsEndpoint).toBe('function'); expect(typeof requests.requestAuthorsById).toBe('function'); expect(typeof requests.requestAuthorsEndpointById).toBe('function'); expect(typeof requests.requestAllAuthors).toBe('function'); expect(typeof requests.requestAllAuthorsEndpoint).toBe('function'); expect(typeof requests.requestAllAuthorsEndpointById).toBe('function'); }); test('Check ability to skip some requests', () => { const requests = createRequests('http://wordpress.test/wp-json/', ['books'], { request: false, requestEndpoint: false, requestById: false, requestEndpointById: false, requestAll: false, requestAllEndpoint: false, requestAllEndpointById: false, }); expect(typeof requests.requestBooks).toBe('undefined'); expect(typeof requests.requestBooksEndpoint).toBe('undefined'); expect(typeof requests.requestBooksById).toBe('undefined'); expect(typeof requests.requestBooksEndpointById).toBe('undefined'); expect(typeof requests.requestAllBooks).toBe('undefined'); expect(typeof requests.requestAllBooksEndpoint).toBe('undefined'); expect(typeof requests.requestAllBooksEndpointById).toBe('undefined'); });
'use strict'; module.exports = function camelcase(str) { return str.replace(/^([A-Z])|[\s-_](\w)/g, function (match, p1, p2) { if (p2) return p2.toUpperCase(); return p1.toLowerCase(); }); };
const subtitleText = 'A nice short description or subtitle to go with the title.'; const menuItems = [ { label: 'One', to: '#' }, { label: 'Two', to: '#' }, { label: 'Three', to: '#' }, { label: 'Four', to: '#' } ]; const menuItemsWithIcons = menuItems.map(a => { const b = Object.assign({}, a); b.icon = { name: 'three-bars' }; return b; }); const menuItemsWithSubtitles = menuItems.map(a => { const b = Object.assign({}, a); b.subtitle = subtitleText; return b; }); module.exports = { title: 'menu', status: 'ready', context: { title: 'Knowledge Base', menuItems: menuItems }, variants: [ { name: 'separated', context: { menuItems: menuItems } }, { name: 'icons', context: { menuItems: menuItemsWithIcons } }, { name: 'subtitles', context: { menuItems: menuItemsWithSubtitles } }, { name: 'horizontal', context: { menuItems: menuItems } }, { name: 'horizontal-separated', context: { menuItems: menuItems } }, { name: 'horizontal-icons', context: { menuItems: menuItemsWithIcons } }, { name: 'hide-labels-small', context: { modifiers: ['horizontal', 'hide-labels-on-small'], menuItems: menuItemsWithIcons } } ] };
// the global variable var watchList = [ { "Title": "Inception", "Year": "2010", "Rated": "PG-13", "Released": "16 Jul 2010", "Runtime": "148 min", "Genre": "Action, Adventure, Crime", "Director": "Christopher Nolan", "Writer": "Christopher Nolan", "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy", "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.", "Language": "English, Japanese, French", "Country": "USA, UK", "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.", "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg", "Metascore": "74", "imdbRating": "8.8", "imdbVotes": "1,446,708", "imdbID": "tt1375666", "Type": "movie", "Response": "True" }, { "Title": "Interstellar", "Year": "2014", "Rated": "PG-13", "Released": "07 Nov 2014", "Runtime": "169 min", "Genre": "Adventure, Drama, Sci-Fi", "Director": "Christopher Nolan", "Writer": "Jonathan Nolan, Christopher Nolan", "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow", "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.", "Language": "English", "Country": "USA, UK", "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.", "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg", "Metascore": "74", "imdbRating": "8.6", "imdbVotes": "910,366", "imdbID": "tt0816692", "Type": "movie", "Response": "True" }, { "Title": "The Dark Knight", "Year": "2008", "Rated": "PG-13", "Released": "18 Jul 2008", "Runtime": "152 min", "Genre": "Action, Adventure, Crime", "Director": "Christopher Nolan", "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)", "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine", "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.", "Language": "English, Mandarin", "Country": "USA, UK", "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.", "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg", "Metascore": "82", "imdbRating": "9.0", "imdbVotes": "1,652,832", "imdbID": "tt0468569", "Type": "movie", "Response": "True" }, { "Title": "Batman Begins", "Year": "2005", "Rated": "PG-13", "Released": "15 Jun 2005", "Runtime": "140 min", "Genre": "Action, Adventure", "Director": "Christopher Nolan", "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)", "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes", "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.", "Language": "English, Urdu, Mandarin", "Country": "USA, UK", "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.", "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg", "Metascore": "70", "imdbRating": "8.3", "imdbVotes": "972,584", "imdbID": "tt0372784", "Type": "movie", "Response": "True" }, { "Title": "Avatar", "Year": "2009", "Rated": "PG-13", "Released": "18 Dec 2009", "Runtime": "162 min", "Genre": "Action, Adventure, Fantasy", "Director": "James Cameron", "Writer": "James Cameron", "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang", "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.", "Language": "English, Spanish", "Country": "USA, UK", "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.", "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg", "Metascore": "83", "imdbRating": "7.9", "imdbVotes": "876,575", "imdbID": "tt0499549", "Type": "movie", "Response": "True" } ]; // Add your code below this line var filteredList; // Add your code above this line console.log(filteredList);
/* eslint-disable prefer-arrow-callback */ import { Meteor } from 'meteor/meteor'; import { defineMessages } from 'react-intl'; // API import { Profiles } from '../../profiles/profiles.js'; import { Shows } from '../../shows/shows.js'; import { Events } from '../../events/events.js'; // The actual values are dynamically generated then pulled from the database // so these are just reference for generating the json files const messages = defineMessages({ 'stats.onePeople': { id: 'stats.onePeople', defaultMessage: 'Person', }, 'stats.otherPeople': { id: 'stats.otherPeople', defaultMessage: 'People', }, 'stats.oneFestival': { id: 'stats.oneFestival', defaultMessage: 'Festival', }, 'stats.otherFestivals': { id: 'stats.otherFestivals', defaultMessage: 'Festivals', }, 'stats.oneEvent': { id: 'stats.oneEvent', defaultMessage: 'Event', }, 'stats.otherEvents': { id: 'stats.otherEvents', defaultMessage: 'Events', }, 'stats.oneShow': { id: 'stats.oneShow', defaultMessage: 'Show', }, 'stats.otherShows': { id: 'stats.otherShows', defaultMessage: 'Shows', }, 'stats.oneArtist': { id: 'stats.oneArtist', defaultMessage: 'Artist', }, 'stats.otherArtists': { id: 'stats.otherArtists', defaultMessage: 'Artists', }, 'stats.oneOrganization': { id: 'stats.oneOrganization', defaultMessage: 'Organization', }, 'stats.otherOrganizations': { id: 'stats.otherOrganizations', defaultMessage: 'Organizations', }, 'stats.oneLocation': { id: 'stats.oneLocation', defaultMessage: 'Location', }, 'stats.otherLocations': { id: 'stats.otherLocations', defaultMessage: 'Locations', }, }); Meteor.publish('counts.collections', function countsCollections() { const self = this; let countTheatremakers = 0; let countOrganizations = 0; let countShows = 0; let countFestivals = 0; let countLocations = 0; let initializing = true; // observeChanges only returns after the initial `added` callbacks // have run. Until then, we don't want to send a lot of // `self.changed()` messages - hence tracking the // `initializing` state. const handleTheatremakers = Profiles.find({ profileType: 'Individual' }).observeChanges({ added: () => { countTheatremakers++; if (!initializing) { self.changed('Counts', 'People', { count: countTheatremakers }); } }, removed: () => { countTheatremakers--; self.changed('Counts', 'People', { count: countTheatremakers }); }, // don't care about changed }); const handleOrganizations = Profiles.find({ profileType: 'Organization' }).observeChanges({ added: () => { countOrganizations++; if (!initializing) { self.changed('Counts', 'Organizations', { count: countOrganizations }); } }, removed: () => { countOrganizations--; self.changed('Counts', 'Organizations', { count: countOrganizations }); }, // don't care about changed }); const handleFestivals = Profiles.find({ profileType: 'Festival' }).observeChanges({ added: () => { countFestivals++; if (!initializing) { self.changed('Counts', 'Festivals', { count: countFestivals }); } }, removed: () => { countFestivals--; self.changed('Counts', 'Festivals', { count: countFestivals }); }, // don't care about changed }); const handleShows = Shows.find({}).observeChanges({ added: () => { countShows++; if (!initializing) { self.changed('Counts', 'Shows', { count: countShows }); } }, removed: () => { countShows--; self.changed('Counts', 'Shows', { count: countShows }); }, // don't care about changed }); const handleEventLocations = Events.find({ lat: { $gt: '' } }).observeChanges({ added: () => { countLocations++; if (!initializing) { self.changed('Counts', 'Locations', { count: countLocations }); } }, removed: () => { countLocations--; self.changed('Counts', 'Locations', { count: countLocations }); }, // don't care about changed }); const handleProfileLocations = Profiles.find({ lat: { $gt: '' } }).observeChanges({ added: () => { countLocations++; if (!initializing) { self.changed('Counts', 'Locations', { count: countLocations }); } }, removed: () => { countLocations--; self.changed('Counts', 'Locations', { count: countLocations }); }, // don't care about changed }); // Instead, we'll send one `self.added()` message right after // observeChanges has returned, and mark the subscription as // ready. initializing = false; self.added('Counts', 'People', { count: countTheatremakers }); self.added('Counts', 'Organizations', { count: countOrganizations }); self.added('Counts', 'Shows', { count: countShows }); self.added('Counts', 'Festivals', { count: countFestivals }); self.added('Counts', 'Locations', { count: countLocations }); self.ready(); // Stop observing the cursor when client unsubs. // Stopping a subscription automatically takes // care of sending the client any removed messages. self.onStop(() => { handleTheatremakers.stop(); handleOrganizations.stop(); handleShows.stop(); handleFestivals.stop(); handleEventLocations.stop(); handleProfileLocations.stop(); }); });
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '20307a5c66886e75c0bbdd20e2f09ffe', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // }, /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password>, // prefix: 'sess:', /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
const Component = require('./Component'); const {Point} = require('./point'); const {Edge} = require('./edge'); const {degreesToRadians} = require('./math'); class BoundingBox extends Component { static builder() { return new BoundingBoxBuilder(); } constructor(width, height) { super('BoundingBox'); this.width = width; this.height = height; this.points = [ new Point(-(width/2), height/2), new Point(width/2, height/2), new Point(width/2, -height/2), new Point(-(width/2), width/2) ]; } /** * Sprite points: * * 1-----2 Note: * | ^ | - Clockwise winding * | | - Starts at the "front left" point * 4-----3 */ /** * Returns four points in local space that make up the entity's sprite. Starts with the front left point and unwinds in clockwise order. */ getPointsInLocalSpace() { return [ new Point(-(this.width / 2), this.height / 2), new Point( this.width / 2, this.height / 2), new Point( this.width / 2, -(this.height / 2)), new Point(-(this.width / 2),-(this.height / 2)) ]; } /** * Returns four points in world space that make up the entity's sprite. Starts with the front left point and unwinds in clockwise order. */ getPointsInWorldSpace() { return this.getPointsInLocalSpace().map(p => this.getPointInWorldSpace(p)); } /** * Returns a point in world space relative to the entity's position and rotation. */ getPointInWorldSpace(p) { // See: https://math.stackexchange.com/a/814981 let transform = this.parent.getComponent('Transform'); let position = transform.position; let rotation = -degreesToRadians(transform.rotation); let x = Math.cos(rotation) * p.x - Math.sin(rotation) * p.y + position.x; let y = Math.sin(rotation) * p.x + Math.cos(rotation) * p.y + position.y; return new Point(x, y); } /** * Returns four edges in world space that correspond to the entity's sprite edges. Starts with the front edge and unwinds clockwise. */ getEdgesInWorldSpace() { let points = this.getPointsInWorldSpace(); let edges = []; for (let i = 0; i < points.length; ++i) { let p1 = points[i]; let p2 = i < points.length - 1 ? points[i + 1] : points[0]; edges.push(new Edge(p1, p2)); } return edges; } /** * Returns four outer normals in world space relative to entity's sprite edges. Starts with the front edge and unwinds in clockwise order. */ getEdgeNormals() { return this.getEdgesInWorldSpace().map(edge => edge.toLeftNormal()); } } module.exports = BoundingBox; class BoundingBoxBuilder { constructor() { this.height = []; } withWidth(width) { this.width = width; return this; } withHeight(height) { this.height = height; return this; } build() { return new BoundingBox(this.width, this.height); } }
import { LOAD_MESSAGES, LOAD_MESSAGES_SUCCESS, LOAD_MESSAGES_ERROR, UPDATE_MESSAGE_STATUS_SUCCESS } from '../constants'; const initialState = { unreadCount: 0, items: [], loading: true, error: false }; export default (state = initialState, action) => { switch (action.type) { case LOAD_MESSAGES: return { ...state, loading: true }; case LOAD_MESSAGES_SUCCESS: return { ...state, loading: false, ...action.data }; case LOAD_MESSAGES_ERROR: return { ...state, loading: false, error: true }; case UPDATE_MESSAGE_STATUS_SUCCESS: return { ...state, unreadCount: state.unreadCount - 1, items: state.items.filter(({id}) => id !== action.id) }; default: return { ...initialState, ...state }; } };
'use strict'; var Handlebars = require('handlebars'), fs = require('fs'), path = require('path'), Util = require('js/util'); // Get all the Handlebars helpers. require('js/templateHelpers'); module.exports = { tmplCache: window.ATOMIC_LACUNA_TEMPLATES || {}, get: function(name) { // Get from cache or load new one. var foo = this._get(name); if (_.isFunction(foo)) { return foo; } else { return this.load(name); } }, _get: function(name) { var rv = Util.deepGet(this.tmplCache, name); return rv; }, load: function(name) { if (window.ATOM_SHELL) { var func = this.compile(this.loadFile(name)); return this.save(name, func); } else { // If it can't be gotten from the file system, then it isn't here. console.log(this.tmplCache); // Debug throw new Error('Template has not been loaded: ' + name); } }, save: function(name, func) { Util.deepSet(this.tmplCache, name, func); return func; }, compile: function(string) { string = string.replace(/\n/g, ''); // Remove newlines. string = string.replace(/\s{2,}/g, ''); // Weed out whitespace. return Handlebars.compile(string); }, fixName: function(name) { name = name.replace(/\./g, path.sep); return name + '.hbs'; }, loadFile: function(name) { var fname = this.fixName(name); var location = path.join(Util.root(), 'templates', fname); return fs.readFileSync(location).toString(); } };
'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var PropTypes = React.PropTypes; var POSITIONS = { above: 'above', inside: 'inside', below: 'below' }; /** * Calls a function when you scroll to the element. */ var Waypoint = React.createClass({ displayName: 'Waypoint', propTypes: { onEnter: PropTypes.func, onLeave: PropTypes.func, // threshold is percentage of the height of the visible part of the // scrollable ancestor (e.g. 0.1) threshold: PropTypes.number }, /** * @return {Object} */ getDefaultProps: function getDefaultProps() { return { threshold: 0, onEnter: function onEnter() {}, onLeave: function onLeave() {} }; }, componentDidMount: function componentDidMount() { this.scrollableAncestor = this._findScrollableAncestor(); this.scrollableAncestor.addEventListener('scroll', this._handleScroll); window.addEventListener('resize', this._handleScroll); this._handleScroll(); }, componentDidUpdate: function componentDidUpdate() { // The element may have moved. this._handleScroll(); }, componentWillUnmount: function componentWillUnmount() { if (this.scrollableAncestor) { // At the time of unmounting, the scrollable ancestor might no longer // exist. Guarding against this prevents the following error: // // Cannot read property 'removeEventListener' of undefined this.scrollableAncestor.removeEventListener('scroll', this._handleScroll); } window.removeEventListener('resize', this._handleScroll); }, /** * Traverses up the DOM to find an ancestor container which has an overflow * style that allows for scrolling. * * @return {Object} the closest ancestor element with an overflow style that * allows for scrolling. If none is found, the `window` object is returned * as a fallback. */ _findScrollableAncestor: function _findScrollableAncestor() { var node = ReactDOM.findDOMNode(this); while (node.parentNode) { node = node.parentNode; if (node === document) { // This particular node does not have a computed style. continue; } var style = window.getComputedStyle(node); var overflowY = style.getPropertyValue('overflow-y') || style.getPropertyValue('overflow'); if (overflowY === 'auto' || overflowY === 'scroll') { return node; } } // A scrollable ancestor element was not found, which means that we need to // do stuff on window. return window; }, /** * @param {Object} event the native scroll event coming from the scrollable * ancestor, or resize event coming from the window. Will be undefined if * called by a React lifecyle method */ _handleScroll: function _handleScroll(event) { var currentPosition = this._currentPosition(); if (this._previousPosition === currentPosition) { // No change since last trigger return; } if (currentPosition === POSITIONS.inside) { this.props.onEnter.call(this, event); } else if (this._previousPosition === POSITIONS.inside) { this.props.onLeave.call(this, event); } var isRapidScrollDown = this._previousPosition === POSITIONS.below && currentPosition === POSITIONS.above; var isRapidScrollUp = this._previousPosition === POSITIONS.above && currentPosition === POSITIONS.below; if (isRapidScrollDown || isRapidScrollUp) { // If the scroll event isn't fired often enough to occur while the // waypoint was visible, we trigger both callbacks anyway. this.props.onEnter.call(this, event); this.props.onLeave.call(this, event); } this._previousPosition = currentPosition; }, /** * @param {Object} node * @return {Number} */ _distanceToTopOfScrollableAncestor: function _distanceToTopOfScrollableAncestor(node) { if (this.scrollableAncestor !== window && !node.offsetParent) { throw new Error('The scrollable ancestor of Waypoint needs to have positioning to ' + 'properly determine position of Waypoint (e.g. `position: relative;`)'); } if (node.offsetParent === this.scrollableAncestor || !node.offsetParent) { return node.offsetTop; } else { return node.offsetTop + this._distanceToTopOfScrollableAncestor(node.offsetParent); } }, /** * @return {boolean} true if scrolled down almost to the end of the scrollable * ancestor element. */ _currentPosition: function _currentPosition() { var waypointTop = this._distanceToTopOfScrollableAncestor(ReactDOM.findDOMNode(this)); var contextHeight = undefined; var contextScrollTop = undefined; if (this.scrollableAncestor === window) { contextHeight = window.innerHeight; contextScrollTop = window.pageYOffset; } else { contextHeight = this.scrollableAncestor.offsetHeight; contextScrollTop = this.scrollableAncestor.scrollTop; } var thresholdPx = contextHeight * this.props.threshold; var isBelowTop = contextScrollTop <= waypointTop + thresholdPx; if (!isBelowTop) { return POSITIONS.above; } var contextBottom = contextScrollTop + contextHeight; var isAboveBottom = contextBottom >= waypointTop - thresholdPx; if (!isAboveBottom) { return POSITIONS.below; } return POSITIONS.inside; }, /** * @return {Object} */ render: function render() { // We need an element that we can locate in the DOM to determine where it is // rendered relative to the top of its context. return React.createElement('span', { style: { fontSize: 0 } }); } }); module.exports = Waypoint;
var myGUI = new Object(); myGUI.shareApp=function(message){ }; myGUI.showAlert=function(title,message,twoButtons,Button1,Button2){ return twoButtons; }; myGUI.saveStringToFile(message, filename){ }; myGUI.loadStringFromFile(String filename){ return ""; };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); exports.toArray = toArray; exports.getActiveIndex = getActiveIndex; exports.getActiveKey = getActiveKey; exports.setTransform = setTransform; exports.isTransformSupported = isTransformSupported; exports.setTransition = setTransition; exports.getTransformPropValue = getTransformPropValue; exports.isVertical = isVertical; exports.getTransformByIndex = getTransformByIndex; exports.getMarginStyle = getMarginStyle; exports.getStyle = getStyle; exports.setPxStyle = setPxStyle; var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function toArray(children) { // allow [c,[a,b]] var c = []; _react2['default'].Children.forEach(children, function (child) { if (child) { c.push(child); } }); return c; } function getActiveIndex(children, activeKey) { var c = toArray(children); for (var i = 0; i < c.length; i++) { if (c[i].key === activeKey) { return i; } } return -1; } function getActiveKey(children, index) { var c = toArray(children); return c[index].key; } function setTransform(style, v) { style.transform = v; style.webkitTransform = v; style.mozTransform = v; } function isTransformSupported(style) { return 'transform' in style || 'webkitTransform' in style || 'MozTransform' in style; } function setTransition(style, v) { style.transition = v; style.webkitTransition = v; style.MozTransition = v; } function getTransformPropValue(v) { return { transform: v, WebkitTransform: v, MozTransform: v }; } function isVertical(tabBarPosition) { return tabBarPosition === 'left' || tabBarPosition === 'right'; } function getTransformByIndex(index, tabBarPosition) { var translate = isVertical(tabBarPosition) ? 'translateY' : 'translateX'; return translate + '(' + -index * 100 + '%) translateZ(0)'; } function getMarginStyle(index, tabBarPosition) { var marginDirection = isVertical(tabBarPosition) ? 'marginTop' : 'marginLeft'; return (0, _defineProperty3['default'])({}, marginDirection, -index * 100 + '%'); } function getStyle(el, property) { return +getComputedStyle(el).getPropertyValue(property).replace('px', ''); } function setPxStyle(el, property, value) { el.style[property] = value + 'px'; }
/** * Created by alex on 03.10.16. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import styles from './CategoriesBar.css'; function CategoriesBar(props) { return ( <div> <h3 className={styles.header}><FormattedMessage id="categoriesBarHeader"/></h3> <ul className={styles['categories-list']}>{ props.categories.map(category => ( <li key={category.cuid} onClick={props.onSelect.bind(null, category.cuid)}>{category.name}</li> )) } </ul> </div> ) } CategoriesBar.defaultProps = { categories: [] }; export default CategoriesBar;
define(function (require) { return { notEmpty: require('./validators/notEmpty'), email: require('./validators/email') } });
var examples = { lorem: 'Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit amet arcu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos.', kafka: 'One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked.', pangram: 'The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz. How quickly daft jumping zebras vex. Two driven jocks help fax my big quiz. Quick, Baz, get my woven flax jodhpurs!' }; var clozeTest = new Ractive({ el: '#clozeTest', template: '#template-clozeTest', data: { input: 'Add your own text here..' }, computed: { inputRegex: function() { var input = this.get('input'); return input.replace(/(\w+)/g,'<span>$1</span>').replace(/\n/g,'<br/>'); } } }); clozeTest.on('eg-lorem', function() { clozeTest.set('input', examples.lorem); }); clozeTest.on('eg-kafka', function() { clozeTest.set('input', examples.kafka); }); clozeTest.on('eg-pangram', function() { clozeTest.set('input', examples.pangram); }); //Randomise plugin (function($) { $.fn.randomize = function(childElem) { return this.each(function() { var $this = $(this); var elems = $this.children(childElem); elems.sort(function() { return (Math.round(Math.random())-0.5); }); $this.remove(childElem); for(var i=0; i < elems.length; i++){ $this.append(elems[i]); } }); } })(jQuery); $(function() { //Increment number var number = 0; function incrementNumber () { number += 1; } //Click spans in result box $('body').on('click', '#result_content span', function(){ var thisTxt = $(this).text(), inputWidth = $(this).width() ; if ( $(this).children().size() > 0 ) { //Need to match word, add a success message (tick maybe) & then replace input with correct text that is highlighted. } else { incrementNumber(); // Item moved to the Keywords area $(this).attr({id: 'item' + number}) .addClass('selected') .clone() .text($(this).text() + ' ') .appendTo('#keyword_content') ; // Items in the 'hide' area $(this).html('(' + number + ') <input type="text"/>') .find('input') .addClass('test-input') .attr({name: thisTxt}) .css('width', inputWidth) .data('text', thisTxt) ; } }); //Move words back to result box $('body').on('click','#keyword_content span', function() { var thisClass = $(this).attr('id'); var thatClass = 'span#' + thisClass; //alert(thatClass) var thisTxt = $(this).text(); //alert(thisTxt) $('#result_content').find(thatClass).replaceWith('<span>' + thisTxt + '</span>'); $(this).fadeOut('slow').remove(); }); //Randomise $('#keywords button').click(function() { $('#keyword_content').randomize("#keyword_content span"); }); //Select text /* $('button#select').on('click',function() { $('#result_content').select(); }); */ $('body').on('keyup', '#result_content input[type=text]', inputCheck); function inputCheck() { console.log('inputCheck'); if ( this.value === this.name ) { $(this).addClass('success'); $(this).parent().addClass('success').text(this.name); $(this).remove(); } else { $(this).addClass('error'); } } }); // To do: // 1. Enter a url or paste in your own text. // 2.
var expect = require("chai").expect; var converter = require("../app/converter"); describe("Color code converter", function(){ describe("RGB to Hex conversion", function() { it("converts the basic colors", function() { var redHex = converter.rgbToHex(255, 0, 0); var greenHex = converter.rgbToHex(0, 255, 0); var blueHex = converter.rgbToHex(0, 0, 255); expect(redHex).to.equal("ff0000"); expect(greenHex).to.equal("00ff00"); expect(blueHex).to.equal("0000ff"); }); }); describe("Hex to RGB conversion", function() { it("converts the basic colors", function() { var red = converter.hexToRgb("ff0000"); var green = converter.hexToRgb("00ff00"); var blue = converter.hexToRgb("0000ff"); expect(red).to.deep.equal([255, 0, 0]); expect(green).to.deep.equal([0, 255, 0]); expect(blue).to.deep.equal([0, 0, 255]); }); }); });
var AmpMoving = require('../ampersand-movingobj'); var domready = require('domready'); domready(function() { var Dialog = AmpMoving.extend({ template: '<div class="dialog">' + ' <h2 data-hook="start-move">This is an example dialog</h2>' + ' <p>' + ' Moving this dialog only works by dragging the headline.' + ' </p>' + '</div>', render: function() { AmpMoving.prototype.render.apply(this); console.log('this is render() in Dialog class'); } }); var dialog = new Dialog({ el: document.querySelector('#dialog'), }); dialog.render(); var MoveElm = AmpMoving.extend({ template: '<div class="moving-elm" data-hook="start-move">' + ' You can move this entire element.' + '</div>', autoRender: true }); var moving_elm = new MoveElm({ el: document.querySelector('#moving_elm'), }); });
'use strict'; module.exports = { db: 'mongodb://user:password@ds029837.mongolab.com:29837/kaysdatabase', debug: 'true', mongoose: { debug: false }, app: { name: 'MEAN - FullStack JS - Development' }, facebook: { clientID: 'DEFAULT_APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: 'DEFAULT_CONSUMER_KEY', clientSecret: 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, github: { clientID: 'DEFAULT_APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, google: { clientID: 'DEFAULT_APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: 'DEFAULT_API_KEY', clientSecret: 'SECRET_KEY', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com> mailer: { service: 'SERVICE_PROVIDER', // Gmail, SMTP auth: { user: 'EMAIL_ID', pass: 'PASSWORD' } } };
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2267',"Tlece.Recruitment.Models.RecruitmentPlanning Namespace","topic_0000000000000692.html"],['2400',"InviteRequestDto Class","topic_000000000000080D.html"],['2401',"Properties","topic_000000000000080D_props--.html"]];
this.NesDb = this.NesDb || {}; NesDb[ '6501F61FD717AE603C2265D0DF074AC2A4DCB8C7' ] = { "$": { "name": "Faxanadu", "altname": "ファザナドゥ", "class": "Licensed", "catalog": "HFC-FX", "publisher": "Hudson Soft", "developer": "Hudson Soft", "region": "Japan", "players": "1", "date": "1987-11-16" }, "cartridge": [ { "$": { "system": "Famicom", "crc": "A80FA181", "sha1": "6501F61FD717AE603C2265D0DF074AC2A4DCB8C7", "dump": "ok", "dumper": "bootgod", "datedumped": "2007-04-29" }, "board": [ { "$": { "type": "HVC-SGROM", "pcb": "HVC-SGROM-02", "mapper": "1" }, "prg": [ { "$": { "name": "HFC-FX-0 PRG", "size": "256k", "crc": "A80FA181", "sha1": "6501F61FD717AE603C2265D0DF074AC2A4DCB8C7" } } ], "vram": [ { "$": { "size": "8k" } } ], "chip": [ { "$": { "type": "MMC1" } } ] } ] } ], "gameGenieCodes": [ { "name": "Double starting power", "codes": [ [ "AXXSNTAP" ] ] }, { "name": "Triple starting power", "codes": [ [ "AUXSNTAP" ] ] }, { "name": "Half normal amount of Gold", "codes": [ [ "IASEPSZA" ] ] }, { "name": "Double normal amount of Gold", "codes": [ [ "GPSEPSZA" ] ] }, { "name": "Infinite magic", "codes": [ [ "AEENEZZA" ] ] }, { "name": "Jump in direction you are facing", "codes": [ [ "AVXVGPSZ" ] ] }, { "name": "Infinite power", "codes": [ [ "GXOGZESV", "GXOKLESV" ] ] }, { "name": "Slow mode", "codes": [ [ "AAUTAEOY", "AAKTPAKY", "AAUTZAPA" ] ] }, { "name": "Infinite Gold", "codes": [ [ "SXXNUOSE", "SXUYUOSE", "SXUNUOSE" ] ] } ] };
var db = { posts: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, title: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, markdown: {type: 'text', maxlength: 16777215, fieldtype: 'medium', nullable: true}, html: {type: 'text', maxlength: 16777215, fieldtype: 'medium', nullable: true}, image: {type: 'text', maxlength: 2000, nullable: true}, featured: {type: 'bool', nullable: false, defaultTo: false, validations: {isIn: [[0, 1, false, true]]}}, page: {type: 'bool', nullable: false, defaultTo: false, validations: {isIn: [[0, 1, false, true]]}}, status: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'draft'}, language: {type: 'string', maxlength: 6, nullable: false, defaultTo: 'en_US'}, meta_title: {type: 'string', maxlength: 150, nullable: true}, meta_description: {type: 'string', maxlength: 200, nullable: true}, author_id: {type: 'integer', nullable: false}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true}, published_at: {type: 'dateTime', nullable: true}, published_by: {type: 'integer', nullable: true} }, issues: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, title: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, image: {type: 'text', maxlength: 2000, nullable: true}, pdf: {type: 'text', maxlength: 2000, nullable: true}, article_length: {type: 'integer', nullable: false, defaultTo: 0}, series: {type: 'string', maxlength: 150, nullable: true}, status: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'draft'}, language: {type: 'string', maxlength: 6, nullable: false, defaultTo: 'en_US'}, meta_title: {type: 'string', maxlength: 150, nullable: true}, meta_description: {type: 'string', maxlength: 200, nullable: true}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true}, published_at: {type: 'dateTime', nullable: true}, published_by: {type: 'integer', nullable: true} }, articles: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, title: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, markdown: {type: 'text', maxlength: 16777215, fieldtype: 'medium', nullable: true}, html: {type: 'text', maxlength: 16777215, fieldtype: 'medium', nullable: true}, image: {type: 'text', maxlength: 2000, nullable: true}, status: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'draft'}, article_num: {type: 'integer', nullable: false}, issue_id: {type: 'integer', nullable: false}, language: {type: 'string', maxlength: 6, nullable: false, defaultTo: 'en_US'}, meta_title: {type: 'string', maxlength: 150, nullable: true}, meta_description: {type: 'string', maxlength: 200, nullable: true}, author_id: {type: 'integer', nullable: true}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true}, }, users: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, password: {type: 'string', maxlength: 60, nullable: false}, email: {type: 'string', maxlength: 254, nullable: false, unique: true, validations: {isEmail: true}}, image: {type: 'text', maxlength: 2000, nullable: true}, cover: {type: 'text', maxlength: 2000, nullable: true}, bio: {type: 'string', maxlength: 200, nullable: true}, website: {type: 'text', maxlength: 2000, nullable: true, validations: {isEmptyOrURL: true}}, location: {type: 'text', maxlength: 65535, nullable: true}, title: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'Member'}, accessibility: {type: 'text', maxlength: 65535, nullable: true}, status: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'active'}, language: {type: 'string', maxlength: 6, nullable: false, defaultTo: 'en_US'}, meta_title: {type: 'string', maxlength: 150, nullable: true}, meta_description: {type: 'string', maxlength: 200, nullable: true}, last_login: {type: 'dateTime', nullable: true}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, roles: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, description: {type: 'string', maxlength: 200, nullable: true}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, roles_users: { id: {type: 'increments', nullable: false, primary: true}, role_id: {type: 'integer', nullable: false}, user_id: {type: 'integer', nullable: false} }, permissions: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, object_type: {type: 'string', maxlength: 150, nullable: false}, action_type: {type: 'string', maxlength: 150, nullable: false}, object_id: {type: 'integer', nullable: true}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, permissions_users: { id: {type: 'increments', nullable: false, primary: true}, user_id: {type: 'integer', nullable: false}, permission_id: {type: 'integer', nullable: false} }, permissions_roles: { id: {type: 'increments', nullable: false, primary: true}, role_id: {type: 'integer', nullable: false}, permission_id: {type: 'integer', nullable: false} }, permissions_apps: { id: {type: 'increments', nullable: false, primary: true}, app_id: {type: 'integer', nullable: false}, permission_id: {type: 'integer', nullable: false} }, settings: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, key: {type: 'string', maxlength: 150, nullable: false, unique: true}, value: {type: 'text', maxlength: 65535, nullable: true}, type: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'core', validations: {isIn: [['core', 'blog', 'theme', 'app', 'plugin']]}}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, tags: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, description: {type: 'string', maxlength: 200, nullable: true}, image: {type: 'text', maxlength: 2000, nullable: true}, hidden: {type: 'bool', nullable: false, defaultTo: false, validations: {isIn: [[0, 1, false, true]]}}, parent_id: {type: 'integer', nullable: true}, meta_title: {type: 'string', maxlength: 150, nullable: true}, meta_description: {type: 'string', maxlength: 200, nullable: true}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, posts_tags: { id: {type: 'increments', nullable: false, primary: true}, post_id: {type: 'integer', nullable: false, unsigned: true, references: 'posts.id'}, tag_id: {type: 'integer', nullable: false, unsigned: true, references: 'tags.id'} }, issues_tags: { id: {type: 'increments', nullable: false, primary: true}, issue_id: {type: 'integer', nullable: false, unsigned: true, references: 'issues.id'}, tag_id: {type: 'integer', nullable: false, unsigned: true, references: 'tags.id'} }, articles_tags: { id: {type: 'increments', nullable: false, primary: true}, article_id: {type: 'integer', nullable: false, unsigned: true, references: 'articles.id'}, tag_id: {type: 'integer', nullable: false, unsigned: true, references: 'tags.id'} }, apps: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false, unique: true}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, version: {type: 'string', maxlength: 150, nullable: false}, status: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'inactive'}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, app_settings: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, key: {type: 'string', maxlength: 150, nullable: false, unique: true}, value: {type: 'text', maxlength: 65535, nullable: true}, app_id: {type: 'integer', nullable: false, unsigned: true, references: 'apps.id'}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, app_fields: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, key: {type: 'string', maxlength: 150, nullable: false}, value: {type: 'text', maxlength: 65535, nullable: true}, type: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'html'}, app_id: {type: 'integer', nullable: false, unsigned: true, references: 'apps.id'}, relatable_id: {type: 'integer', nullable: false, unsigned: true}, relatable_type: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'posts'}, active: {type: 'bool', nullable: false, defaultTo: true, validations: {isIn: [[0, 1, false, true]]}}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, clients: { id: {type: 'increments', nullable: false, primary: true}, uuid: {type: 'string', maxlength: 36, nullable: false}, name: {type: 'string', maxlength: 150, nullable: false, unique: true}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, secret: {type: 'string', maxlength: 150, nullable: false, unique: true}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, updated_by: {type: 'integer', nullable: true} }, accesstokens: { id: {type: 'increments', nullable: false, primary: true}, token: {type: 'string', nullable: false, unique: true}, user_id: {type: 'integer', nullable: false, unsigned: true, references: 'users.id'}, client_id: {type: 'integer', nullable: false, unsigned: true, references: 'clients.id'}, expires: {type: 'bigInteger', nullable: false} }, refreshtokens: { id: {type: 'increments', nullable: false, primary: true}, token: {type: 'string', nullable: false, unique: true}, user_id: {type: 'integer', nullable: false, unsigned: true, references: 'users.id'}, client_id: {type: 'integer', nullable: false, unsigned: true, references: 'clients.id'}, expires: {type: 'bigInteger', nullable: false} }, }; function isPost(jsonData) { return jsonData.hasOwnProperty('html') && jsonData.hasOwnProperty('markdown') && jsonData.hasOwnProperty('title') && jsonData.hasOwnProperty('slug'); } function isIssue(jsonData) { return jsonData.hasOwnProperty('title') && jsonData.hasOwnProperty('slug') && jsonData.hasOwnProperty('pdf'); } function isArticle(jsonData) { return jsonData.hasOwnProperty('title') && jsonData.hasOwnProperty('slug') && jsonData.hasOwnProperty('pdf_start') && jsonData.hasOwnProperty('pdf_end'); } function isTag(jsonData) { return jsonData.hasOwnProperty('name') && jsonData.hasOwnProperty('slug') && jsonData.hasOwnProperty('description') && jsonData.hasOwnProperty('parent'); } function isUser(jsonData) { return jsonData.hasOwnProperty('bio') && jsonData.hasOwnProperty('website') && jsonData.hasOwnProperty('status') && jsonData.hasOwnProperty('location'); } module.exports.tables = db; module.exports.checks = { isPost: isPost, isIssue: isIssue, isArticle: isArticle, isTag: isTag, isUser: isUser };
var outdatedBrowser=function(options){var outdated=document.getElementById("outdated");this.defaultOpts={bgColor:'#f25648',color:'#ffffff',lowerThan:'transform',languagePath:'../outdatedbrowser/lang/en.html'} if(options){if(options.lowerThan=='IE8'||options.lowerThan=='borderSpacing'){options.lowerThan='borderSpacing';}else if(options.lowerThan=='IE9'||options.lowerThan=='boxShadow'){options.lowerThan='boxShadow';}else if(options.lowerThan=='IE10'||options.lowerThan=='transform'||options.lowerThan==''||typeof options.lowerThan==="undefined"){options.lowerThan='transform';}else if(options.lowerThan=='IE11'||options.lowerThan=='borderImage'){options.lowerThan='borderImage';} this.defaultOpts.bgColor=options.bgColor;this.defaultOpts.color=options.color;this.defaultOpts.lowerThan=options.lowerThan;this.defaultOpts.languagePath=options.languagePath;bkgColor=this.defaultOpts.bgColor;txtColor=this.defaultOpts.color;cssProp=this.defaultOpts.lowerThan;languagePath=this.defaultOpts.languagePath;}else{bkgColor=this.defaultOpts.bgColor;txtColor=this.defaultOpts.color;cssProp=this.defaultOpts.lowerThan;languagePath=this.defaultOpts.languagePath;} var done=true;function function_opacity(opacity_value){outdated.style.opacity=opacity_value/100;outdated.style.filter='alpha(opacity='+opacity_value+')';} function function_fade_in(opacity_value){function_opacity(opacity_value);if(opacity_value==1){outdated.style.display='block';} if(opacity_value==100){done=true;}} var supports=(function(){var div=document.createElement('div');var vendors='Khtml Ms O Moz Webkit'.split(' ');var len=vendors.length;return function(prop){if(prop in div.style)return true;prop=prop.replace(/^[a-z]/,function(val){return val.toUpperCase();});while(len--){if(vendors[len]+prop in div.style){return true;}} return false;};})();if(!supports(''+cssProp+'')){if(done&&outdated.style.opacity!=='1'){done=false;for(var i=1;i<=100;i++){setTimeout((function(x){return function(){function_fade_in(x);};})(i),i*8);}}}else{return;} if(languagePath===' '||languagePath.length==0){startStylesAndEvents();}else{grabFile(languagePath);} function startStylesAndEvents(){var btnClose=document.getElementById("btnCloseUpdateBrowser");var btnUpdate=document.getElementById("btnUpdateBrowser");outdated.style.backgroundColor=bkgColor;outdated.style.color=txtColor;outdated.children[0].style.color=txtColor;outdated.children[1].style.color=txtColor;btnUpdate.style.color=txtColor;if(btnUpdate.style.borderColor){btnUpdate.style.borderColor=txtColor;} btnClose.style.color=txtColor;btnClose.onmousedown=function(){outdated.style.display='none';return false;};btnUpdate.onmouseover=function(){this.style.color=bkgColor;this.style.backgroundColor=txtColor;};btnUpdate.onmouseout=function(){this.style.color=txtColor;this.style.backgroundColor=bkgColor;};} var ajaxEnglishDefault='<h6>Your browser is out-of-date!</h6>' +'<p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" href="http://outdatedbrowser.com/">Update my browser now </a></p>' +'<p class="last"><a href="#" id="btnCloseUpdateBrowser" title="Close">&times;</a></p>';function getHTTPObject(){var xhr=false;if(window.XMLHttpRequest){xhr=new XMLHttpRequest();}else if(window.ActiveXObject){try{xhr=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xhr=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){xhr=false;}}} return xhr;} function grabFile(file){var request=getHTTPObject();if(request){request.onreadystatechange=function(){displayResponse(request);};request.open("GET",file,true);request.send(null);} return false;} function displayResponse(request){var insertContentHere=document.getElementById("outdated");if(request.readyState==4){if(request.status==200||request.status==304){insertContentHere.innerHTML=request.responseText;}else{insertContentHere.innerHTML=ajaxEnglishDefault;} startStylesAndEvents();} return false;}};
var OUTPUT_VERBOSITY_QUIET = 0; var OUTPUT_VERBOSITY_NORMAL = 1; var OUTPUT_VERBOSITY_VERBOSE = 2; function Output(verbosity, decorated, formatter) { this.VERBOSITY_QUIET = 0; this.VERBOSITY_NORMAL = 1; this.VERBOSITY_VERBOSE = 2; this.OUTPUT_NORMAL = 0; this.OUTPUT_RAW = 1; this.OUTPUT_PLAIN = 2; this._verbosity = typeof verbosity === 'undefined' ? this.VERBOSITY_NORMAL : verbosity; this._formatter = typeof formatter === 'undefined' ? new OutputFormatter() : formatter; this._formatter.setDecorated(decorated); }; Output.prototype.setFormatter = function(formatter) { this._formatter = formatter; }; Output.prototype.getFormatter = function(formatter) { return this._formatter; }; Output.prototype.setDecorated = function(decorated) { this._formatter.setDecorated(decorated); }; Output.prototype.isDecorated = function() { return this._formatter.isDecorated(); }; Output.prototype.setVerbosity = function(level) { this._verbosity = level; }; Output.prototype.getVerbosity = function() { return this._verbosity; }; Output.prototype.writeln = function(messages, type) { type = typeof type === 'undefined' ? 0 : type; this.write(messages, true, type); }; Output.prototype.write = function(messages, newline, type) { if (this.VERBOSITY_QUIET === this._verbosity) { return; }; messages = messages instanceof Array ? messages : [messages]; for (var i = messages.length - 1; i >= 0; i--) { var message = messages[i]; switch (type) { case this.OUTPUT_NORMAL: message = this._formatter.format(message); break; case this.OUTPUT_RAW: break; case this.OUTPUT_PLAIN: message = strip_tags(this._formatter.format(message)); break; default: throw new Error('Unknown output type given ('+type+')'); }; this.doWrite(message, newline); }; }; Output.prototype.doWrite = function(message, newline) { throw new Error('You must override this method.'); };
/* WysiHat - WYSIWYG JavaScript framework, version 0.2.1 * (c) 2008-2010 Joshua Peek * * WysiHat is freely distributable under the terms of an MIT-style license. *--------------------------------------------------------------------------*/ var WysiHat = {}; WysiHat.Editor = { attach: function(textarea, options, block) { options = $H(options); textarea = $(textarea); textarea.hide(); var model = options.get('model') || WysiHat.iFrame; var initializer = block; return model.create(textarea, function(editArea) { var document = editArea.getDocument(); var window = editArea.getWindow(); editArea.load(); Event.observe(window, 'focus', function(event) { editArea.focus(); }); Event.observe(window, 'blur', function(event) { editArea.blur(); }); editArea._observeEvents(); if (Prototype.Browser.Gecko) { editArea.execCommand('undo', false, null); } if (initializer) initializer(editArea); editArea.focus(); }); }, include: function(module) { this.includedModules = this.includedModules || $A([]); this.includedModules.push(module); }, extend: function(object) { var modules = this.includedModules || $A([]); modules.each(function(module) { Object.extend(object, module); }); } }; WysiHat.Commands = (function() { function boldSelection() { this.execCommand('bold', false, null); } function boldSelected() { return this.queryCommandState('bold'); } function underlineSelection() { this.execCommand('underline', false, null); } function underlineSelected() { return this.queryCommandState('underline'); } function italicSelection() { this.execCommand('italic', false, null); } function italicSelected() { return this.queryCommandState('italic'); } function strikethroughSelection() { this.execCommand('strikethrough', false, null); } function blockquoteSelection() { this.execCommand('blockquote', false, null); } function fontSelection(font) { this.execCommand('fontname', false, font); } function fontSizeSelection(fontSize) { this.execCommand('fontsize', false, fontSize); } function colorSelection(color) { this.execCommand('forecolor', false, color); } function backgroundColorSelection(color) { if(Prototype.Browser.Gecko) { this.execCommand('hilitecolor', false, color); } else { this.execCommand('backcolor', false, color); } } function alignSelection(alignment) { this.execCommand('justify' + alignment); } function alignSelected() { var node = this.selection.getNode(); return Element.getStyle(node, 'textAlign'); } function linkSelection(url) { this.execCommand('createLink', false, url); } function unlinkSelection() { var node = this.selection.getNode(); if (this.linkSelected()) this.selection.selectNode(node); this.execCommand('unlink', false, null); } function linkSelected() { var node = this.selection.getNode(); return node ? node.tagName.toUpperCase() == 'A' : false; } function formatblockSelection(element){ this.execCommand('formatblock', false, element); } function insertOrderedList() { this.execCommand('insertorderedlist', false, null); } function insertUnorderedList() { this.execCommand('insertunorderedlist', false, null); } function insertImage(url) { this.execCommand('insertImage', false, url); } function insertHTML(html) { if (Prototype.Browser.IE) { var range = this._selection.getRange(); range.pasteHTML(html); range.collapse(false); range.select(); } else { this.execCommand('insertHTML', false, html); } } function execCommand(command, ui, value) { var document = this.getDocument(); if (Prototype.Browser.IE) this.selection.restore(); var handler = this.commands.get(command); if (handler) handler.bind(this)(value); else { try { document.execCommand(command, ui, value); } catch (error) { //alert(command); } } } function queryCommandState(state) { var document = this.getDocument(); var handler = this.queryCommands.get(state); if (handler) return handler.bind(this)(); else { try { // dies in FF return document.queryCommandState(state); } catch (error) { } } } function getSelectedStyles() { var styles = $H({}); var editor = this; editor.styleSelectors.each(function(style){ var node = editor.selection.getNode(); styles.set(style.first(), Element.getStyle(node, style.last())); }); return styles; } return { boldSelection: boldSelection, boldSelected: boldSelected, underlineSelection: underlineSelection, underlineSelected: underlineSelected, italicSelection: italicSelection, italicSelected: italicSelected, strikethroughSelection: strikethroughSelection, blockquoteSelection: blockquoteSelection, fontSelection: fontSelection, fontSizeSelection: fontSizeSelection, colorSelection: colorSelection, backgroundColorSelection: backgroundColorSelection, alignSelection: alignSelection, alignSelected: alignSelected, linkSelection: linkSelection, unlinkSelection: unlinkSelection, linkSelected: linkSelected, formatblockSelection: formatblockSelection, insertOrderedList: insertOrderedList, insertUnorderedList: insertUnorderedList, insertImage: insertImage, insertHTML: insertHTML, execCommand: execCommand, queryCommandState: queryCommandState, getSelectedStyles: getSelectedStyles, commands: $H({}), queryCommands: $H({ link: linkSelected }), styleSelectors: $H({ fontname: 'fontFamily', fontsize: 'fontSize', forecolor: 'color', hilitecolor: 'backgroundColor', backcolor: 'backgroundColor' }) }; })(); WysiHat.Editor.include(WysiHat.Commands); WysiHat.Events = (function() { var eventsToFoward = [ 'click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout', 'keypress', 'keydown', 'keyup' ]; function forwardEvents(document, editor) { eventsToFoward.each(function(event) { Event.observe(document, event, function(e) { editor.fire('wysihat:' + event); }); }); } function observePasteEvent(window, document, editor) { Event.observe(document, 'keydown', function(event) { if (event.keyCode == 86) editor.fire("wysihat:paste"); }); Event.observe(window, 'paste', function(event) { editor.fire("wysihat:paste"); }); } function observeFocus(window, editor) { Event.observe(window, 'focus', function(event) { editor.fire("wysihat:focus"); }); Event.observe(window, 'blur', function(event) { editor.fire("wysihat:blur"); }); } function observeSelections(document, editor) { Event.observe(document, 'mouseup', function(event) { var range = editor.selection.getRange(); if (!range.collapsed) editor.fire("wysihat:select"); }); } function observeChanges(document, editor) { var previousContents = editor.rawContent(); Event.observe(document, 'keyup', function(event) { var contents = editor.rawContent(); if (previousContents != contents) { editor.fire("wysihat:change"); previousContents = contents; } }); } function observeCursorMovements(document, editor) { var previousRange = editor.selection.getRange(); var handler = function(event) { var range = editor.selection.getRange(); if (previousRange != range) { editor.fire("wysihat:cursormove"); previousRange = range; } }; Event.observe(document, 'keyup', handler); Event.observe(document, 'mouseup', handler); } function observeEvents() { if (this._observers_setup) return; var document = this.getDocument(); var window = this.getWindow(); forwardEvents(document, this); observePasteEvent(window, document, this); observeFocus(window, this); observeSelections(document, this); observeChanges(document, this); observeCursorMovements(document, this); this._observers_setup = true; } return { _observeEvents: observeEvents }; })(); WysiHat.Editor.include(WysiHat.Events); WysiHat.Persistence = (function() { function outputFilter(text) { return text.formatHTMLOutput(); } function inputFilter(text) { return text.formatHTMLInput(); } function content() { return this.outputFilter(this.rawContent()); } function setContent(text) { this.setRawContent(this.inputFilter(text)); } function save() { this.textarea.value = this.content(); } function load() { this.setContent(this.textarea.value); } function reload() { this.selection.setBookmark(); this.save(); this.load(); this.selection.moveToBookmark(); } return { outputFilter: outputFilter, inputFilter: inputFilter, content: content, setContent: setContent, save: save, load: load, reload: reload }; })(); WysiHat.Editor.include(WysiHat.Persistence); WysiHat.Window = (function() { function getDocument() { return this.contentDocument || this.contentWindow.document; } function getWindow() { if (this.contentDocument && this.contentDocument.defaultView) return this.contentDocument.defaultView; else if (this.contentWindow.document) return this.contentWindow; else return null; } function focus() { this.getWindow().focus(); if (this.hasFocus) return; this.hasFocus = true; } function blur() { this.hasFocus = false; } return { getDocument: getDocument, getWindow: getWindow, focus: focus, blur: blur }; })(); WysiHat.Editor.include(WysiHat.Window); WysiHat.iFrame = { create: function(textarea, callback) { var editArea = new Element('iframe', { 'id': textarea.id + '_editor', 'class': 'editor' }); Object.extend(editArea, WysiHat.iFrame.Methods); WysiHat.Editor.extend(editArea); editArea.attach(textarea, callback); textarea.insert({before: editArea}); return editArea; } }; WysiHat.iFrame.Methods = { attach: function(element, callback) { this.textarea = element; this.observe('load', function() { try { var document = this.getDocument(); } catch(e) { return; } // No iframe, just stop this.selection = new WysiHat.Selection(this); if (this.ready && document.designMode == 'on') return; this.setStyle({}); document.designMode = 'on'; callback(this); this.ready = true; this.fire('wysihat:ready'); }); }, unattach: function() { this.remove(); }, whenReady: function(callback) { if (this.ready) { callback(this); } else { var editor = this; editor.observe('wysihat:ready', function() { callback(editor); }); } return this; }, setStyle: function(styles) { var document = this.getDocument(); var element = this; if (!this.ready) return setTimeout(function() { element.setStyle(styles); }, 1); if (Prototype.Browser.IE) { var style = document.createStyleSheet(); style.addRule("body", "border: 0"); style.addRule("p", "margin: 0"); $H(styles).each(function(pair) { var value = pair.first().underscore().dasherize() + ": " + pair.last(); style.addRule("body", value); }); } else if (Prototype.Browser.Opera) { var style = Element('style').update("p { margin: 0; }"); var head = document.getElementsByTagName('head')[0]; head.appendChild(style); } else { Element.setStyle(document.body, styles); } return this; }, /** * WysiHat.iFrame.Methods#getStyle(style) -> string * - style specificication (i.e. backgroundColor) * * Returns the style from the element based on the given style */ getStyle: function(style) { var document = this.getDocument(); return Element.getStyle(document.body, style); }, rawContent: function() { var document = this.getDocument(); if (document.body) return document.body.innerHTML; else return ""; }, setRawContent: function(text) { var document = this.getDocument(); if (document.body) document.body.innerHTML = text; } }; WysiHat.Editable = { create: function(textarea, callback) { var editArea = new Element('div', { 'id': textarea.id + '_editor', 'class': 'editor', 'contenteditable': 'true' }); editArea.textarea = textarea; WysiHat.Editor.extend(editArea); Object.extend(editArea, WysiHat.Editable.Methods); callback(editArea); textarea.insert({before: editArea}); return editArea; } }; WysiHat.Editable.Methods = { getDocument: function() { return document; }, getWindow: function() { return window; }, rawContent: function() { return this.innerHTML; }, setRawContent: function(text) { this.innerHTML = text; } }; Object.extend(String.prototype, (function() { function formatHTMLOutput() { var text = String(this); text = text.tidyXHTML(); if (Prototype.Browser.WebKit) { text = text.replace(/(<div>)+/g, "\n"); text = text.replace(/(<\/div>)+/g, ""); text = text.replace(/<p>\s*<\/p>/g, ""); text = text.replace(/<br \/>(\n)*/g, "\n"); } else if (Prototype.Browser.Gecko) { text = text.replace(/<p>/g, ""); text = text.replace(/<\/p>(\n)?/g, "\n"); text = text.replace(/<br \/>(\n)*/g, "\n"); } else if (Prototype.Browser.IE || Prototype.Browser.Opera) { text = text.replace(/<p>(&nbsp;|&#160;|\s)<\/p>/g, "<p></p>"); text = text.replace(/<br \/>/g, ""); text = text.replace(/<p>/g, ''); text = text.replace(/&nbsp;/g, ''); text = text.replace(/<\/p>(\n)?/g, "\n"); text = text.gsub(/^<p>/, ''); text = text.gsub(/<\/p>$/, ''); } text = text.gsub(/<b>/, "<strong>"); text = text.gsub(/<\/b>/, "</strong>"); text = text.gsub(/<i>/, "<em>"); text = text.gsub(/<\/i>/, "</em>"); text = text.replace(/\n\n+/g, "</p>\n\n<p>"); text = text.gsub(/(([^\n])(\n))(?=([^\n]))/, "#{2}<br />\n"); text = '<p>' + text + '</p>'; text = text.replace(/<p>\s*/g, "<p>"); text = text.replace(/\s*<\/p>/g, "</p>"); var element = Element("body"); element.innerHTML = text; if (Prototype.Browser.WebKit || Prototype.Browser.Gecko) { var replaced; do { replaced = false; element.select('span').each(function(span) { if (span.hasClassName('Apple-style-span')) { span.removeClassName('Apple-style-span'); if (span.className == '') span.removeAttribute('class'); replaced = true; } else if (span.getStyle('fontWeight') == 'bold') { span.setStyle({fontWeight: ''}); if (span.style.length == 0) span.removeAttribute('style'); span.update('<strong>' + span.innerHTML + '</strong>'); replaced = true; } else if (span.getStyle('fontStyle') == 'italic') { span.setStyle({fontStyle: ''}); if (span.style.length == 0) span.removeAttribute('style'); span.update('<em>' + span.innerHTML + '</em>'); replaced = true; } else if (span.getStyle('textDecoration') == 'underline') { span.setStyle({textDecoration: ''}); if (span.style.length == 0) span.removeAttribute('style'); span.update('<u>' + span.innerHTML + '</u>'); replaced = true; } else if (span.attributes.length == 0) { span.replace(span.innerHTML); replaced = true; } }); } while (replaced); } var acceptableBlankTags = $A(['BR', 'IMG']); for (var i = 0; i < element.descendants().length; i++) { var node = element.descendants()[i]; if (node.innerHTML.blank() && !acceptableBlankTags.include(node.nodeName) && node.id != 'bookmark') node.remove(); } text = element.innerHTML; text = text.tidyXHTML(); text = text.replace(/<br \/>(\n)*/g, "<br />\n"); text = text.replace(/<\/p>\n<p>/g, "</p>\n\n<p>"); text = text.replace(/<p>\s*<\/p>/g, ""); text = text.replace(/\s*$/g, ""); return text; } function formatHTMLInput() { var text = String(this); var element = Element("body"); element.innerHTML = text; if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) { element.select('strong').each(function(element) { element.replace('<span style="font-weight: bold;">' + element.innerHTML + '</span>'); }); element.select('em').each(function(element) { element.replace('<span style="font-style: italic;">' + element.innerHTML + '</span>'); }); element.select('u').each(function(element) { element.replace('<span style="text-decoration: underline;">' + element.innerHTML + '</span>'); }); } if (Prototype.Browser.WebKit) element.select('span').each(function(span) { if (span.getStyle('fontWeight') == 'bold') span.addClassName('Apple-style-span'); if (span.getStyle('fontStyle') == 'italic') span.addClassName('Apple-style-span'); if (span.getStyle('textDecoration') == 'underline') span.addClassName('Apple-style-span'); }); text = element.innerHTML; text = text.tidyXHTML(); text = text.replace(/<\/p>(\n)*<p>/g, "\n\n"); text = text.replace(/(\n)?<br( \/)?>(\n)?/g, "\n"); text = text.replace(/^<p>/g, ''); text = text.replace(/<\/p>$/g, ''); if (Prototype.Browser.Gecko) { text = text.replace(/\n/g, "<br>"); text = text + '<br>'; } else if (Prototype.Browser.WebKit) { text = text.replace(/\n/g, "</div><div>"); text = '<div>' + text + '</div>'; text = text.replace(/<div><\/div>/g, "<div><br></div>"); } else if (Prototype.Browser.IE || Prototype.Browser.Opera) { text = text.replace(/\n/g, "</p>\n<p>"); text = '<p>' + text + '</p>'; text = text.replace(/<p><\/p>/g, "<p>&nbsp;</p>"); text = text.replace(/(<p>&nbsp;<\/p>)+$/g, ""); } return text; } function tidyXHTML() { var text = String(this); text = text.gsub(/\r\n?/, "\n"); text = text.gsub(/<([A-Z]+)([^>]*)>/, function(match) { return '<' + match[1].toLowerCase() + match[2] + '>'; }); text = text.gsub(/<\/([A-Z]+)>/, function(match) { return '</' + match[1].toLowerCase() + '>'; }); text = text.replace(/<br>/g, "<br />"); return text; } return { formatHTMLOutput: formatHTMLOutput, formatHTMLInput: formatHTMLInput, tidyXHTML: tidyXHTML }; })()); Object.extend(String.prototype, { sanitize: function(options) { return Element("div").update(this).sanitize(options).innerHTML.tidyXHTML(); } }); Element.addMethods({ sanitize: function(element, options) { element = $(element); options = $H(options); var allowed_tags = $A(options.get('tags') || []); var allowed_attributes = $A(options.get('attributes') || []); var sanitized = Element(element.nodeName); $A(element.childNodes).each(function(child) { if (child.nodeType == 1) { var children = $(child).sanitize(options).childNodes; if (allowed_tags.include(child.nodeName.toLowerCase())) { var new_child = Element(child.nodeName); allowed_attributes.each(function(attribute) { if ((value = child.readAttribute(attribute))) new_child.writeAttribute(attribute, value); }); sanitized.appendChild(new_child); $A(children).each(function(grandchild) { new_child.appendChild(grandchild); }); } else { $A(children).each(function(grandchild) { sanitized.appendChild(grandchild); }); } } else if (child.nodeType == 3) { sanitized.appendChild(child); } }); return sanitized; } }); if (typeof Range == 'undefined') { Range = function(ownerDocument) { this.ownerDocument = ownerDocument; this.startContainer = this.ownerDocument.documentElement; this.startOffset = 0; this.endContainer = this.ownerDocument.documentElement; this.endOffset = 0; this.collapsed = true; this.commonAncestorContainer = this._commonAncestorContainer(this.startContainer, this.endContainer); this.detached = false; this.START_TO_START = 0; this.START_TO_END = 1; this.END_TO_END = 2; this.END_TO_START = 3; }; Range.CLONE_CONTENTS = 0; Range.DELETE_CONTENTS = 1; Range.EXTRACT_CONTENTS = 2; if (!document.createRange) { document.createRange = function() { return new Range(this); }; } Object.extend(Range.prototype, (function() { function cloneContents() { return _processContents(this, Range.CLONE_CONTENTS); } function cloneRange() { try { var clone = new Range(this.ownerDocument); clone.startContainer = this.startContainer; clone.startOffset = this.startOffset; clone.endContainer = this.endContainer; clone.endOffset = this.endOffset; clone.collapsed = this.collapsed; clone.commonAncestorContainer = this.commonAncestorContainer; clone.detached = this.detached; return clone; } catch (e) { return null; }; } function collapse(toStart) { if (toStart) { this.endContainer = this.startContainer; this.endOffset = this.startOffset; this.collapsed = true; } else { this.startContainer = this.endContainer; this.startOffset = this.endOffset; this.collapsed = true; } } function compareBoundaryPoints(compareHow, sourceRange) { try { var cmnSelf, cmnSource, rootSelf, rootSource; cmnSelf = this.commonAncestorContainer; cmnSource = sourceRange.commonAncestorContainer; rootSelf = cmnSelf; while (rootSelf.parentNode) { rootSelf = rootSelf.parentNode; } rootSource = cmnSource; while (rootSource.parentNode) { rootSource = rootSource.parentNode; } switch (compareHow) { case this.START_TO_START: return _compareBoundaryPoints(this, this.startContainer, this.startOffset, sourceRange.startContainer, sourceRange.startOffset); break; case this.START_TO_END: return _compareBoundaryPoints(this, this.startContainer, this.startOffset, sourceRange.endContainer, sourceRange.endOffset); break; case this.END_TO_END: return _compareBoundaryPoints(this, this.endContainer, this.endOffset, sourceRange.endContainer, sourceRange.endOffset); break; case this.END_TO_START: return _compareBoundaryPoints(this, this.endContainer, this.endOffset, sourceRange.startContainer, sourceRange.startOffset); break; } } catch (e) {}; return null; } function deleteContents() { try { _processContents(this, Range.DELETE_CONTENTS); } catch (e) {} } function detach() { this.detached = true; } function extractContents() { try { return _processContents(this, Range.EXTRACT_CONTENTS); } catch (e) { return null; }; } function insertNode(newNode) { try { var n, newText, offset; switch (this.startContainer.nodeType) { case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: newText = this.startContainer.splitText(this.startOffset); this.startContainer.parentNode.insertBefore(newNode, newText); break; default: if (this.startContainer.childNodes.length == 0) { offset = null; } else { offset = this.startContainer.childNodes(this.startOffset); } this.startContainer.insertBefore(newNode, offset); } } catch (e) {} } function selectNode(refNode) { this.setStartBefore(refNode); this.setEndAfter(refNode); } function selectNodeContents(refNode) { this.setStart(refNode, 0); this.setEnd(refNode, refNode.childNodes.length); } function setStart(refNode, offset) { try { var endRootContainer, startRootContainer; this.startContainer = refNode; this.startOffset = offset; endRootContainer = this.endContainer; while (endRootContainer.parentNode) { endRootContainer = endRootContainer.parentNode; } startRootContainer = this.startContainer; while (startRootContainer.parentNode) { startRootContainer = startRootContainer.parentNode; } if (startRootContainer != endRootContainer) { this.collapse(true); } else { if (_compareBoundaryPoints(this, this.startContainer, this.startOffset, this.endContainer, this.endOffset) > 0) { this.collapse(true); } } this.collapsed = _isCollapsed(this); this.commonAncestorContainer = _commonAncestorContainer(this.startContainer, this.endContainer); } catch (e) {} } function setStartAfter(refNode) { this.setStart(refNode.parentNode, _nodeIndex(refNode) + 1); } function setStartBefore(refNode) { this.setStart(refNode.parentNode, _nodeIndex(refNode)); } function setEnd(refNode, offset) { try { this.endContainer = refNode; this.endOffset = offset; endRootContainer = this.endContainer; while (endRootContainer.parentNode) { endRootContainer = endRootContainer.parentNode; } startRootContainer = this.startContainer; while (startRootContainer.parentNode) { startRootContainer = startRootContainer.parentNode; } if (startRootContainer != endRootContainer) { this.collapse(false); } else { if (_compareBoundaryPoints(this, this.startContainer, this.startOffset, this.endContainer, this.endOffset) > 0) { this.collapse(false); } } this.collapsed = _isCollapsed(this); this.commonAncestorContainer = _commonAncestorContainer(this.startContainer, this.endContainer); } catch (e) {} } function setEndAfter(refNode) { this.setEnd(refNode.parentNode, _nodeIndex(refNode) + 1); } function setEndBefore(refNode) { this.setEnd(refNode.parentNode, _nodeIndex(refNode)); } function surroundContents(newParent) { try { var n, fragment; while (newParent.firstChild) { newParent.removeChild(newParent.firstChild); } fragment = this.extractContents(); this.insertNode(newParent); newParent.appendChild(fragment); this.selectNode(newParent); } catch (e) {} } function _compareBoundaryPoints(range, containerA, offsetA, containerB, offsetB) { var c, offsetC, n, cmnRoot, childA; if (containerA == containerB) { if (offsetA == offsetB) { return 0; // equal } else if (offsetA < offsetB) { return -1; // before } else { return 1; // after } } c = containerB; while (c && c.parentNode != containerA) { c = c.parentNode; } if (c) { offsetC = 0; n = containerA.firstChild; while (n != c && offsetC < offsetA) { offsetC++; n = n.nextSibling; } if (offsetA <= offsetC) { return -1; // before } else { return 1; // after } } c = containerA; while (c && c.parentNode != containerB) { c = c.parentNode; } if (c) { offsetC = 0; n = containerB.firstChild; while (n != c && offsetC < offsetB) { offsetC++; n = n.nextSibling; } if (offsetC < offsetB) { return -1; // before } else { return 1; // after } } cmnRoot = range._commonAncestorContainer(containerA, containerB); childA = containerA; while (childA && childA.parentNode != cmnRoot) { childA = childA.parentNode; } if (!childA) { childA = cmnRoot; } childB = containerB; while (childB && childB.parentNode != cmnRoot) { childB = childB.parentNode; } if (!childB) { childB = cmnRoot; } if (childA == childB) { return 0; // equal } n = cmnRoot.firstChild; while (n) { if (n == childA) { return -1; // before } if (n == childB) { return 1; // after } n = n.nextSibling; } return null; } function _commonAncestorContainer(containerA, containerB) { var parentStart = containerA, parentEnd; while (parentStart) { parentEnd = containerB; while (parentEnd && parentStart != parentEnd) { parentEnd = parentEnd.parentNode; } if (parentStart == parentEnd) { break; } parentStart = parentStart.parentNode; } if (!parentStart && containerA.ownerDocument) { return containerA.ownerDocument.documentElement; } return parentStart; } function _isCollapsed(range) { return (range.startContainer == range.endContainer && range.startOffset == range.endOffset); } function _offsetInCharacters(node) { switch (node.nodeType) { case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.ELEMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: return true; default: return false; } } function _processContents(range, action) { try { var cmnRoot, partialStart = null, partialEnd = null, fragment, n, c, i; var leftContents, leftParent, leftContentsParent; var rightContents, rightParent, rightContentsParent; var next, prev; var processStart, processEnd; if (range.collapsed) { return null; } cmnRoot = range.commonAncestorContainer; if (range.startContainer != cmnRoot) { partialStart = range.startContainer; while (partialStart.parentNode != cmnRoot) { partialStart = partialStart.parentNode; } } if (range.endContainer != cmnRoot) { partialEnd = range.endContainer; while (partialEnd.parentNode != cmnRoot) { partialEnd = partialEnd.parentNode; } } if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { fragment = range.ownerDocument.createDocumentFragment(); } if (range.startContainer == range.endContainer) { switch (range.startContainer.nodeType) { case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.TEXT_NODE: if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { c = range.startContainer.cloneNode(); c.deleteData(range.endOffset, range.startContainer.data.length - range.endOffset); c.deleteData(0, range.startOffset); fragment.appendChild(c); } if (action == Range.EXTRACT_CONTENTS || action == Range.DELETE_CONTENTS) { range.startContainer.deleteData(range.startOffset, range.endOffset - range.startOffset); } break; case Node.PROCESSING_INSTRUCTION_NODE: break; default: n = range.startContainer.firstChild; for (i = 0; i < range.startOffset; i++) { n = n.nextSibling; } while (n && i < range.endOffset) { next = n.nextSibling; if (action == Range.EXTRACT_CONTENTS) { fragment.appendChild(n); } else if (action == Range.CLONE_CONTENTS) { fragment.appendChild(n.cloneNode()); } else { range.startContainer.removeChild(n); } n = next; i++; } } range.collapse(true); return fragment; } if (range.startContainer != cmnRoot) { switch (range.startContainer.nodeType) { case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.TEXT_NODE: if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { c = range.startContainer.cloneNode(true); c.deleteData(0, range.startOffset); leftContents = c; } if (action == Range.EXTRACT_CONTENTS || action == Range.DELETE_CONTENTS) { range.startContainer.deleteData(range.startOffset, range.startContainer.data.length - range.startOffset); } break; case Node.PROCESSING_INSTRUCTION_NODE: break; default: if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { leftContents = range.startContainer.cloneNode(false); } n = range.startContainer.firstChild; for (i = 0; i < range.startOffset; i++) { n = n.nextSibling; } while (n && i < range.endOffset) { next = n.nextSibling; if (action == Range.EXTRACT_CONTENTS) { fragment.appendChild(n); } else if (action == Range.CLONE_CONTENTS) { fragment.appendChild(n.cloneNode()); } else { range.startContainer.removeChild(n); } n = next; i++; } } leftParent = range.startContainer.parentNode; n = range.startContainer.nextSibling; for(; leftParent != cmnRoot; leftParent = leftParent.parentNode) { if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { leftContentsParent = leftParent.cloneNode(false); leftContentsParent.appendChild(leftContents); leftContents = leftContentsParent; } for (; n; n = next) { next = n.nextSibling; if (action == Range.EXTRACT_CONTENTS) { leftContents.appendChild(n); } else if (action == Range.CLONE_CONTENTS) { leftContents.appendChild(n.cloneNode(true)); } else { leftParent.removeChild(n); } } n = leftParent.nextSibling; } } if (range.endContainer != cmnRoot) { switch (range.endContainer.nodeType) { case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.TEXT_NODE: if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { c = range.endContainer.cloneNode(true); c.deleteData(range.endOffset, range.endContainer.data.length - range.endOffset); rightContents = c; } if (action == Range.EXTRACT_CONTENTS || action == Range.DELETE_CONTENTS) { range.endContainer.deleteData(0, range.endOffset); } break; case Node.PROCESSING_INSTRUCTION_NODE: break; default: if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { rightContents = range.endContainer.cloneNode(false); } n = range.endContainer.firstChild; if (n && range.endOffset) { for (i = 0; i+1 < range.endOffset; i++) { next = n.nextSibling; if (!next) { break; } n = next; } for (; n; n = prev) { prev = n.previousSibling; if (action == Range.EXTRACT_CONTENTS) { rightContents.insertBefore(n, rightContents.firstChild); } else if (action == Range.CLONE_CONTENTS) { rightContents.insertBefore(n.cloneNode(True), rightContents.firstChild); } else { range.endContainer.removeChild(n); } } } } rightParent = range.endContainer.parentNode; n = range.endContainer.previousSibling; for(; rightParent != cmnRoot; rightParent = rightParent.parentNode) { if (action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) { rightContentsParent = rightContents.cloneNode(false); rightContentsParent.appendChild(rightContents); rightContents = rightContentsParent; } for (; n; n = prev) { prev = n.previousSibling; if (action == Range.EXTRACT_CONTENTS) { rightContents.insertBefore(n, rightContents.firstChild); } else if (action == Range.CLONE_CONTENTS) { rightContents.appendChild(n.cloneNode(true), rightContents.firstChild); } else { rightParent.removeChild(n); } } n = rightParent.previousSibling; } } if (range.startContainer == cmnRoot) { processStart = range.startContainer.firstChild; for (i = 0; i < range.startOffset; i++) { processStart = processStart.nextSibling; } } else { processStart = range.startContainer; while (processStart.parentNode != cmnRoot) { processStart = processStart.parentNode; } processStart = processStart.nextSibling; } if (range.endContainer == cmnRoot) { processEnd = range.endContainer.firstChild; for (i = 0; i < range.endOffset; i++) { processEnd = processEnd.nextSibling; } } else { processEnd = range.endContainer; while (processEnd.parentNode != cmnRoot) { processEnd = processEnd.parentNode; } } if ((action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) && leftContents) { fragment.appendChild(leftContents); } if (processStart) { for (n = processStart; n && n != processEnd; n = next) { next = n.nextSibling; if (action == Range.EXTRACT_CONTENTS) { fragment.appendChild(n); } else if (action == Range.CLONE_CONTENTS) { fragment.appendChild(n.cloneNode(true)); } else { cmnRoot.removeChild(n); } } } if ((action == Range.EXTRACT_CONTENTS || action == Range.CLONE_CONTENTS) && rightContents) { fragment.appendChild(rightContents); } if (action == Range.EXTRACT_CONTENTS || action == Range.DELETE_CONTENTS) { if (!partialStart && !partialEnd) { range.collapse(true); } else if (partialStart) { range.startContainer = partialStart.parentNode; range.endContainer = partialStart.parentNode; range.startOffset = range.endOffset = range._nodeIndex(partialStart) + 1; } else if (partialEnd) { range.startContainer = partialEnd.parentNode; range.endContainer = partialEnd.parentNode; range.startOffset = range.endOffset = range._nodeIndex(partialEnd); } } return fragment; } catch (e) { return null; }; } function _nodeIndex(refNode) { var nodeIndex = 0; while (refNode.previousSibling) { nodeIndex++; refNode = refNode.previousSibling; } return nodeIndex; } return { setStart: setStart, setEnd: setEnd, setStartBefore: setStartBefore, setStartAfter: setStartAfter, setEndBefore: setEndBefore, setEndAfter: setEndAfter, collapse: collapse, selectNode: selectNode, selectNodeContents: selectNodeContents, compareBoundaryPoints: compareBoundaryPoints, deleteContents: deleteContents, extractContents: extractContents, cloneContents: cloneContents, insertNode: insertNode, surroundContents: surroundContents, cloneRange: cloneRange, toString: toString, detach: detach, _commonAncestorContainer: _commonAncestorContainer }; })()); } if (!window.getSelection) { window.getSelection = function() { return Selection.getInstance(); }; SelectionImpl = function() { this.anchorNode = null; this.anchorOffset = 0; this.focusNode = null; this.focusOffset = 0; this.isCollapsed = true; this.rangeCount = 0; this.ranges = []; }; Object.extend(SelectionImpl.prototype, (function() { function addRange(r) { return true; } function collapse() { return true; } function collapseToStart() { return true; } function collapseToEnd() { return true; } function getRangeAt() { return true; } function removeAllRanges() { this.anchorNode = null; this.anchorOffset = 0; this.focusNode = null; this.focusOffset = 0; this.isCollapsed = true; this.rangeCount = 0; this.ranges = []; } function _addRange(r) { if (r.startContainer.nodeType != Node.TEXT_NODE) { var start = this._getRightStart(r.startContainer); var startOffset = 0; } else { var start = r.startContainer; var startOffset = r.startOffset; } if (r.endContainer.nodeType != Node.TEXT_NODE) { var end = this._getRightEnd(r.endContainer); var endOffset = end.data.length; } else { var end = r.endContainer; var endOffset = r.endOffset; } var rStart = this._selectStart(start, startOffset); var rEnd = this._selectEnd(end,endOffset); rStart.setEndPoint('EndToStart', rEnd); rStart.select(); document.selection._selectedRange = r; } function _getRightStart(start, offset) { if (start.nodeType != Node.TEXT_NODE) { if (start.nodeType == Node.ELEMENT_NODE) { start = start.childNodes(offset); } return getNextTextNode(start); } else { return null; } } function _getRightEnd(end, offset) { if (end.nodeType != Node.TEXT_NODE) { if (end.nodeType == Node.ELEMENT_NODE) { end = end.childNodes(offset); } return getPreviousTextNode(end); } else { return null; } } function _selectStart(start, offset) { var r = document.body.createTextRange(); if (start.nodeType == Node.TEXT_NODE) { var moveCharacters = offset, node = start; var moveToNode = null, collapse = true; while (node.previousSibling) { switch (node.previousSibling.nodeType) { case Node.ELEMENT_NODE: moveToNode = node.previousSibling; collapse = false; break; case Node.TEXT_NODE: moveCharacters += node.previousSibling.data.length; } if (moveToNode != null) { break; } node = node.previousSibling; } if (moveToNode == null) { moveToNode = start.parentNode; } r.moveToElementText(moveToNode); r.collapse(collapse); r.move('Character', moveCharacters); return r; } else { return null; } } function _selectEnd(end, offset) { var r = document.body.createTextRange(), node = end; if (end.nodeType == 3) { var moveCharacters = end.data.length - offset; var moveToNode = null, collapse = false; while (node.nextSibling) { switch (node.nextSibling.nodeType) { case Node.ELEMENT_NODE: moveToNode = node.nextSibling; collapse = true; break; case Node.TEXT_NODE: moveCharacters += node.nextSibling.data.length; break; } if (moveToNode != null) { break; } node = node.nextSibling; } if (moveToNode == null) { moveToNode = end.parentNode; collapse = false; } switch (moveToNode.nodeName.toLowerCase()) { case 'p': case 'div': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': moveCharacters++; } r.moveToElementText(moveToNode); r.collapse(collapse); r.move('Character', -moveCharacters); return r; } return null; } function getPreviousTextNode(node) { var stack = []; var current = null; while (node) { stack = []; current = node; while (current) { while (current) { if (current.nodeType == 3 && current.data.replace(/^\s+|\s+$/, '').length) { return current; } if (current.previousSibling) { stack.push (current.previousSibling); } current = current.lastChild; } current = stack.pop(); } node = node.previousSibling; } return null; } function getNextTextNode(node) { var stack = []; var current = null; while (node) { stack = []; current = node; while (current) { while (current) { if (current.nodeType == 3 && current.data.replace(/^\s+|\s+$/, '').length) { return current; } if (current.nextSibling) { stack.push (current.nextSibling); } current = current.firstChild; } current = stack.pop(); } node = node.nextSibling; } return null; } return { removeAllRanges: removeAllRanges, _addRange: _addRange, _getRightStart: _getRightStart, _getRightEnd: _getRightEnd, _selectStart: _selectStart, _selectEnd: _selectEnd }; })()); Selection = new function() { var instance = null; this.getInstance = function() { if (instance == null) { return (instance = new SelectionImpl()); } else { return instance; } }; }; } Object.extend(Range.prototype, (function() { function getNode() { var node = this.commonAncestorContainer; if (this.startContainer == this.endContainer) if (this.startOffset - this.endOffset < 2) node = this.startContainer.childNodes[this.startOffset]; while (node.nodeType == Node.TEXT_NODE) node = node.parentNode; return node; } return { getNode: getNode }; })()); WysiHat.Selection = Class.create((function() { function initialize(editor) { this.window = editor.getWindow(); this.document = editor.getDocument(); if (Prototype.Browser.IE) { editor.observe('wysihat:cursormove', saveRange.bind(this)); editor.observe('wysihat:focus', restoreRange); } } function getSelection() { return this.window.getSelection ? this.window.getSelection() : this.document.selection; } function getRange() { var range = null, selection = this.getSelection(); try { if (selection.getRangeAt) range = selection.getRangeAt(0); else range = selection.createRange(); } catch(e) { return null; } if (Prototype.Browser.WebKit) { range.setStart(selection.baseNode, selection.baseOffset); range.setEnd(selection.extentNode, selection.extentOffset); } return range; } function selectNode(node) { var selection = this.getSelection(); if (Prototype.Browser.IE) { var range = createRangeFromElement(this.document, node); range.select(); } else if (Prototype.Browser.WebKit) { selection.setBaseAndExtent(node, 0, node, node.innerText.length); } else if (Prototype.Browser.Opera) { range = this.document.createRange(); range.selectNode(node); selection.removeAllRanges(); selection.addRange(range); } else { var range = createRangeFromElement(this.document, node); selection.removeAllRanges(); selection.addRange(range); } } function getNode() { var nodes = null, candidates = [], children, el; var range = this.getRange(); if (!range) return null; var parent; if (range.parentElement) parent = range.parentElement(); else parent = range.commonAncestorContainer; if (parent) { while (parent.nodeType != 1) parent = parent.parentNode; if (parent.nodeName.toLowerCase() != "body") { el = parent; do { el = el.parentNode; candidates[candidates.length] = el; } while (el.nodeName.toLowerCase() != "body"); } children = parent.all || parent.getElementsByTagName("*"); for (var j = 0; j < children.length; j++) candidates[candidates.length] = children[j]; nodes = [parent]; for (var ii = 0, r2; ii < candidates.length; ii++) { r2 = createRangeFromElement(this.document, candidates[ii]); if (r2 && compareRanges(range, r2)) nodes[nodes.length] = candidates[ii]; } } return nodes.first(); } function createRangeFromElement(document, node) { if (document.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(node); } else if (document.createRange) { var range = document.createRange(); range.selectNodeContents(node); } return range; } function compareRanges(r1, r2) { if (r1.compareEndPoints) { return !( r2.compareEndPoints('StartToStart', r1) == 1 && r2.compareEndPoints('EndToEnd', r1) == 1 && r2.compareEndPoints('StartToEnd', r1) == 1 && r2.compareEndPoints('EndToStart', r1) == 1 || r2.compareEndPoints('StartToStart', r1) == -1 && r2.compareEndPoints('EndToEnd', r1) == -1 && r2.compareEndPoints('StartToEnd', r1) == -1 && r2.compareEndPoints('EndToStart', r1) == -1 ); } else if (r1.compareBoundaryPoints) { return !( r2.compareBoundaryPoints(0, r1) == 1 && r2.compareBoundaryPoints(2, r1) == 1 && r2.compareBoundaryPoints(1, r1) == 1 && r2.compareBoundaryPoints(3, r1) == 1 || r2.compareBoundaryPoints(0, r1) == -1 && r2.compareBoundaryPoints(2, r1) == -1 && r2.compareBoundaryPoints(1, r1) == -1 && r2.compareBoundaryPoints(3, r1) == -1 ); } return null; }; function setBookmark() { var bookmark = this.document.getElementById('bookmark'); if (bookmark) bookmark.parentNode.removeChild(bookmark); bookmark = this.document.createElement('span'); bookmark.id = 'bookmark'; bookmark.innerHTML = '&nbsp;'; if (Prototype.Browser.IE) { var range = this.document.selection.createRange(); var parent = this.document.createElement('div'); parent.appendChild(bookmark); range.collapse(); range.pasteHTML(parent.innerHTML); } else { var range = this.getRange(); range.insertNode(bookmark); } } function moveToBookmark() { var bookmark = this.document.getElementById('bookmark'); if (!bookmark) return; if (Prototype.Browser.IE) { var range = this.getRange(); range.moveToElementText(bookmark); range.collapse(); range.select(); } else if (Prototype.Browser.WebKit) { var selection = this.getSelection(); selection.setBaseAndExtent(bookmark, 0, bookmark, 0); } else { var range = this.getRange(); range.setStartBefore(bookmark); } bookmark.parentNode.removeChild(bookmark); } var savedRange = null; function saveRange() { savedRange = this.getRange(); } function restoreRange() { if (savedRange) savedRange.select(); } return { initialize: initialize, getSelection: getSelection, getRange: getRange, getNode: getNode, selectNode: selectNode, setBookmark: setBookmark, moveToBookmark: moveToBookmark, restore: restoreRange }; })()); WysiHat.Toolbar = Class.create((function() { function initialize(editor) { this.editor = editor; this.element = this.createToolbarElement(); } function createToolbarElement() { var toolbar = new Element('div', { 'class': 'editor_toolbar' }); this.editor.insert({before: toolbar}); return toolbar; } function addButtonSet(set) { var toolbar = this; $A(set).each(function(button){ toolbar.addButton(button); }); } function addButton(options, handler) { options = $H(options); if (!options.get('name')) options.set('name', options.get('label').toLowerCase()); var name = options.get('name'); var button = this.createButtonElement(this.element, options); var handler = this.buttonHandler(name, options); this.observeButtonClick(button, handler); var handler = this.buttonStateHandler(name, options); this.observeStateChanges(button, name, handler); } function createButtonElement(toolbar, options) { var button = new Element('a', { 'class': 'button', 'href': '#' }); button.update('<span>' + options.get('label') + '</span>'); button.addClassName(options.get('name')); toolbar.appendChild(button); return button; } function buttonHandler(name, options) { if (options.handler) return options.handler; else if (options.get('handler')) return options.get('handler'); else return function(editor) { editor.execCommand(name); }; } function observeButtonClick(element, handler) { var toolbar = this; element.observe('click', function(event) { handler(toolbar.editor); toolbar.editor.fire("wysihat:change"); toolbar.editor.fire("wysihat:cursormove"); Event.stop(event); }); } function buttonStateHandler(name, options) { if (options.query) return options.query; else if (options.get('query')) return options.get('query'); else return function(editor) { return editor.queryCommandState(name); }; } function observeStateChanges(element, name, handler) { var toolbar = this; var previousState = false; toolbar.editor.observe("wysihat:cursormove", function(event) { var state = handler(toolbar.editor); if (state != previousState) { previousState = state; toolbar.updateButtonState(element, name, state); } }); } function updateButtonState(element, name, state) { if (state) element.addClassName('selected'); else element.removeClassName('selected'); } return { initialize: initialize, createToolbarElement: createToolbarElement, addButtonSet: addButtonSet, addButton: addButton, createButtonElement: createButtonElement, buttonHandler: buttonHandler, observeButtonClick: observeButtonClick, buttonStateHandler: buttonStateHandler, observeStateChanges: observeStateChanges, updateButtonState: updateButtonState }; })()); WysiHat.Toolbar.ButtonSets = {}; WysiHat.Toolbar.ButtonSets.Basic = $A([ { label: "Bold" }, { label: "Underline" }, { label: "Italic" } ]);
/* eslint no-console: ["error", { allow: ["warn", "error"] }] */ /* jshint esversion: 6, asi: true, node: true */ /* * index.js * * WebSSH2 - Web to SSH2 gateway * Bill Church - https://github.com/billchurch/WebSSH2 - May 2017 * */ const { config } = require('./server/app'); const { server } = require('./server/app'); server.listen({ host: config.listen.ip, port: config.listen.port }); // eslint-disable-next-line no-console console.log(`WebSSH2 service listening on ${config.listen.ip}:${config.listen.port}`); server.on('error', (err) => { if (err.code === 'EADDRINUSE') { config.listen.port += 1; console.warn(`WebSSH2 Address in use, retrying on port ${config.listen.port}`); setTimeout(() => { server.listen(config.listen.port); }, 250); } else { // eslint-disable-next-line no-console console.log(`WebSSH2 server.listen ERROR: ${err.code}`); } });
new function () { var a = 1; b(this.constructor.arguments.c); };
(() => { // packages/alpinejs/src/scheduler.js var flushPending = false; var flushing = false; var queue = []; function scheduler(callback) { queueJob(callback); } function queueJob(job) { if (!queue.includes(job)) queue.push(job); queueFlush(); } function queueFlush() { if (!flushing && !flushPending) { flushPending = true; queueMicrotask(flushJobs); } } function flushJobs() { flushPending = false; flushing = true; for (let i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; flushing = false; } // packages/alpinejs/src/reactivity.js var reactive; var effect; var release; var raw; var shouldSchedule = true; function disableEffectScheduling(callback) { shouldSchedule = false; callback(); shouldSchedule = true; } function setReactivityEngine(engine) { reactive = engine.reactive; release = engine.release; effect = (callback) => engine.effect(callback, {scheduler: (task) => { if (shouldSchedule) { scheduler(task); } else { task(); } }}); raw = engine.raw; } function overrideEffect(override) { effect = override; } function elementBoundEffect(el) { let cleanup2 = () => { }; let wrappedEffect = (callback) => { let effectReference = effect(callback); if (!el._x_effects) { el._x_effects = new Set(); el._x_runEffects = () => { el._x_effects.forEach((i) => i()); }; } el._x_effects.add(effectReference); cleanup2 = () => { if (effectReference === void 0) return; el._x_effects.delete(effectReference); release(effectReference); }; }; return [wrappedEffect, () => { cleanup2(); }]; } // packages/alpinejs/src/mutation.js var onAttributeAddeds = []; var onElRemoveds = []; var onElAddeds = []; function onElAdded(callback) { onElAddeds.push(callback); } function onElRemoved(callback) { onElRemoveds.push(callback); } function onAttributesAdded(callback) { onAttributeAddeds.push(callback); } function onAttributeRemoved(el, name, callback) { if (!el._x_attributeCleanups) el._x_attributeCleanups = {}; if (!el._x_attributeCleanups[name]) el._x_attributeCleanups[name] = []; el._x_attributeCleanups[name].push(callback); } function cleanupAttributes(el, names) { if (!el._x_attributeCleanups) return; Object.entries(el._x_attributeCleanups).forEach(([name, value]) => { (names === void 0 || names.includes(name)) && value.forEach((i) => i()); delete el._x_attributeCleanups[name]; }); } var observer = new MutationObserver(onMutate); var currentlyObserving = false; function startObservingMutations() { observer.observe(document, {subtree: true, childList: true, attributes: true, attributeOldValue: true}); currentlyObserving = true; } function stopObservingMutations() { observer.disconnect(); currentlyObserving = false; } var recordQueue = []; var willProcessRecordQueue = false; function flushObserver() { recordQueue = recordQueue.concat(observer.takeRecords()); if (recordQueue.length && !willProcessRecordQueue) { willProcessRecordQueue = true; queueMicrotask(() => { processRecordQueue(); willProcessRecordQueue = false; }); } } function processRecordQueue() { onMutate(recordQueue); recordQueue.length = 0; } function mutateDom(callback) { if (!currentlyObserving) return callback(); flushObserver(); stopObservingMutations(); let result = callback(); startObservingMutations(); return result; } function onMutate(mutations) { let addedNodes = []; let removedNodes = []; let addedAttributes = new Map(); let removedAttributes = new Map(); for (let i = 0; i < mutations.length; i++) { if (mutations[i].target._x_ignoreMutationObserver) continue; if (mutations[i].type === "childList") { mutations[i].addedNodes.forEach((node) => node.nodeType === 1 && addedNodes.push(node)); mutations[i].removedNodes.forEach((node) => node.nodeType === 1 && removedNodes.push(node)); } if (mutations[i].type === "attributes") { let el = mutations[i].target; let name = mutations[i].attributeName; let oldValue = mutations[i].oldValue; let add2 = () => { if (!addedAttributes.has(el)) addedAttributes.set(el, []); addedAttributes.get(el).push({name, value: el.getAttribute(name)}); }; let remove = () => { if (!removedAttributes.has(el)) removedAttributes.set(el, []); removedAttributes.get(el).push(name); }; if (el.hasAttribute(name) && oldValue === null) { add2(); } else if (el.hasAttribute(name)) { remove(); add2(); } else { remove(); } } } removedAttributes.forEach((attrs, el) => { cleanupAttributes(el, attrs); }); addedAttributes.forEach((attrs, el) => { onAttributeAddeds.forEach((i) => i(el, attrs)); }); for (let node of addedNodes) { if (removedNodes.includes(node)) continue; onElAddeds.forEach((i) => i(node)); } for (let node of removedNodes) { if (addedNodes.includes(node)) continue; onElRemoveds.forEach((i) => i(node)); } addedNodes = null; removedNodes = null; addedAttributes = null; removedAttributes = null; } // packages/alpinejs/src/scope.js function addScopeToNode(node, data2, referenceNode) { node._x_dataStack = [data2, ...closestDataStack(referenceNode || node)]; return () => { node._x_dataStack = node._x_dataStack.filter((i) => i !== data2); }; } function refreshScope(element, scope) { let existingScope = element._x_dataStack[0]; Object.entries(scope).forEach(([key, value]) => { existingScope[key] = value; }); } function closestDataStack(node) { if (node._x_dataStack) return node._x_dataStack; if (node instanceof ShadowRoot) { return closestDataStack(node.host); } if (!node.parentNode) { return []; } return closestDataStack(node.parentNode); } function mergeProxies(objects) { return new Proxy({}, { ownKeys: () => { return Array.from(new Set(objects.flatMap((i) => Object.keys(i)))); }, has: (target, name) => { return objects.some((obj) => obj.hasOwnProperty(name)); }, get: (target, name) => { return (objects.find((obj) => obj.hasOwnProperty(name)) || {})[name]; }, set: (target, name, value) => { let closestObjectWithKey = objects.find((obj) => obj.hasOwnProperty(name)); if (closestObjectWithKey) { closestObjectWithKey[name] = value; } else { objects[objects.length - 1][name] = value; } return true; } }); } // packages/alpinejs/src/interceptor.js function initInterceptors(data2) { let isObject2 = (val) => typeof val === "object" && !Array.isArray(val) && val !== null; let recurse = (obj, basePath = "") => { Object.entries(obj).forEach(([key, value]) => { let path = basePath === "" ? key : `${basePath}.${key}`; if (typeof value === "object" && value !== null && value._x_interceptor) { obj[key] = value.initialize(data2, path, key); } else { if (isObject2(value) && value !== obj && !(value instanceof Element)) { recurse(value, path); } } }); }; return recurse(data2); } function interceptor(callback, mutateObj = () => { }) { let obj = { initialValue: void 0, _x_interceptor: true, initialize(data2, path, key) { return callback(this.initialValue, () => get(data2, path), (value) => set(data2, path, value), path, key); } }; mutateObj(obj); return (initialValue) => { if (typeof initialValue === "object" && initialValue !== null && initialValue._x_interceptor) { let initialize = obj.initialize.bind(obj); obj.initialize = (data2, path, key) => { let innerValue = initialValue.initialize(data2, path, key); obj.initialValue = innerValue; return initialize(data2, path, key); }; } else { obj.initialValue = initialValue; } return obj; }; } function get(obj, path) { return path.split(".").reduce((carry, segment) => carry[segment], obj); } function set(obj, path, value) { if (typeof path === "string") path = path.split("."); if (path.length === 1) obj[path[0]] = value; else if (path.length === 0) throw error; else { if (obj[path[0]]) return set(obj[path[0]], path.slice(1), value); else { obj[path[0]] = {}; return set(obj[path[0]], path.slice(1), value); } } } // packages/alpinejs/src/magics.js var magics = {}; function magic(name, callback) { magics[name] = callback; } function injectMagics(obj, el) { Object.entries(magics).forEach(([name, callback]) => { Object.defineProperty(obj, `$${name}`, { get() { return callback(el, {Alpine: alpine_default, interceptor}); }, enumerable: false }); }); return obj; } // packages/alpinejs/src/evaluator.js function evaluate(el, expression, extras = {}) { let result; evaluateLater(el, expression)((value) => result = value, extras); return result; } function evaluateLater(...args) { return theEvaluatorFunction(...args); } var theEvaluatorFunction = normalEvaluator; function setEvaluator(newEvaluator) { theEvaluatorFunction = newEvaluator; } function normalEvaluator(el, expression) { let overriddenMagics = {}; injectMagics(overriddenMagics, el); let dataStack = [overriddenMagics, ...closestDataStack(el)]; if (typeof expression === "function") { return generateEvaluatorFromFunction(dataStack, expression); } let evaluator = generateEvaluatorFromString(dataStack, expression); return tryCatch.bind(null, el, expression, evaluator); } function generateEvaluatorFromFunction(dataStack, func) { return (receiver = () => { }, {scope = {}, params = []} = {}) => { let result = func.apply(mergeProxies([scope, ...dataStack]), params); runIfTypeOfFunction(receiver, result); }; } var evaluatorMemo = {}; function generateFunctionFromString(expression) { if (evaluatorMemo[expression]) { return evaluatorMemo[expression]; } let AsyncFunction = Object.getPrototypeOf(async function() { }).constructor; let rightSideSafeExpression = /^[\n\s]*if.*\(.*\)/.test(expression) || /^(let|const)/.test(expression) ? `(() => { ${expression} })()` : expression; let func = new AsyncFunction(["__self", "scope"], `with (scope) { __self.result = ${rightSideSafeExpression} }; __self.finished = true; return __self.result;`); evaluatorMemo[expression] = func; return func; } function generateEvaluatorFromString(dataStack, expression) { let func = generateFunctionFromString(expression); return (receiver = () => { }, {scope = {}, params = []} = {}) => { func.result = void 0; func.finished = false; let completeScope = mergeProxies([scope, ...dataStack]); let promise = func(func, completeScope); if (func.finished) { runIfTypeOfFunction(receiver, func.result, completeScope, params); } else { promise.then((result) => { runIfTypeOfFunction(receiver, result, completeScope, params); }); } }; } function runIfTypeOfFunction(receiver, value, scope, params) { if (typeof value === "function") { let result = value.apply(scope, params); if (result instanceof Promise) { result.then((i) => runIfTypeOfFunction(receiver, i, scope, params)); } else { receiver(result); } } else { receiver(value); } } function tryCatch(el, expression, callback, ...args) { try { return callback(...args); } catch (e) { console.warn(`Alpine Expression Error: ${e.message} Expression: "${expression}" `, el); throw e; } } // packages/alpinejs/src/directives.js var prefixAsString = "x-"; function prefix(subject = "") { return prefixAsString + subject; } function setPrefix(newPrefix) { prefixAsString = newPrefix; } var directiveHandlers = {}; function directive(name, callback) { directiveHandlers[name] = callback; } function directives(el, attributes, originalAttributeOverride) { let transformedAttributeMap = {}; let directives2 = Array.from(attributes).map(toTransformedAttributes((newName, oldName) => transformedAttributeMap[newName] = oldName)).filter(outNonAlpineAttributes).map(toParsedDirectives(transformedAttributeMap, originalAttributeOverride)).sort(byPriority); return directives2.map((directive2) => { return getDirectiveHandler(el, directive2); }); } var isDeferringHandlers = false; var directiveHandlerStacks = new Map(); var currentHandlerStackKey = Symbol(); function deferHandlingDirectives(callback) { isDeferringHandlers = true; let key = Symbol(); currentHandlerStackKey = key; directiveHandlerStacks.set(key, []); let flushHandlers = () => { while (directiveHandlerStacks.get(key).length) directiveHandlerStacks.get(key).shift()(); directiveHandlerStacks.delete(key); }; let stopDeferring = () => { isDeferringHandlers = false; flushHandlers(); }; callback(flushHandlers); stopDeferring(); } function getDirectiveHandler(el, directive2) { let noop = () => { }; let handler3 = directiveHandlers[directive2.type] || noop; let cleanups = []; let cleanup2 = (callback) => cleanups.push(callback); let [effect3, cleanupEffect] = elementBoundEffect(el); cleanups.push(cleanupEffect); let utilities = { Alpine: alpine_default, effect: effect3, cleanup: cleanup2, evaluateLater: evaluateLater.bind(evaluateLater, el), evaluate: evaluate.bind(evaluate, el) }; let doCleanup = () => cleanups.forEach((i) => i()); onAttributeRemoved(el, directive2.original, doCleanup); let fullHandler = () => { if (el._x_ignore || el._x_ignoreSelf) return; handler3.inline && handler3.inline(el, directive2, utilities); handler3 = handler3.bind(handler3, el, directive2, utilities); isDeferringHandlers ? directiveHandlerStacks.get(currentHandlerStackKey).push(handler3) : handler3(); }; fullHandler.runCleanups = doCleanup; return fullHandler; } var startingWith = (subject, replacement) => ({name, value}) => { if (name.startsWith(subject)) name = name.replace(subject, replacement); return {name, value}; }; var into = (i) => i; function toTransformedAttributes(callback) { return ({name, value}) => { let {name: newName, value: newValue} = attributeTransformers.reduce((carry, transform) => { return transform(carry); }, {name, value}); if (newName !== name) callback(newName, name); return {name: newName, value: newValue}; }; } var attributeTransformers = []; function mapAttributes(callback) { attributeTransformers.push(callback); } function outNonAlpineAttributes({name}) { return alpineAttributeRegex().test(name); } var alpineAttributeRegex = () => new RegExp(`^${prefixAsString}([^:^.]+)\\b`); function toParsedDirectives(transformedAttributeMap, originalAttributeOverride) { return ({name, value}) => { let typeMatch = name.match(alpineAttributeRegex()); let valueMatch = name.match(/:([a-zA-Z0-9\-:]+)/); let modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || []; let original = originalAttributeOverride || transformedAttributeMap[name] || name; return { type: typeMatch ? typeMatch[1] : null, value: valueMatch ? valueMatch[1] : null, modifiers: modifiers.map((i) => i.replace(".", "")), expression: value, original }; }; } var DEFAULT = "DEFAULT"; var directiveOrder = [ "ignore", "ref", "data", "bind", "init", "for", "model", "transition", "show", "if", DEFAULT, "element" ]; function byPriority(a, b) { let typeA = directiveOrder.indexOf(a.type) === -1 ? DEFAULT : a.type; let typeB = directiveOrder.indexOf(b.type) === -1 ? DEFAULT : b.type; return directiveOrder.indexOf(typeA) - directiveOrder.indexOf(typeB); } // packages/alpinejs/src/utils/dispatch.js function dispatch(el, name, detail = {}) { el.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true, cancelable: true })); } // packages/alpinejs/src/nextTick.js var tickStack = []; var isHolding = false; function nextTick(callback) { tickStack.push(callback); queueMicrotask(() => { isHolding || setTimeout(() => { releaseNextTicks(); }); }); } function releaseNextTicks() { isHolding = false; while (tickStack.length) tickStack.shift()(); } function holdNextTicks() { isHolding = true; } // packages/alpinejs/src/utils/walk.js function walk(el, callback) { if (el instanceof ShadowRoot) { Array.from(el.children).forEach((el2) => walk(el2, callback)); return; } let skip = false; callback(el, () => skip = true); if (skip) return; let node = el.firstElementChild; while (node) { walk(node, callback, false); node = node.nextElementSibling; } } // packages/alpinejs/src/utils/warn.js function warn(message, ...args) { console.warn(`Alpine Warning: ${message}`, ...args); } // packages/alpinejs/src/lifecycle.js function start() { if (!document.body) warn("Unable to initialize. Trying to load Alpine before `<body>` is available. Did you forget to add `defer` in Alpine's `<script>` tag?"); dispatch(document, "alpine:init"); dispatch(document, "alpine:initializing"); startObservingMutations(); onElAdded((el) => initTree(el, walk)); onElRemoved((el) => nextTick(() => destroyTree(el))); onAttributesAdded((el, attrs) => { directives(el, attrs).forEach((handle) => handle()); }); let outNestedComponents = (el) => !closestRoot(el.parentElement); Array.from(document.querySelectorAll(allSelectors())).filter(outNestedComponents).forEach((el) => { initTree(el); }); dispatch(document, "alpine:initialized"); } var rootSelectorCallbacks = []; var initSelectorCallbacks = []; function rootSelectors() { return rootSelectorCallbacks.map((fn) => fn()); } function allSelectors() { return rootSelectorCallbacks.concat(initSelectorCallbacks).map((fn) => fn()); } function addRootSelector(selectorCallback) { rootSelectorCallbacks.push(selectorCallback); } function addInitSelector(selectorCallback) { initSelectorCallbacks.push(selectorCallback); } function closestRoot(el) { if (!el) return; if (rootSelectors().some((selector) => el.matches(selector))) return el; if (!el.parentElement) return; return closestRoot(el.parentElement); } function isRoot(el) { return rootSelectors().some((selector) => el.matches(selector)); } function initTree(el, walker = walk) { deferHandlingDirectives(() => { walker(el, (el2, skip) => { directives(el2, el2.attributes).forEach((handle) => handle()); el2._x_ignore && skip(); }); }); } function destroyTree(root) { walk(root, (el) => cleanupAttributes(el)); } // packages/alpinejs/src/plugin.js function plugin(callback) { callback(alpine_default); } // packages/alpinejs/src/store.js var stores = {}; var isReactive = false; function store(name, value) { if (!isReactive) { stores = reactive(stores); isReactive = true; } if (value === void 0) { return stores[name]; } stores[name] = value; if (typeof value === "object" && value !== null && value.hasOwnProperty("init") && typeof value.init === "function") { stores[name].init(); } } function getStores() { return stores; } // packages/alpinejs/src/clone.js var isCloning = false; function skipDuringClone(callback) { return (...args) => isCloning || callback(...args); } function clone(oldEl, newEl) { newEl._x_dataStack = oldEl._x_dataStack; isCloning = true; dontRegisterReactiveSideEffects(() => { cloneTree(newEl); }); isCloning = false; } function cloneTree(el) { let hasRunThroughFirstEl = false; let shallowWalker = (el2, callback) => { walk(el2, (el3, skip) => { if (hasRunThroughFirstEl && isRoot(el3)) return skip(); hasRunThroughFirstEl = true; callback(el3, skip); }); }; initTree(el, shallowWalker); } function dontRegisterReactiveSideEffects(callback) { let cache = effect; overrideEffect((callback2, el) => { let storedEffect = cache(callback2); release(storedEffect); return () => { }; }); callback(); overrideEffect(cache); } // packages/alpinejs/src/datas.js var datas = {}; function data(name, callback) { datas[name] = callback; } function injectDataProviders(obj, context) { Object.entries(datas).forEach(([name, callback]) => { Object.defineProperty(obj, name, { get() { return (...args) => { return callback.bind(context)(...args); }; }, enumerable: false }); }); return obj; } // packages/alpinejs/src/alpine.js var Alpine = { get reactive() { return reactive; }, get release() { return release; }, get effect() { return effect; }, get raw() { return raw; }, version: "3.3.0", disableEffectScheduling, setReactivityEngine, addRootSelector, mapAttributes, evaluateLater, setEvaluator, closestRoot, interceptor, mutateDom, directive, evaluate, initTree, nextTick, prefix: setPrefix, plugin, magic, store, start, clone, data }; var alpine_default = Alpine; // node_modules/@vue/shared/dist/shared.esm-bundler.js function makeMap(str, expectsLowerCase) { const map = Object.create(null); const list = str.split(","); for (let i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? (val) => !!map[val.toLowerCase()] : (val) => !!map[val]; } var PatchFlagNames = { [1]: `TEXT`, [2]: `CLASS`, [4]: `STYLE`, [8]: `PROPS`, [16]: `FULL_PROPS`, [32]: `HYDRATE_EVENTS`, [64]: `STABLE_FRAGMENT`, [128]: `KEYED_FRAGMENT`, [256]: `UNKEYED_FRAGMENT`, [512]: `NEED_PATCH`, [1024]: `DYNAMIC_SLOTS`, [2048]: `DEV_ROOT_FRAGMENT`, [-1]: `HOISTED`, [-2]: `BAIL` }; var slotFlagsText = { [1]: "STABLE", [2]: "DYNAMIC", [3]: "FORWARDED" }; var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; var isBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`); var EMPTY_OBJ = true ? Object.freeze({}) : {}; var EMPTY_ARR = true ? Object.freeze([]) : []; var extend = Object.assign; var hasOwnProperty = Object.prototype.hasOwnProperty; var hasOwn = (val, key) => hasOwnProperty.call(val, key); var isArray = Array.isArray; var isMap = (val) => toTypeString(val) === "[object Map]"; var isString = (val) => typeof val === "string"; var isSymbol = (val) => typeof val === "symbol"; var isObject = (val) => val !== null && typeof val === "object"; var objectToString = Object.prototype.toString; var toTypeString = (value) => objectToString.call(value); var toRawType = (value) => { return toTypeString(value).slice(8, -1); }; var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; var cacheStringFunction = (fn) => { const cache = Object.create(null); return (str) => { const hit = cache[str]; return hit || (cache[str] = fn(str)); }; }; var camelizeRE = /-(\w)/g; var camelize = cacheStringFunction((str) => { return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); }); var hyphenateRE = /\B([A-Z])/g; var hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase()); var capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1)); var toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``); var hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue); // node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js var targetMap = new WeakMap(); var effectStack = []; var activeEffect; var ITERATE_KEY = Symbol(true ? "iterate" : ""); var MAP_KEY_ITERATE_KEY = Symbol(true ? "Map key iterate" : ""); function isEffect(fn) { return fn && fn._isEffect === true; } function effect2(fn, options = EMPTY_OBJ) { if (isEffect(fn)) { fn = fn.raw; } const effect3 = createReactiveEffect(fn, options); if (!options.lazy) { effect3(); } return effect3; } function stop(effect3) { if (effect3.active) { cleanup(effect3); if (effect3.options.onStop) { effect3.options.onStop(); } effect3.active = false; } } var uid = 0; function createReactiveEffect(fn, options) { const effect3 = function reactiveEffect() { if (!effect3.active) { return fn(); } if (!effectStack.includes(effect3)) { cleanup(effect3); try { enableTracking(); effectStack.push(effect3); activeEffect = effect3; return fn(); } finally { effectStack.pop(); resetTracking(); activeEffect = effectStack[effectStack.length - 1]; } } }; effect3.id = uid++; effect3.allowRecurse = !!options.allowRecurse; effect3._isEffect = true; effect3.active = true; effect3.raw = fn; effect3.deps = []; effect3.options = options; return effect3; } function cleanup(effect3) { const {deps} = effect3; if (deps.length) { for (let i = 0; i < deps.length; i++) { deps[i].delete(effect3); } deps.length = 0; } } var shouldTrack = true; var trackStack = []; function pauseTracking() { trackStack.push(shouldTrack); shouldTrack = false; } function enableTracking() { trackStack.push(shouldTrack); shouldTrack = true; } function resetTracking() { const last = trackStack.pop(); shouldTrack = last === void 0 ? true : last; } function track(target, type, key) { if (!shouldTrack || activeEffect === void 0) { return; } let depsMap = targetMap.get(target); if (!depsMap) { targetMap.set(target, depsMap = new Map()); } let dep = depsMap.get(key); if (!dep) { depsMap.set(key, dep = new Set()); } if (!dep.has(activeEffect)) { dep.add(activeEffect); activeEffect.deps.push(dep); if (activeEffect.options.onTrack) { activeEffect.options.onTrack({ effect: activeEffect, target, type, key }); } } } function trigger(target, type, key, newValue, oldValue, oldTarget) { const depsMap = targetMap.get(target); if (!depsMap) { return; } const effects = new Set(); const add2 = (effectsToAdd) => { if (effectsToAdd) { effectsToAdd.forEach((effect3) => { if (effect3 !== activeEffect || effect3.allowRecurse) { effects.add(effect3); } }); } }; if (type === "clear") { depsMap.forEach(add2); } else if (key === "length" && isArray(target)) { depsMap.forEach((dep, key2) => { if (key2 === "length" || key2 >= newValue) { add2(dep); } }); } else { if (key !== void 0) { add2(depsMap.get(key)); } switch (type) { case "add": if (!isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } else if (isIntegerKey(key)) { add2(depsMap.get("length")); } break; case "delete": if (!isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } break; case "set": if (isMap(target)) { add2(depsMap.get(ITERATE_KEY)); } break; } } const run = (effect3) => { if (effect3.options.onTrigger) { effect3.options.onTrigger({ effect: effect3, target, key, type, newValue, oldValue, oldTarget }); } if (effect3.options.scheduler) { effect3.options.scheduler(effect3); } else { effect3(); } }; effects.forEach(run); } var isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`); var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).map((key) => Symbol[key]).filter(isSymbol)); var get2 = /* @__PURE__ */ createGetter(); var shallowGet = /* @__PURE__ */ createGetter(false, true); var readonlyGet = /* @__PURE__ */ createGetter(true); var shallowReadonlyGet = /* @__PURE__ */ createGetter(true, true); var arrayInstrumentations = {}; ["includes", "indexOf", "lastIndexOf"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { const arr = toRaw(this); for (let i = 0, l = this.length; i < l; i++) { track(arr, "get", i + ""); } const res = method.apply(arr, args); if (res === -1 || res === false) { return method.apply(arr, args.map(toRaw)); } else { return res; } }; }); ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { pauseTracking(); const res = method.apply(this, args); resetTracking(); return res; }; }); function createGetter(isReadonly = false, shallow = false) { return function get3(target, key, receiver) { if (key === "__v_isReactive") { return !isReadonly; } else if (key === "__v_isReadonly") { return isReadonly; } else if (key === "__v_raw" && receiver === (isReadonly ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) { return target; } const targetIsArray = isArray(target); if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) { return Reflect.get(arrayInstrumentations, key, receiver); } const res = Reflect.get(target, key, receiver); if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; } if (!isReadonly) { track(target, "get", key); } if (shallow) { return res; } if (isRef(res)) { const shouldUnwrap = !targetIsArray || !isIntegerKey(key); return shouldUnwrap ? res.value : res; } if (isObject(res)) { return isReadonly ? readonly(res) : reactive2(res); } return res; }; } var set2 = /* @__PURE__ */ createSetter(); var shallowSet = /* @__PURE__ */ createSetter(true); function createSetter(shallow = false) { return function set3(target, key, value, receiver) { let oldValue = target[key]; if (!shallow) { value = toRaw(value); oldValue = toRaw(oldValue); if (!isArray(target) && isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } } const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); if (target === toRaw(receiver)) { if (!hadKey) { trigger(target, "add", key, value); } else if (hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } } return result; }; } function deleteProperty(target, key) { const hadKey = hasOwn(target, key); const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function has(target, key) { const result = Reflect.has(target, key); if (!isSymbol(key) || !builtInSymbols.has(key)) { track(target, "has", key); } return result; } function ownKeys(target) { track(target, "iterate", isArray(target) ? "length" : ITERATE_KEY); return Reflect.ownKeys(target); } var mutableHandlers = { get: get2, set: set2, deleteProperty, has, ownKeys }; var readonlyHandlers = { get: readonlyGet, set(target, key) { if (true) { console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target); } return true; }, deleteProperty(target, key) { if (true) { console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target); } return true; } }; var shallowReactiveHandlers = extend({}, mutableHandlers, { get: shallowGet, set: shallowSet }); var shallowReadonlyHandlers = extend({}, readonlyHandlers, { get: shallowReadonlyGet }); var toReactive = (value) => isObject(value) ? reactive2(value) : value; var toReadonly = (value) => isObject(value) ? readonly(value) : value; var toShallow = (value) => value; var getProto = (v) => Reflect.getPrototypeOf(v); function get$1(target, key, isReadonly = false, isShallow = false) { target = target["__v_raw"]; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (key !== rawKey) { !isReadonly && track(rawTarget, "get", key); } !isReadonly && track(rawTarget, "get", rawKey); const {has: has2} = getProto(rawTarget); const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; if (has2.call(rawTarget, key)) { return wrap(target.get(key)); } else if (has2.call(rawTarget, rawKey)) { return wrap(target.get(rawKey)); } else if (target !== rawTarget) { target.get(key); } } function has$1(key, isReadonly = false) { const target = this["__v_raw"]; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (key !== rawKey) { !isReadonly && track(rawTarget, "has", key); } !isReadonly && track(rawTarget, "has", rawKey); return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); } function size(target, isReadonly = false) { target = target["__v_raw"]; !isReadonly && track(toRaw(target), "iterate", ITERATE_KEY); return Reflect.get(target, "size", target); } function add(value) { value = toRaw(value); const target = toRaw(this); const proto = getProto(target); const hadKey = proto.has.call(target, value); if (!hadKey) { target.add(value); trigger(target, "add", value, value); } return this; } function set$1(key, value) { value = toRaw(value); const target = toRaw(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw(key); hadKey = has2.call(target, key); } else if (true) { checkIdentityKeys(target, has2, key); } const oldValue = get3.call(target, key); target.set(key, value); if (!hadKey) { trigger(target, "add", key, value); } else if (hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } return this; } function deleteEntry(key) { const target = toRaw(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw(key); hadKey = has2.call(target, key); } else if (true) { checkIdentityKeys(target, has2, key); } const oldValue = get3 ? get3.call(target, key) : void 0; const result = target.delete(key); if (hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function clear() { const target = toRaw(this); const hadItems = target.size !== 0; const oldTarget = true ? isMap(target) ? new Map(target) : new Set(target) : void 0; const result = target.clear(); if (hadItems) { trigger(target, "clear", void 0, void 0, oldTarget); } return result; } function createForEach(isReadonly, isShallow) { return function forEach(callback, thisArg) { const observed = this; const target = observed["__v_raw"]; const rawTarget = toRaw(target); const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; !isReadonly && track(rawTarget, "iterate", ITERATE_KEY); return target.forEach((value, key) => { return callback.call(thisArg, wrap(value), wrap(key), observed); }); }; } function createIterableMethod(method, isReadonly, isShallow) { return function(...args) { const target = this["__v_raw"]; const rawTarget = toRaw(target); const targetIsMap = isMap(rawTarget); const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; const isKeyOnly = method === "keys" && targetIsMap; const innerIterator = target[method](...args); const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; !isReadonly && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY); return { next() { const {value, done} = innerIterator.next(); return done ? {value, done} : { value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), done }; }, [Symbol.iterator]() { return this; } }; }; } function createReadonlyMethod(type) { return function(...args) { if (true) { const key = args[0] ? `on key "${args[0]}" ` : ``; console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this)); } return type === "delete" ? false : this; }; } var mutableInstrumentations = { get(key) { return get$1(this, key); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, false) }; var shallowInstrumentations = { get(key) { return get$1(this, key, false, true); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, true) }; var readonlyInstrumentations = { get(key) { return get$1(this, key, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, false) }; var shallowReadonlyInstrumentations = { get(key) { return get$1(this, key, true, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, true) }; var iteratorMethods = ["keys", "values", "entries", Symbol.iterator]; iteratorMethods.forEach((method) => { mutableInstrumentations[method] = createIterableMethod(method, false, false); readonlyInstrumentations[method] = createIterableMethod(method, true, false); shallowInstrumentations[method] = createIterableMethod(method, false, true); shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true); }); function createInstrumentationGetter(isReadonly, shallow) { const instrumentations = shallow ? isReadonly ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly ? readonlyInstrumentations : mutableInstrumentations; return (target, key, receiver) => { if (key === "__v_isReactive") { return !isReadonly; } else if (key === "__v_isReadonly") { return isReadonly; } else if (key === "__v_raw") { return target; } return Reflect.get(hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver); }; } var mutableCollectionHandlers = { get: createInstrumentationGetter(false, false) }; var shallowCollectionHandlers = { get: createInstrumentationGetter(false, true) }; var readonlyCollectionHandlers = { get: createInstrumentationGetter(true, false) }; var shallowReadonlyCollectionHandlers = { get: createInstrumentationGetter(true, true) }; function checkIdentityKeys(target, has2, key) { const rawKey = toRaw(key); if (rawKey !== key && has2.call(target, rawKey)) { const type = toRawType(target); console.warn(`Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`); } } var reactiveMap = new WeakMap(); var shallowReactiveMap = new WeakMap(); var readonlyMap = new WeakMap(); var shallowReadonlyMap = new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { case "Object": case "Array": return 1; case "Map": case "Set": case "WeakMap": case "WeakSet": return 2; default: return 0; } } function getTargetType(value) { return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(toRawType(value)); } function reactive2(target) { if (target && target["__v_isReadonly"]) { return target; } return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); } function readonly(target) { return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); } function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) { if (!isObject(target)) { if (true) { console.warn(`value cannot be made reactive: ${String(target)}`); } return target; } if (target["__v_raw"] && !(isReadonly && target["__v_isReactive"])) { return target; } const existingProxy = proxyMap.get(target); if (existingProxy) { return existingProxy; } const targetType = getTargetType(target); if (targetType === 0) { return target; } const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers); proxyMap.set(target, proxy); return proxy; } function toRaw(observed) { return observed && toRaw(observed["__v_raw"]) || observed; } function isRef(r) { return Boolean(r && r.__v_isRef === true); } // packages/alpinejs/src/magics/$nextTick.js magic("nextTick", () => nextTick); // packages/alpinejs/src/magics/$dispatch.js magic("dispatch", (el) => dispatch.bind(dispatch, el)); // packages/alpinejs/src/magics/$watch.js magic("watch", (el) => (key, callback) => { let evaluate2 = evaluateLater(el, key); let firstTime = true; let oldValue; effect(() => evaluate2((value) => { let div = document.createElement("div"); div.dataset.throwAway = value; if (!firstTime) { queueMicrotask(() => { callback(value, oldValue); oldValue = value; }); } else { oldValue = value; } firstTime = false; })); }); // packages/alpinejs/src/magics/$store.js magic("store", getStores); // packages/alpinejs/src/magics/$root.js magic("root", (el) => closestRoot(el)); // packages/alpinejs/src/magics/$refs.js magic("refs", (el) => closestRoot(el)._x_refs || {}); // packages/alpinejs/src/magics/$el.js magic("el", (el) => el); // packages/alpinejs/src/utils/classes.js function setClasses(el, value) { if (Array.isArray(value)) { return setClassesFromString(el, value.join(" ")); } else if (typeof value === "object" && value !== null) { return setClassesFromObject(el, value); } else if (typeof value === "function") { return setClasses(el, value()); } return setClassesFromString(el, value); } function setClassesFromString(el, classString) { let split = (classString2) => classString2.split(" ").filter(Boolean); let missingClasses = (classString2) => classString2.split(" ").filter((i) => !el.classList.contains(i)).filter(Boolean); let addClassesAndReturnUndo = (classes) => { el.classList.add(...classes); return () => { el.classList.remove(...classes); }; }; classString = classString === true ? classString = "" : classString || ""; return addClassesAndReturnUndo(missingClasses(classString)); } function setClassesFromObject(el, classObject) { let split = (classString) => classString.split(" ").filter(Boolean); let forAdd = Object.entries(classObject).flatMap(([classString, bool]) => bool ? split(classString) : false).filter(Boolean); let forRemove = Object.entries(classObject).flatMap(([classString, bool]) => !bool ? split(classString) : false).filter(Boolean); let added = []; let removed = []; forRemove.forEach((i) => { if (el.classList.contains(i)) { el.classList.remove(i); removed.push(i); } }); forAdd.forEach((i) => { if (!el.classList.contains(i)) { el.classList.add(i); added.push(i); } }); return () => { removed.forEach((i) => el.classList.add(i)); added.forEach((i) => el.classList.remove(i)); }; } // packages/alpinejs/src/utils/styles.js function setStyles(el, value) { if (typeof value === "object" && value !== null) { return setStylesFromObject(el, value); } return setStylesFromString(el, value); } function setStylesFromObject(el, value) { let previousStyles = {}; Object.entries(value).forEach(([key, value2]) => { previousStyles[key] = el.style[key]; el.style.setProperty(kebabCase(key), value2); }); setTimeout(() => { if (el.style.length === 0) { el.removeAttribute("style"); } }); return () => { setStyles(el, previousStyles); }; } function setStylesFromString(el, value) { let cache = el.getAttribute("style", value); el.setAttribute("style", value); return () => { el.setAttribute("style", cache); }; } function kebabCase(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); } // packages/alpinejs/src/utils/once.js function once(callback, fallback = () => { }) { let called = false; return function() { if (!called) { called = true; callback.apply(this, arguments); } else { fallback.apply(this, arguments); } }; } // packages/alpinejs/src/directives/x-transition.js directive("transition", (el, {value, modifiers, expression}, {evaluate: evaluate2}) => { if (typeof expression === "function") expression = evaluate2(expression); if (!expression) { registerTransitionsFromHelper(el, modifiers, value); } else { registerTransitionsFromClassString(el, expression, value); } }); function registerTransitionsFromClassString(el, classString, stage) { registerTransitionObject(el, setClasses, ""); let directiveStorageMap = { enter: (classes) => { el._x_transition.enter.during = classes; }, "enter-start": (classes) => { el._x_transition.enter.start = classes; }, "enter-end": (classes) => { el._x_transition.enter.end = classes; }, leave: (classes) => { el._x_transition.leave.during = classes; }, "leave-start": (classes) => { el._x_transition.leave.start = classes; }, "leave-end": (classes) => { el._x_transition.leave.end = classes; } }; directiveStorageMap[stage](classString); } function registerTransitionsFromHelper(el, modifiers, stage) { registerTransitionObject(el, setStyles); let doesntSpecify = !modifiers.includes("in") && !modifiers.includes("out") && !stage; let transitioningIn = doesntSpecify || modifiers.includes("in") || ["enter"].includes(stage); let transitioningOut = doesntSpecify || modifiers.includes("out") || ["leave"].includes(stage); if (modifiers.includes("in") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index < modifiers.indexOf("out")); } if (modifiers.includes("out") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index > modifiers.indexOf("out")); } let wantsAll = !modifiers.includes("opacity") && !modifiers.includes("scale"); let wantsOpacity = wantsAll || modifiers.includes("opacity"); let wantsScale = wantsAll || modifiers.includes("scale"); let opacityValue = wantsOpacity ? 0 : 1; let scaleValue = wantsScale ? modifierValue(modifiers, "scale", 95) / 100 : 1; let delay = modifierValue(modifiers, "delay", 0); let origin = modifierValue(modifiers, "origin", "center"); let property = "opacity, transform"; let durationIn = modifierValue(modifiers, "duration", 150) / 1e3; let durationOut = modifierValue(modifiers, "duration", 75) / 1e3; let easing = `cubic-bezier(0.4, 0.0, 0.2, 1)`; if (transitioningIn) { el._x_transition.enter.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationIn}s`, transitionTimingFunction: easing }; el._x_transition.enter.start = { opacity: opacityValue, transform: `scale(${scaleValue})` }; el._x_transition.enter.end = { opacity: 1, transform: `scale(1)` }; } if (transitioningOut) { el._x_transition.leave.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationOut}s`, transitionTimingFunction: easing }; el._x_transition.leave.start = { opacity: 1, transform: `scale(1)` }; el._x_transition.leave.end = { opacity: opacityValue, transform: `scale(${scaleValue})` }; } } function registerTransitionObject(el, setFunction, defaultValue = {}) { if (!el._x_transition) el._x_transition = { enter: {during: defaultValue, start: defaultValue, end: defaultValue}, leave: {during: defaultValue, start: defaultValue, end: defaultValue}, in(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.enter.during, start: this.enter.start, end: this.enter.end, entering: true }, before, after); }, out(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.leave.during, start: this.leave.start, end: this.leave.end, entering: false }, before, after); } }; } window.Element.prototype._x_toggleAndCascadeWithTransitions = function(el, value, show, hide) { let clickAwayCompatibleShow = () => requestAnimationFrame(show); if (value) { el._x_transition ? el._x_transition.in(show) : clickAwayCompatibleShow(); return; } el._x_hidePromise = el._x_transition ? new Promise((resolve, reject) => { el._x_transition.out(() => { }, () => resolve(hide)); el._x_transitioning.beforeCancel(() => reject({isFromCancelledTransition: true})); }) : Promise.resolve(hide); queueMicrotask(() => { let closest = closestHide(el); if (closest) { if (!closest._x_hideChildren) closest._x_hideChildren = []; closest._x_hideChildren.push(el); } else { queueMicrotask(() => { let hideAfterChildren = (el2) => { let carry = Promise.all([ el2._x_hidePromise, ...(el2._x_hideChildren || []).map(hideAfterChildren) ]).then(([i]) => i()); delete el2._x_hidePromise; delete el2._x_hideChildren; return carry; }; hideAfterChildren(el).catch((e) => { if (!e.isFromCancelledTransition) throw e; }); }); } }); }; function closestHide(el) { let parent = el.parentNode; if (!parent) return; return parent._x_hidePromise ? parent : closestHide(parent); } function transition(el, setFunction, {during, start: start2, end, entering} = {}, before = () => { }, after = () => { }) { if (el._x_transitioning) el._x_transitioning.cancel(); if (Object.keys(during).length === 0 && Object.keys(start2).length === 0 && Object.keys(end).length === 0) { before(); after(); return; } let undoStart, undoDuring, undoEnd; performTransition(el, { start() { undoStart = setFunction(el, start2); }, during() { undoDuring = setFunction(el, during); }, before, end() { undoStart(); undoEnd = setFunction(el, end); }, after, cleanup() { undoDuring(); undoEnd(); } }, entering); } function performTransition(el, stages, entering) { let interrupted, reachedBefore, reachedEnd; let finish = once(() => { mutateDom(() => { interrupted = true; if (!reachedBefore) stages.before(); if (!reachedEnd) { stages.end(); releaseNextTicks(); } stages.after(); if (el.isConnected) stages.cleanup(); delete el._x_transitioning; }); }); el._x_transitioning = { beforeCancels: [], beforeCancel(callback) { this.beforeCancels.push(callback); }, cancel: once(function() { while (this.beforeCancels.length) { this.beforeCancels.shift()(); } ; finish(); }), finish, entering }; mutateDom(() => { stages.start(); stages.during(); }); holdNextTicks(); requestAnimationFrame(() => { if (interrupted) return; let duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, "").replace("s", "")) * 1e3; let delay = Number(getComputedStyle(el).transitionDelay.replace(/,.*/, "").replace("s", "")) * 1e3; if (duration === 0) duration = Number(getComputedStyle(el).animationDuration.replace("s", "")) * 1e3; mutateDom(() => { stages.before(); }); reachedBefore = true; requestAnimationFrame(() => { if (interrupted) return; mutateDom(() => { stages.end(); }); releaseNextTicks(); setTimeout(el._x_transitioning.finish, duration + delay); reachedEnd = true; }); }); } function modifierValue(modifiers, key, fallback) { if (modifiers.indexOf(key) === -1) return fallback; const rawValue = modifiers[modifiers.indexOf(key) + 1]; if (!rawValue) return fallback; if (key === "scale") { if (isNaN(rawValue)) return fallback; } if (key === "duration") { let match = rawValue.match(/([0-9]+)ms/); if (match) return match[1]; } if (key === "origin") { if (["top", "right", "left", "center", "bottom"].includes(modifiers[modifiers.indexOf(key) + 2])) { return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(" "); } } return rawValue; } // packages/alpinejs/src/directives/x-ignore.js var handler = () => { }; handler.inline = (el, {modifiers}, {cleanup: cleanup2}) => { modifiers.includes("self") ? el._x_ignoreSelf = true : el._x_ignore = true; cleanup2(() => { modifiers.includes("self") ? delete el._x_ignoreSelf : delete el._x_ignore; }); }; directive("ignore", handler); // packages/alpinejs/src/directives/x-effect.js directive("effect", (el, {expression}, {effect: effect3}) => effect3(evaluateLater(el, expression))); // packages/alpinejs/src/utils/bind.js function bind(el, name, value, modifiers = []) { if (!el._x_bindings) el._x_bindings = reactive({}); el._x_bindings[name] = value; name = modifiers.includes("camel") ? camelCase(name) : name; switch (name) { case "value": bindInputValue(el, value); break; case "style": bindStyles(el, value); break; case "class": bindClasses(el, value); break; default: bindAttribute(el, name, value); break; } } function bindInputValue(el, value) { if (el.type === "radio") { if (el.attributes.value === void 0) { el.value = value; } if (window.fromModel) { el.checked = checkedAttrLooseCompare(el.value, value); } } else if (el.type === "checkbox") { if (Number.isInteger(value)) { el.value = value; } else if (!Number.isInteger(value) && !Array.isArray(value) && typeof value !== "boolean" && ![null, void 0].includes(value)) { el.value = String(value); } else { if (Array.isArray(value)) { el.checked = value.some((val) => checkedAttrLooseCompare(val, el.value)); } else { el.checked = !!value; } } } else if (el.tagName === "SELECT") { updateSelect(el, value); } else { if (el.value === value) return; el.value = value; } } function bindClasses(el, value) { if (el._x_undoAddedClasses) el._x_undoAddedClasses(); el._x_undoAddedClasses = setClasses(el, value); } function bindStyles(el, value) { if (el._x_undoAddedStyles) el._x_undoAddedStyles(); el._x_undoAddedStyles = setStyles(el, value); } function bindAttribute(el, name, value) { if ([null, void 0, false].includes(value) && attributeShouldntBePreservedIfFalsy(name)) { el.removeAttribute(name); } else { if (isBooleanAttr2(name)) value = name; setIfChanged(el, name, value); } } function setIfChanged(el, attrName, value) { if (el.getAttribute(attrName) != value) { el.setAttribute(attrName, value); } } function updateSelect(el, value) { const arrayWrappedValue = [].concat(value).map((value2) => { return value2 + ""; }); Array.from(el.options).forEach((option) => { option.selected = arrayWrappedValue.includes(option.value); }); } function camelCase(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function checkedAttrLooseCompare(valueA, valueB) { return valueA == valueB; } function isBooleanAttr2(attrName) { const booleanAttributes = [ "disabled", "checked", "required", "readonly", "hidden", "open", "selected", "autofocus", "itemscope", "multiple", "novalidate", "allowfullscreen", "allowpaymentrequest", "formnovalidate", "autoplay", "controls", "loop", "muted", "playsinline", "default", "ismap", "reversed", "async", "defer", "nomodule" ]; return booleanAttributes.includes(attrName); } function attributeShouldntBePreservedIfFalsy(name) { return !["aria-pressed", "aria-checked"].includes(name); } // packages/alpinejs/src/utils/on.js function on(el, event, modifiers, callback) { let listenerTarget = el; let handler3 = (e) => callback(e); let options = {}; let wrapHandler = (callback2, wrapper) => (e) => wrapper(callback2, e); if (modifiers.includes("dot")) event = dotSyntax(event); if (modifiers.includes("camel")) event = camelCase2(event); if (modifiers.includes("passive")) options.passive = true; if (modifiers.includes("window")) listenerTarget = window; if (modifiers.includes("document")) listenerTarget = document; if (modifiers.includes("prevent")) handler3 = wrapHandler(handler3, (next, e) => { e.preventDefault(); next(e); }); if (modifiers.includes("stop")) handler3 = wrapHandler(handler3, (next, e) => { e.stopPropagation(); next(e); }); if (modifiers.includes("self")) handler3 = wrapHandler(handler3, (next, e) => { e.target === el && next(e); }); if (modifiers.includes("away") || modifiers.includes("outside")) { listenerTarget = document; handler3 = wrapHandler(handler3, (next, e) => { if (el.contains(e.target)) return; if (el.offsetWidth < 1 && el.offsetHeight < 1) return; next(e); }); } handler3 = wrapHandler(handler3, (next, e) => { if (isKeyEvent(event)) { if (isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers)) { return; } } next(e); }); if (modifiers.includes("debounce")) { let nextModifier = modifiers[modifiers.indexOf("debounce") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = debounce(handler3, wait, this); } if (modifiers.includes("throttle")) { let nextModifier = modifiers[modifiers.indexOf("throttle") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = throttle(handler3, wait, this); } if (modifiers.includes("once")) { handler3 = wrapHandler(handler3, (next, e) => { next(e); listenerTarget.removeEventListener(event, handler3, options); }); } listenerTarget.addEventListener(event, handler3, options); return () => { listenerTarget.removeEventListener(event, handler3, options); }; } function dotSyntax(subject) { return subject.replace(/-/g, "."); } function camelCase2(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function debounce(func, wait) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } function throttle(func, limit) { let inThrottle; return function() { let context = this, args = arguments; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } function isNumeric(subject) { return !Array.isArray(subject) && !isNaN(subject); } function kebabCase2(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]/, "-").toLowerCase(); } function isKeyEvent(event) { return ["keydown", "keyup"].includes(event); } function isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers) { let keyModifiers = modifiers.filter((i) => { return !["window", "document", "prevent", "stop", "once"].includes(i); }); if (keyModifiers.includes("debounce")) { let debounceIndex = keyModifiers.indexOf("debounce"); keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || "invalid-wait").split("ms")[0]) ? 2 : 1); } if (keyModifiers.length === 0) return false; if (keyModifiers.length === 1 && keyToModifiers(e.key).includes(keyModifiers[0])) return false; const systemKeyModifiers = ["ctrl", "shift", "alt", "meta", "cmd", "super"]; const selectedSystemKeyModifiers = systemKeyModifiers.filter((modifier) => keyModifiers.includes(modifier)); keyModifiers = keyModifiers.filter((i) => !selectedSystemKeyModifiers.includes(i)); if (selectedSystemKeyModifiers.length > 0) { const activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter((modifier) => { if (modifier === "cmd" || modifier === "super") modifier = "meta"; return e[`${modifier}Key`]; }); if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) { if (keyToModifiers(e.key).includes(keyModifiers[0])) return false; } } return true; } function keyToModifiers(key) { if (!key) return []; key = kebabCase2(key); let modifierToKeyMap = { ctrl: "control", slash: "/", space: "-", spacebar: "-", cmd: "meta", esc: "escape", up: "arrow-up", down: "arrow-down", left: "arrow-left", right: "arrow-right", period: ".", equal: "=" }; modifierToKeyMap[key] = key; return Object.keys(modifierToKeyMap).map((modifier) => { if (modifierToKeyMap[modifier] === key) return modifier; }).filter((modifier) => modifier); } // packages/alpinejs/src/directives/x-model.js directive("model", (el, {modifiers, expression}, {effect: effect3, cleanup: cleanup2}) => { let evaluate2 = evaluateLater(el, expression); let assignmentExpression = `${expression} = rightSideOfExpression($event, ${expression})`; let evaluateAssignment = evaluateLater(el, assignmentExpression); var event = el.tagName.toLowerCase() === "select" || ["checkbox", "radio"].includes(el.type) || modifiers.includes("lazy") ? "change" : "input"; let assigmentFunction = generateAssignmentFunction(el, modifiers, expression); let removeListener = on(el, event, modifiers, (e) => { evaluateAssignment(() => { }, {scope: { $event: e, rightSideOfExpression: assigmentFunction }}); }); cleanup2(() => removeListener()); el._x_forceModelUpdate = () => { evaluate2((value) => { if (value === void 0 && expression.match(/\./)) value = ""; window.fromModel = true; mutateDom(() => bind(el, "value", value)); delete window.fromModel; }); }; effect3(() => { if (modifiers.includes("unintrusive") && document.activeElement.isSameNode(el)) return; el._x_forceModelUpdate(); }); }); function generateAssignmentFunction(el, modifiers, expression) { if (el.type === "radio") { mutateDom(() => { if (!el.hasAttribute("name")) el.setAttribute("name", expression); }); } return (event, currentValue) => { return mutateDom(() => { if (event instanceof CustomEvent && event.detail !== void 0) { return event.detail || event.target.value; } else if (el.type === "checkbox") { if (Array.isArray(currentValue)) { let newValue = modifiers.includes("number") ? safeParseNumber(event.target.value) : event.target.value; return event.target.checked ? currentValue.concat([newValue]) : currentValue.filter((el2) => !checkedAttrLooseCompare2(el2, newValue)); } else { return event.target.checked; } } else if (el.tagName.toLowerCase() === "select" && el.multiple) { return modifiers.includes("number") ? Array.from(event.target.selectedOptions).map((option) => { let rawValue = option.value || option.text; return safeParseNumber(rawValue); }) : Array.from(event.target.selectedOptions).map((option) => { return option.value || option.text; }); } else { let rawValue = event.target.value; return modifiers.includes("number") ? safeParseNumber(rawValue) : modifiers.includes("trim") ? rawValue.trim() : rawValue; } }); }; } function safeParseNumber(rawValue) { let number = rawValue ? parseFloat(rawValue) : null; return isNumeric2(number) ? number : rawValue; } function checkedAttrLooseCompare2(valueA, valueB) { return valueA == valueB; } function isNumeric2(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-cloak.js directive("cloak", (el) => queueMicrotask(() => mutateDom(() => el.removeAttribute(prefix("cloak"))))); // packages/alpinejs/src/directives/x-init.js addInitSelector(() => `[${prefix("init")}]`); directive("init", skipDuringClone((el, {expression}) => !!expression.trim() && evaluate(el, expression, {}, false))); // packages/alpinejs/src/directives/x-text.js directive("text", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { mutateDom(() => { el.textContent = value; }); }); }); }); // packages/alpinejs/src/directives/x-html.js directive("html", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { el.innerHTML = value; }); }); }); // packages/alpinejs/src/directives/x-bind.js mapAttributes(startingWith(":", into(prefix("bind:")))); directive("bind", (el, {value, modifiers, expression, original}, {effect: effect3}) => { if (!value) return applyBindingsObject(el, expression, original, effect3); if (value === "key") return storeKeyForXFor(el, expression); let evaluate2 = evaluateLater(el, expression); effect3(() => evaluate2((result) => { if (result === void 0 && expression.match(/\./)) result = ""; mutateDom(() => bind(el, value, result, modifiers)); })); }); function applyBindingsObject(el, expression, original, effect3) { let getBindings = evaluateLater(el, expression); let cleanupRunners = []; effect3(() => { while (cleanupRunners.length) cleanupRunners.pop()(); getBindings((bindings) => { let attributes = Object.entries(bindings).map(([name, value]) => ({name, value})); directives(el, attributes, original).map((handle) => { cleanupRunners.push(handle.runCleanups); handle(); }); }); }); } function storeKeyForXFor(el, expression) { el._x_keyExpression = expression; } // packages/alpinejs/src/directives/x-data.js addRootSelector(() => `[${prefix("data")}]`); directive("data", skipDuringClone((el, {expression}, {cleanup: cleanup2}) => { expression = expression === "" ? "{}" : expression; let magicContext = {}; injectMagics(magicContext, el); let dataProviderContext = {}; injectDataProviders(dataProviderContext, magicContext); let data2 = evaluate(el, expression, {scope: dataProviderContext}); injectMagics(data2, el); let reactiveData = reactive(data2); initInterceptors(reactiveData); let undo = addScopeToNode(el, reactiveData); reactiveData["init"] && evaluate(el, reactiveData["init"]); cleanup2(() => { undo(); reactiveData["destroy"] && evaluate(el, reactiveData["destroy"]); }); })); // packages/alpinejs/src/directives/x-show.js directive("show", (el, {modifiers, expression}, {effect: effect3}) => { let evaluate2 = evaluateLater(el, expression); let hide = () => mutateDom(() => { el.style.display = "none"; el._x_isShown = false; }); let show = () => mutateDom(() => { if (el.style.length === 1 && el.style.display === "none") { el.removeAttribute("style"); } else { el.style.removeProperty("display"); } el._x_isShown = true; }); let clickAwayCompatibleShow = () => setTimeout(show); let toggle = once((value) => value ? show() : hide(), (value) => { if (typeof el._x_toggleAndCascadeWithTransitions === "function") { el._x_toggleAndCascadeWithTransitions(el, value, show, hide); } else { value ? clickAwayCompatibleShow() : hide(); } }); let oldValue; let firstTime = true; effect3(() => evaluate2((value) => { if (!firstTime && value === oldValue) return; if (modifiers.includes("immediate")) value ? clickAwayCompatibleShow() : hide(); toggle(value); oldValue = value; firstTime = false; })); }); // packages/alpinejs/src/directives/x-for.js directive("for", (el, {expression}, {effect: effect3, cleanup: cleanup2}) => { let iteratorNames = parseForExpression(expression); let evaluateItems = evaluateLater(el, iteratorNames.items); let evaluateKey = evaluateLater(el, el._x_keyExpression || "index"); el._x_prevKeys = []; el._x_lookup = {}; effect3(() => loop(el, iteratorNames, evaluateItems, evaluateKey)); cleanup2(() => { Object.values(el._x_lookup).forEach((el2) => el2.remove()); delete el._x_prevKeys; delete el._x_lookup; }); }); function loop(el, iteratorNames, evaluateItems, evaluateKey) { let isObject2 = (i) => typeof i === "object" && !Array.isArray(i); let templateEl = el; evaluateItems((items) => { if (isNumeric3(items) && items >= 0) { items = Array.from(Array(items).keys(), (i) => i + 1); } if (items === void 0) items = []; let lookup = el._x_lookup; let prevKeys = el._x_prevKeys; let scopes = []; let keys = []; if (isObject2(items)) { items = Object.entries(items).map(([key, value]) => { let scope = getIterationScopeVariables(iteratorNames, value, key, items); evaluateKey((value2) => keys.push(value2), {scope: {index: key, ...scope}}); scopes.push(scope); }); } else { for (let i = 0; i < items.length; i++) { let scope = getIterationScopeVariables(iteratorNames, items[i], i, items); evaluateKey((value) => keys.push(value), {scope: {index: i, ...scope}}); scopes.push(scope); } } let adds = []; let moves = []; let removes = []; let sames = []; for (let i = 0; i < prevKeys.length; i++) { let key = prevKeys[i]; if (keys.indexOf(key) === -1) removes.push(key); } prevKeys = prevKeys.filter((key) => !removes.includes(key)); let lastKey = "template"; for (let i = 0; i < keys.length; i++) { let key = keys[i]; let prevIndex = prevKeys.indexOf(key); if (prevIndex === -1) { prevKeys.splice(i, 0, key); adds.push([lastKey, i]); } else if (prevIndex !== i) { let keyInSpot = prevKeys.splice(i, 1)[0]; let keyForSpot = prevKeys.splice(prevIndex - 1, 1)[0]; prevKeys.splice(i, 0, keyForSpot); prevKeys.splice(prevIndex, 0, keyInSpot); moves.push([keyInSpot, keyForSpot]); } else { sames.push(key); } lastKey = key; } for (let i = 0; i < removes.length; i++) { let key = removes[i]; lookup[key].remove(); lookup[key] = null; delete lookup[key]; } for (let i = 0; i < moves.length; i++) { let [keyInSpot, keyForSpot] = moves[i]; let elInSpot = lookup[keyInSpot]; let elForSpot = lookup[keyForSpot]; let marker = document.createElement("div"); mutateDom(() => { elForSpot.after(marker); elInSpot.after(elForSpot); marker.before(elInSpot); marker.remove(); }); refreshScope(elForSpot, scopes[keys.indexOf(keyForSpot)]); } for (let i = 0; i < adds.length; i++) { let [lastKey2, index] = adds[i]; let lastEl = lastKey2 === "template" ? templateEl : lookup[lastKey2]; let scope = scopes[index]; let key = keys[index]; let clone2 = document.importNode(templateEl.content, true).firstElementChild; addScopeToNode(clone2, reactive(scope), templateEl); mutateDom(() => { lastEl.after(clone2); initTree(clone2); }); if (typeof key === "object") { warn("x-for key cannot be an object, it must be a string or an integer", templateEl); } lookup[key] = clone2; } for (let i = 0; i < sames.length; i++) { refreshScope(lookup[sames[i]], scopes[keys.indexOf(sames[i])]); } templateEl._x_prevKeys = keys; }); } function parseForExpression(expression) { let forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; let stripParensRE = /^\s*\(|\)\s*$/g; let forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; let inMatch = expression.match(forAliasRE); if (!inMatch) return; let res = {}; res.items = inMatch[2].trim(); let item = inMatch[1].replace(stripParensRE, "").trim(); let iteratorMatch = item.match(forIteratorRE); if (iteratorMatch) { res.item = item.replace(forIteratorRE, "").trim(); res.index = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.collection = iteratorMatch[2].trim(); } } else { res.item = item; } return res; } function getIterationScopeVariables(iteratorNames, item, index, items) { let scopeVariables = {}; if (/^\[.*\]$/.test(iteratorNames.item) && Array.isArray(item)) { let names = iteratorNames.item.replace("[", "").replace("]", "").split(",").map((i) => i.trim()); names.forEach((name, i) => { scopeVariables[name] = item[i]; }); } else { scopeVariables[iteratorNames.item] = item; } if (iteratorNames.index) scopeVariables[iteratorNames.index] = index; if (iteratorNames.collection) scopeVariables[iteratorNames.collection] = items; return scopeVariables; } function isNumeric3(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-ref.js function handler2() { } handler2.inline = (el, {expression}, {cleanup: cleanup2}) => { let root = closestRoot(el); if (!root._x_refs) root._x_refs = {}; root._x_refs[expression] = el; cleanup2(() => delete root._x_refs[expression]); }; directive("ref", handler2); // packages/alpinejs/src/directives/x-if.js directive("if", (el, {expression}, {effect: effect3, cleanup: cleanup2}) => { let evaluate2 = evaluateLater(el, expression); let show = () => { if (el._x_currentIfEl) return el._x_currentIfEl; let clone2 = el.content.cloneNode(true).firstElementChild; addScopeToNode(clone2, {}, el); mutateDom(() => { el.after(clone2); initTree(clone2); }); el._x_currentIfEl = clone2; el._x_undoIf = () => { clone2.remove(); delete el._x_currentIfEl; }; return clone2; }; let hide = () => { if (!el._x_undoIf) return; el._x_undoIf(); delete el._x_undoIf; }; effect3(() => evaluate2((value) => { value ? show() : hide(); })); cleanup2(() => el._x_undoIf && el._x_undoIf()); }); // packages/alpinejs/src/directives/x-on.js mapAttributes(startingWith("@", into(prefix("on:")))); directive("on", skipDuringClone((el, {value, modifiers, expression}, {cleanup: cleanup2}) => { let evaluate2 = expression ? evaluateLater(el, expression) : () => { }; let removeListener = on(el, value, modifiers, (e) => { evaluate2(() => { }, {scope: {$event: e}, params: [e]}); }); cleanup2(() => removeListener()); })); // packages/alpinejs/src/index.js alpine_default.setEvaluator(normalEvaluator); alpine_default.setReactivityEngine({reactive: reactive2, effect: effect2, release: stop, raw: toRaw}); var src_default = alpine_default; // packages/alpinejs/builds/cdn.js window.Alpine = src_default; queueMicrotask(() => { src_default.start(); }); })();
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2021 School of Management and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ /** * @fileOverview * @author Cyril Junod <cyril.junod at gmail.com> */ YUI.add("wegas-image", function(Y) { "use strict"; /** * @name Y.Wegas.Image * @extends Y.Widget * @borrows Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable * @class class to display simple image * @constructor * @description Display a string (given as ATTRS) in content box */ var Image = Y.Base.create("wegas-image", Y.Widget, [Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable], { /** @lends Y.Wegas.Image# */ image: null, CONTENT_TEMPLATE: "<img style='width:inherit;height:inherit'></img>", /** * Lifecycle method * @function * @private */ initializer: function() { this.publish("error", { fireOnce: true, async: true }); this.publish("load", { fireOnce: true, async: true }); this.image = this.get("contentBox"); }, getEditorLabel: function() { return this.get("url"); }, /** * Lifecycle method * @function * @private */ renderUI: function() { this.image = this.get("boundingBox").one("img"); // !! IE 8 : this.image._node === // this.get(CONTENTBOX)._node => false ... this.get("url"); }, /** * Lifecycle method * @function * @private */ bindUI: function() { this.image.on("load", function(e) { if (!this.CSSSize) { // adapt only without plugin this.get("boundingBox").setStyles({ width: this.image.width, height: this.image.height }); } this.fire("load"); this.getEvent("load").fired = true; }, this); this.image.on("error", function(e) { if (this.image.getAttribute("src")) { this.image.setAttribute("src", ""); this.image.setAttribute("alt", "Image error"); this.fire("error"); this.getEvent("error").fired = true; } }, this); } }, { /** @lends Y.Wegas.Image */ EDITORNAME: "Image", FILEENTRY: function() { return Y.Wegas.Facade.File.get("source") + "read"; }, ATTRS: { url: { value: "", type: "string", setter: function(val) { this.getEvent("load").fired = false; this.getEvent("error").fired = false; this.image.setAttribute("src", (val.indexOf("/") === 0) ? Image.FILEENTRY() + val : //Wegas Filesystem val); return val; }, view: { label: "URL", type: "wegasimageurl" } }, complete: { readOnly: true, "transient": true, getter: function() { return this.image && this.image.getDOMNode() ? this.image.getDOMNode().complete : true; } } } }); Y.Wegas.Image = Image; });
var context = require.context('./test', true, /\.js$/); context.keys().forEach(function(moduleName) { context(moduleName); });
$(document).ready(function() { $("footer div.social-networks").socialSharePrivacy({ services : { facebook : { 'status' : 'on', 'txt_info' : '2 clicks for increased privacy: Only after clicking here the button will become active and allow connecting to Facebook. Data will already be transferred upon activation &ndash; see <em>i</em>', 'txt_fb_off' : 'not connected to Facebook', 'txt_fb_on' : 'connected to Facebook', 'display_name' : 'Facebook', 'language' : 'en_US', 'action' : 'like', 'dummy_caption' : 'Like' }, twitter : { 'status' : 'on', 'txt_info' : '2 clicks for increased privacy: Only after clicking here the button will become active and allow connecting to Twitter. Data will already be transferred upon activation &ndash; see <em>i</em>', 'txt_twitter_off' : 'not connected to twitter', 'txt_twitter_on' : 'connected to twitter', 'display_name' : 'Twitter', 'language' : 'en', 'dummy_caption' : 'Tweet' }, gplus : { 'status' : 'on', 'txt_info' : '2 clicks for increased privacy: Only after clicking here the button will become active and allow connecting to Google+. Data will already be transferred upon activation &ndash; see <em>i</em>', 'txt_glus_off' : 'not connected to google+', 'txt_gplus_on' : 'connected to google+', 'display_name' : 'Google+', 'language' : 'en' } }, 'info_link' : '', 'txt_help' : 'If you activate these buttons, data will be transferred to Facebook, Twitter or Google in the USA. This data might also be stored there.', 'settings_perma' : 'Activate permanently and confirm transfer of data:' }); });
/** * Created by USER: tarso. * On DATE: 26/08/16. * By NAME: rmqt01receive.js. */ /** * Source: https://www.rabbitmq.com/tutorials/tutorial-one-javascript.html */ var amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost:8080', function(err, conn) { conn.createChannel(function(err, ch) { var q = 'hello'; ch.assertQueue(q, {durable: false}); }); console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q); ch.consume(q, function(msg) { console.log(" [x] Received %s", msg.content.toString()); }, {noAck: true}); });
export loadData from './loadData'; export loadInfo from './loadInfo'; export * as widget from './widget'; export * as survey from './survey';
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('object-list-view-header-cell', 'Integration | Component | object list view header cell', { integration: true }); test('it renders', function(assert) { this.set('myColumn', { header: 'myHeader' }); this.render(hbs`{{object-list-view-header-cell column=myColumn}}`); assert.equal(this.$().text().trim(), 'myHeader'); });
import React from "react" import Layout from "../components/layout" import SEO from "../components/seo" const Redirect = () => ( <Layout> <SEO title="Redirect" /> <p>This should be at /pt/redirect-me/</p> </Layout> ) export default Redirect
// ==UserScript== // @name cnes // @namespace cnes // @version 0.1.0.5a // @description Cyber Nations Enhanced Services // @author Ryahn aka Ryan Carr // @match http://www.cybernations.net/* // @require https://code.jquery.com/jquery-3.2.1.min.js // @downloadURL https://raw.githubusercontent.com/Ryahn/cnes/master/cnes.user.js // @updateURL https://raw.githubusercontent.com/Ryahn/cnes/master/cnes.meta.js // @connect raw.githubusercontent.com // @connect cybernations.net // @grant GM_addStyle // @grant GM_setValue // @grant GM_getValue // @grant GM_deleteValue // @grant GM_listValues // @grant GM_addValueChangeListener // @grant GM_removeValueChangeListener // @grant GM_getResourceText // @grant GM_getResourceURL // @grant GM_xmlhttpRequest // @grant GM_info // ==/UserScript== //Test //Gets population var pop = $("#table18 > tbody > tr:nth-child(52) > td:nth-child(2)").text().split(/\s+/); //Returns number var popnum = pop[1].replace(/,/g,''); //returns percentage var percentage = (20 / 100) * popnum; //returns whole number var whole = Math.round(percentage); //Gets military personnel var mil = $("#table18 > tbody > tr:nth-child(53) > td:nth-child(2) > i").text().split(/\s+/); //returns number var milnum = mil[0]; //returns how many to buy var total = whole - milnum; //if less than or equal to 5, do not display. Anything over, display if(total <= 5) return; //Display message after military personnel numbers $('#table18 > tbody > tr:nth-child(53) > td:nth-child(2) > i').after(' <span style="color:blue;font-size:12px">Purchase <span style="font-weight:bold;">' + total + '</span> to be at 20% of citizen population</span>'); var tech = $("#table17 > tbody > tr:nth-child(2) > td:nth-child(2) > b > i"); switch (tech) { case tech <= 4.5: console.log('4.5'); break; case 'prototype': console.log('4.5'); break; case 'mootools': console.log('4.5'); break; case 'dojo': console.log('4.5'); break; default: console.log('4.5'); }
$(function() { $.widget('bluetea.bootstrapModal', { // Default options options: { content: null, translations: { textBlockUiTitle: 'Submitting', textBlockUiMessage: 'Please wait...' } }, _element: null, _create: function() { // Save element in private variable _element this._element = this.element; // Initialize event listener for this modal this._initEventListeners(); }, _initEventListeners: function() { this._on($(this._element).find('form'), { submit: function(event) { // this.element = div / modal // event.currentTarget = form event.preventDefault(); this._submitForm(event.currentTarget); } }); }, _submitForm: function(form) { var type = $(form).attr('method'); var url = $(form).attr('action'); var data = $(form).serialize(); $(document).ajaxProtocol("call", { url: url, data: data, type: type, beforeSendCallback: $.proxy(function() { $(document).blockUi( 'blockUI', this.options.translations.textBlockUiTitle, this.options.translations.textBlockUiMessage ); }, this) }); $(document).bind('ajax_done', $.proxy(function(event, data) { this.destroy(); }, this)); }, _destroy: function() { $(this._element) .modal('hide'); } }); }(jQuery));
/** * * LayoutContainer * */ import React, { Component } from "react"; import PropTypes from "prop-types"; import Grid from 'material-ui/Grid'; class LayoutContainer extends Component { constructor(props) { super(props); } render() { return ( <Grid container {...this.props}> {this.props.children} </Grid> ); } } LayoutContainer.propTypes = { children: PropTypes.node, }; LayoutContainer.defaultProps = { children: null, }; export default LayoutContainer;
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['demo-projects'], projects: [ Ember.Object.create({ title: "Code Corps", description: "Building a better future together. Contribute to public software for social good.", iconLargeUrl: "https://d3pgew4wbk2vb1.cloudfront.net/images/cc-demo.png", organizationName: "Code Corps", categories: [ { name: "Society", selected: false, slug: "society" }, { name: "Technology", selected: true, slug: "technology" }, ], skills: [ { title: "Ember.js", matched: true, }, { title: "HTML", matched: true, }, { title: "Rails", matched: true, }, { title: "Ruby", matched: true, }, { title: "Copywriting", matched: false, }, { title: "CSS", matched: false, }, ], }), Ember.Object.create({ title: "Movement", description: "We help people elect their representatives and then hold them accountable.", iconLargeUrl: "https://d3pgew4wbk2vb1.cloudfront.net/images/movement-demo.png", organizationName: "Movement", categories: [ { name: "Government", selected: true, slug: "government" }, { name: "Politics", selected: false, slug: "politics" }, { name: "Society", selected: false, slug: "society" }, ], skills: [ { title: "Rails", matched: true, }, { title: "Ruby", matched: true, }, { title: "Amazon S3", matched: false, }, { title: "iOS", matched: false, }, { title: "PostgreSQL", matched: false, }, { title: "Swift", matched: false, }, ], }), ], });
/* eslint-disable func-names, space-before-function-paren, wrap-iife, no-var, no-new, max-len */ /* global GitLab */ /* global DropzoneInput */ /* global autosize */ window.gl = window.gl || {}; function GLForm(form) { this.form = form; this.textarea = this.form.find('textarea.js-gfm-input'); // Before we start, we should clean up any previous data for this form this.destroy(); // Setup the form this.setupForm(); this.form.data('gl-form', this); } GLForm.prototype.destroy = function() { // Clean form listeners this.clearEventListeners(); return this.form.data('gl-form', null); }; GLForm.prototype.setupForm = function() { var isNewForm; isNewForm = this.form.is(':not(.gfm-form)'); this.form.removeClass('js-new-note-form'); if (isNewForm) { this.form.find('.div-dropzone').remove(); this.form.addClass('gfm-form'); // remove notify commit author checkbox for non-commit notes gl.utils.disableButtonIfEmptyField(this.form.find('.js-note-text'), this.form.find('.js-comment-button, .js-note-new-discussion')); gl.GfmAutoComplete.setup(this.form.find('.js-gfm-input')); new DropzoneInput(this.form); autosize(this.textarea); } // form and textarea event listeners this.addEventListeners(); gl.text.init(this.form); // hide discard button this.form.find('.js-note-discard').hide(); this.form.show(); if (this.isAutosizeable) this.setupAutosize(); }; GLForm.prototype.setupAutosize = function () { this.textarea.off('autosize:resized') .on('autosize:resized', this.setHeightData.bind(this)); this.textarea.off('mouseup.autosize') .on('mouseup.autosize', this.destroyAutosize.bind(this)); setTimeout(() => { autosize(this.textarea); this.textarea.css('resize', 'vertical'); }, 0); }; GLForm.prototype.setHeightData = function () { this.textarea.data('height', this.textarea.outerHeight()); }; GLForm.prototype.destroyAutosize = function () { const outerHeight = this.textarea.outerHeight(); if (this.textarea.data('height') === outerHeight) return; autosize.destroy(this.textarea); this.textarea.data('height', outerHeight); this.textarea.outerHeight(outerHeight); this.textarea.css('max-height', window.outerHeight); }; GLForm.prototype.clearEventListeners = function() { this.textarea.off('focus'); this.textarea.off('blur'); return gl.text.removeListeners(this.form); }; GLForm.prototype.addEventListeners = function() { this.textarea.on('focus', function() { return $(this).closest('.md-area').addClass('is-focused'); }); return this.textarea.on('blur', function() { return $(this).closest('.md-area').removeClass('is-focused'); }); }; window.gl.GLForm = GLForm;
/*! * Native JavaScript for Bootstrap v4.0.7 (https://thednp.github.io/bootstrap.native/) * Copyright 2015-2021 © dnp_theme * Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE) */ var transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend'; var supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style; var transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration'; var transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty'; function getElementTransitionDuration(element) { var computedStyle = getComputedStyle(element); var propertyValue = computedStyle[transitionProperty]; var durationValue = computedStyle[transitionDuration]; var durationScale = durationValue.includes('ms') ? 1 : 1000; var duration = supportTransition && propertyValue && propertyValue !== 'none' ? parseFloat(durationValue) * durationScale : 0; return !Number.isNaN(duration) ? duration : 0; } function emulateTransitionEnd(element, handler) { var called = 0; var endEvent = new Event(transitionEndEvent); var duration = getElementTransitionDuration(element); if (duration) { element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) { if (e.target === element) { handler.apply(element, [e]); element.removeEventListener(transitionEndEvent, transitionEndWrapper); called = 1; } }); setTimeout(function () { if (!called) { element.dispatchEvent(endEvent); } }, duration + 17); } else { handler.apply(element, [endEvent]); } } function queryElement(selector, parent) { var lookUp = parent && parent instanceof Element ? parent : document; return selector instanceof Element ? selector : lookUp.querySelector(selector); } function bootstrapCustomEvent(eventType, componentName, eventProperties) { var OriginalCustomEvent = new CustomEvent((eventType + ".bs." + componentName), { cancelable: true }); if (typeof eventProperties !== 'undefined') { Object.keys(eventProperties).forEach(function (key) { Object.defineProperty(OriginalCustomEvent, key, { value: eventProperties[key], }); }); } return OriginalCustomEvent; } function dispatchCustomEvent(customEvent) { if (this) { this.dispatchEvent(customEvent); } } /* Native JavaScript for Bootstrap 4 | Alert -------------------------------------------- */ // ALERT DEFINITION // ================ function Alert(elem) { var element; // bind var self = this; // the target alert var alert; // custom events var closeCustomEvent = bootstrapCustomEvent('close', 'alert'); var closedCustomEvent = bootstrapCustomEvent('closed', 'alert'); // private methods function triggerHandler() { if (alert.classList.contains('fade')) { emulateTransitionEnd(alert, transitionEndHandler); } else { transitionEndHandler(); } } function toggleEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; element[action]('click', clickHandler, false); } // event handlers function clickHandler(e) { alert = e && e.target.closest('.alert'); element = queryElement('[data-dismiss="alert"]', alert); if (element && alert && (element === e.target || element.contains(e.target))) { self.close(); } } function transitionEndHandler() { toggleEvents(); alert.parentNode.removeChild(alert); dispatchCustomEvent.call(alert, closedCustomEvent); } // PUBLIC METHODS self.close = function () { if (alert && element && alert.classList.contains('show')) { dispatchCustomEvent.call(alert, closeCustomEvent); if (closeCustomEvent.defaultPrevented) { return; } self.dispose(); alert.classList.remove('show'); triggerHandler(); } }; self.dispose = function () { toggleEvents(); delete element.Alert; }; // INIT // initialization element element = queryElement(elem); // find the target alert alert = element.closest('.alert'); // reset on re-init if (element.Alert) { element.Alert.dispose(); } // prevent adding event handlers twice if (!element.Alert) { toggleEvents(1); } // store init object within target element self.element = element; element.Alert = self; } /* Native JavaScript for Bootstrap 4 | Button ---------------------------------------------*/ // BUTTON DEFINITION // ================= function Button(elem) { var element; // bind and labels var self = this; var labels; // changeEvent var changeCustomEvent = bootstrapCustomEvent('change', 'button'); // private methods function toggle(e) { var eTarget = e.target; var parentLabel = eTarget.closest('LABEL'); // the .btn label var label = null; if (eTarget.tagName === 'LABEL') { label = eTarget; } else if (parentLabel) { label = parentLabel; } // current input var input = label && label.getElementsByTagName('INPUT')[0]; // invalidate if no input if (!input) { return; } dispatchCustomEvent.call(input, changeCustomEvent); // trigger the change for the input dispatchCustomEvent.call(element, changeCustomEvent); // trigger the change for the btn-group // manage the dom manipulation if (input.type === 'checkbox') { // checkboxes if (changeCustomEvent.defaultPrevented) { return; } // discontinue when defaultPrevented is true if (!input.checked) { label.classList.add('active'); input.getAttribute('checked'); input.setAttribute('checked', 'checked'); input.checked = true; } else { label.classList.remove('active'); input.getAttribute('checked'); input.removeAttribute('checked'); input.checked = false; } if (!element.toggled) { // prevent triggering the event twice element.toggled = true; } } if (input.type === 'radio' && !element.toggled) { // radio buttons if (changeCustomEvent.defaultPrevented) { return; } // don't trigger if already active // (the OR condition is a hack to check if the buttons were selected // with key press and NOT mouse click) if (!input.checked || (e.screenX === 0 && e.screenY === 0)) { label.classList.add('active'); label.classList.add('focus'); input.setAttribute('checked', 'checked'); input.checked = true; element.toggled = true; Array.from(labels).forEach(function (otherLabel) { var otherInput = otherLabel.getElementsByTagName('INPUT')[0]; if (otherLabel !== label && otherLabel.classList.contains('active')) { dispatchCustomEvent.call(otherInput, changeCustomEvent); // trigger the change otherLabel.classList.remove('active'); otherInput.removeAttribute('checked'); otherInput.checked = false; } }); } } setTimeout(function () { element.toggled = false; }, 50); } // handlers function keyHandler(e) { var key = e.which || e.keyCode; if (key === 32 && e.target === document.activeElement) { toggle(e); } } function preventScroll(e) { var key = e.which || e.keyCode; if (key === 32) { e.preventDefault(); } } function focusToggle(e) { if (e.target.tagName === 'INPUT') { var action = e.type === 'focusin' ? 'add' : 'remove'; e.target.closest('.btn').classList[action]('focus'); } } function toggleEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; element[action]('click', toggle, false); element[action]('keyup', keyHandler, false); element[action]('keydown', preventScroll, false); element[action]('focusin', focusToggle, false); element[action]('focusout', focusToggle, false); } // public method self.dispose = function () { toggleEvents(); delete element.Button; }; // init // initialization element element = queryElement(elem); // reset on re-init if (element.Button) { element.Button.dispose(); } labels = element.getElementsByClassName('btn'); // invalidate if (!labels.length) { return; } // prevent adding event handlers twice if (!element.Button) { toggleEvents(1); } // set initial toggled state // toggled makes sure to prevent triggering twice the change.bs.button events element.toggled = false; // associate target with init object element.Button = self; // activate items on load Array.from(labels).forEach(function (btn) { var hasChecked = queryElement('input:checked', btn); if (!btn.classList.contains('active') && hasChecked) { btn.classList.add('active'); } if (btn.classList.contains('active') && !hasChecked) { btn.classList.remove('active'); } }); } var mouseHoverEvents = ('onmouseleave' in document) ? ['mouseenter', 'mouseleave'] : ['mouseover', 'mouseout']; var addEventListener = 'addEventListener'; var removeEventListener = 'removeEventListener'; var supportPassive = (function () { var result = false; try { var opts = Object.defineProperty({}, 'passive', { get: function get() { result = true; return result; }, }); document[addEventListener]('DOMContentLoaded', function wrap() { document[removeEventListener]('DOMContentLoaded', wrap, opts); }, opts); } catch (e) { throw Error('Passive events are not supported'); } return result; })(); // general event options var passiveHandler = supportPassive ? { passive: true } : false; function isElementInScrollRange(element) { var bcr = element.getBoundingClientRect(); var viewportHeight = window.innerHeight || document.documentElement.clientHeight; return bcr.top <= viewportHeight && bcr.bottom >= 0; // bottom && top } function reflow(element) { return element.offsetHeight; } /* Native JavaScript for Bootstrap 4 | Carousel ----------------------------------------------- */ // CAROUSEL DEFINITION // =================== function Carousel(elem, opsInput) { var assign, assign$1, assign$2; var element; // set options var options = opsInput || {}; // bind var self = this; // internal variables var vars; var ops; // custom events var slideCustomEvent; var slidCustomEvent; // carousel elements var slides; var leftArrow; var rightArrow; var indicator; var indicators; // handlers function pauseHandler() { if (ops.interval !== false && !element.classList.contains('paused')) { element.classList.add('paused'); if (!vars.isSliding) { clearInterval(vars.timer); vars.timer = null; } } } function resumeHandler() { if (ops.interval !== false && element.classList.contains('paused')) { element.classList.remove('paused'); if (!vars.isSliding) { clearInterval(vars.timer); vars.timer = null; self.cycle(); } } } function indicatorHandler(e) { e.preventDefault(); if (vars.isSliding) { return; } var eventTarget = e.target; // event target | the current active item if (eventTarget && !eventTarget.classList.contains('active') && eventTarget.getAttribute('data-slide-to')) { vars.index = +(eventTarget.getAttribute('data-slide-to')); } else { return; } self.slideTo(vars.index); // Do the slide } function controlsHandler(e) { e.preventDefault(); if (vars.isSliding) { return; } var eventTarget = e.currentTarget || e.srcElement; if (eventTarget === rightArrow) { vars.index += 1; } else if (eventTarget === leftArrow) { vars.index -= 1; } self.slideTo(vars.index); // Do the slide } function keyHandler(ref) { var which = ref.which; if (vars.isSliding) { return; } switch (which) { case 39: vars.index += 1; break; case 37: vars.index -= 1; break; default: return; } self.slideTo(vars.index); // Do the slide } function toggleEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; if (ops.pause && ops.interval) { element[action](mouseHoverEvents[0], pauseHandler, false); element[action](mouseHoverEvents[1], resumeHandler, false); element[action]('touchstart', pauseHandler, passiveHandler); element[action]('touchend', resumeHandler, passiveHandler); } if (ops.touch && slides.length > 1) { element[action]('touchstart', touchDownHandler, passiveHandler); } if (rightArrow) { rightArrow[action]('click', controlsHandler, false); } if (leftArrow) { leftArrow[action]('click', controlsHandler, false); } if (indicator) { indicator[action]('click', indicatorHandler, false); } if (ops.keyboard) { window[action]('keydown', keyHandler, false); } } // touch events function toggleTouchEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; element[action]('touchmove', touchMoveHandler, passiveHandler); element[action]('touchend', touchEndHandler, passiveHandler); } function touchDownHandler(e) { if (vars.isTouch) { return; } vars.touchPosition.startX = e.changedTouches[0].pageX; if (element.contains(e.target)) { vars.isTouch = true; toggleTouchEvents(1); } } function touchMoveHandler(e) { if (!vars.isTouch) { e.preventDefault(); return; } vars.touchPosition.currentX = e.changedTouches[0].pageX; // cancel touch if more than one changedTouches detected if (e.type === 'touchmove' && e.changedTouches.length > 1) { e.preventDefault(); } } function touchEndHandler(e) { if (!vars.isTouch || vars.isSliding) { return; } vars.touchPosition.endX = vars.touchPosition.currentX || e.changedTouches[0].pageX; if (vars.isTouch) { if ((!element.contains(e.target) || !element.contains(e.relatedTarget)) && Math.abs(vars.touchPosition.startX - vars.touchPosition.endX) < 75) { return; } if (vars.touchPosition.currentX < vars.touchPosition.startX) { vars.index += 1; } else if (vars.touchPosition.currentX > vars.touchPosition.startX) { vars.index -= 1; } vars.isTouch = false; self.slideTo(vars.index); toggleTouchEvents(); // remove } } // private methods function setActivePage(pageIndex) { // indicators Array.from(indicators).forEach(function (x) { return x.classList.remove('active'); }); if (indicators[pageIndex]) { indicators[pageIndex].classList.add('active'); } } function transitionEndHandler(e) { if (vars.touchPosition) { var next = vars.index; var timeout = e && e.target !== slides[next] ? e.elapsedTime * 1000 + 100 : 20; var activeItem = self.getActiveIndex(); var orientation = vars.direction === 'left' ? 'next' : 'prev'; if (vars.isSliding) { setTimeout(function () { if (vars.touchPosition) { vars.isSliding = false; slides[next].classList.add('active'); slides[activeItem].classList.remove('active'); slides[next].classList.remove(("carousel-item-" + orientation)); slides[next].classList.remove(("carousel-item-" + (vars.direction))); slides[activeItem].classList.remove(("carousel-item-" + (vars.direction))); dispatchCustomEvent.call(element, slidCustomEvent); // check for element, might have been disposed if (!document.hidden && ops.interval && !element.classList.contains('paused')) { self.cycle(); } } }, timeout); } } } // public methods self.cycle = function () { if (vars.timer) { clearInterval(vars.timer); vars.timer = null; } vars.timer = setInterval(function () { var idx = vars.index || self.getActiveIndex(); if (isElementInScrollRange(element)) { idx += 1; self.slideTo(idx); } }, ops.interval); }; self.slideTo = function (idx) { if (vars.isSliding) { return; } // when controled via methods, make sure to check again // the current active, orientation, event eventProperties var activeItem = self.getActiveIndex(); var next = idx; // first return if we're on the same item #227 if (activeItem === next) { return; // or determine slide direction } if ((activeItem < next) || (activeItem === 0 && next === slides.length - 1)) { vars.direction = 'left'; // next } else if ((activeItem > next) || (activeItem === slides.length - 1 && next === 0)) { vars.direction = 'right'; // prev } // find the right next index if (next < 0) { next = slides.length - 1; } else if (next >= slides.length) { next = 0; } var orientation = vars.direction === 'left' ? 'next' : 'prev'; // determine type var eventProperties = { relatedTarget: slides[next], direction: vars.direction, from: activeItem, to: next, }; slideCustomEvent = bootstrapCustomEvent('slide', 'carousel', eventProperties); slidCustomEvent = bootstrapCustomEvent('slid', 'carousel', eventProperties); dispatchCustomEvent.call(element, slideCustomEvent); // here we go with the slide if (slideCustomEvent.defaultPrevented) { return; } // discontinue when prevented // update index vars.index = next; vars.isSliding = true; clearInterval(vars.timer); vars.timer = null; setActivePage(next); if (getElementTransitionDuration(slides[next]) && element.classList.contains('slide')) { slides[next].classList.add(("carousel-item-" + orientation)); reflow(slides[next]); slides[next].classList.add(("carousel-item-" + (vars.direction))); slides[activeItem].classList.add(("carousel-item-" + (vars.direction))); emulateTransitionEnd(slides[next], transitionEndHandler); } else { slides[next].classList.add('active'); reflow(slides[next]); slides[activeItem].classList.remove('active'); setTimeout(function () { vars.isSliding = false; // check for element, might have been disposed if (ops.interval && element && !element.classList.contains('paused')) { self.cycle(); } dispatchCustomEvent.call(element, slidCustomEvent); }, 100); } }; self.getActiveIndex = function () { return Array.from(slides).indexOf(element.getElementsByClassName('carousel-item active')[0]) || 0; }; self.dispose = function () { var itemClasses = ['left', 'right', 'prev', 'next']; Array.from(slides).forEach(function (slide, idx) { if (slide.classList.contains('active')) { setActivePage(idx); } itemClasses.forEach(function (cls) { return slide.classList.remove(("carousel-item-" + cls)); }); }); clearInterval(vars.timer); toggleEvents(); vars = {}; ops = {}; delete element.Carousel; }; // init // initialization element element = queryElement(elem); // reset on re-init if (element.Carousel) { element.Carousel.dispose(); } // carousel elements slides = element.getElementsByClassName('carousel-item'); (assign = element.getElementsByClassName('carousel-control-prev'), leftArrow = assign[0]); (assign$1 = element.getElementsByClassName('carousel-control-next'), rightArrow = assign$1[0]); (assign$2 = element.getElementsByClassName('carousel-indicators'), indicator = assign$2[0]); indicators = (indicator && indicator.getElementsByTagName('LI')) || []; // invalidate when not enough items if (slides.length < 2) { return; } // check options // DATA API var intervalAttribute = element.getAttribute('data-interval'); var intervalData = intervalAttribute === 'false' ? 0 : +(intervalAttribute); var touchData = element.getAttribute('data-touch') === 'false' ? 0 : 1; var pauseData = element.getAttribute('data-pause') === 'hover' || false; var keyboardData = element.getAttribute('data-keyboard') === 'true' || false; // JS options var intervalOption = options.interval; var touchOption = options.touch; // set instance options ops = {}; ops.keyboard = options.keyboard === true || keyboardData; ops.pause = (options.pause === 'hover' || pauseData) ? 'hover' : false; // false / hover ops.touch = touchOption || touchData; ops.interval = 5000; // bootstrap carousel default interval if (typeof intervalOption === 'number') { ops.interval = intervalOption; } else if (intervalOption === false || intervalData === 0 || intervalData === false) { ops.interval = 0; } else if (!Number.isNaN(intervalData)) { ops.interval = intervalData; } // set first slide active if none if (self.getActiveIndex() < 0) { if (slides.length) { slides[0].classList.add('active'); } if (indicators.length) { setActivePage(0); } } // set initial state vars = {}; vars.direction = 'left'; vars.index = 0; vars.timer = null; vars.isSliding = false; vars.isTouch = false; vars.touchPosition = { startX: 0, currentX: 0, endX: 0, }; // attach event handlers toggleEvents(1); // start to cycle if interval is set if (ops.interval) { self.cycle(); } // associate init object to target element.Carousel = self; } /* Native JavaScript for Bootstrap 4 | Collapse ----------------------------------------------- */ // COLLAPSE DEFINITION // =================== function Collapse(elem, opsInput) { var element; // set options var options = opsInput || {}; // bind var self = this; // target practice var accordion = null; var collapse = null; var activeCollapse; var activeElement; // custom events var showCustomEvent; var shownCustomEvent; var hideCustomEvent; var hiddenCustomEvent; // private methods function openAction(collapseElement, toggle) { dispatchCustomEvent.call(collapseElement, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } collapseElement.isAnimating = true; collapseElement.classList.add('collapsing'); collapseElement.classList.remove('collapse'); collapseElement.style.height = (collapseElement.scrollHeight) + "px"; emulateTransitionEnd(collapseElement, function () { collapseElement.isAnimating = false; collapseElement.setAttribute('aria-expanded', 'true'); toggle.setAttribute('aria-expanded', 'true'); collapseElement.classList.remove('collapsing'); collapseElement.classList.add('collapse'); collapseElement.classList.add('show'); collapseElement.style.height = ''; dispatchCustomEvent.call(collapseElement, shownCustomEvent); }); } function closeAction(collapseElement, toggle) { dispatchCustomEvent.call(collapseElement, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } collapseElement.isAnimating = true; collapseElement.style.height = (collapseElement.scrollHeight) + "px"; // set height first collapseElement.classList.remove('collapse'); collapseElement.classList.remove('show'); collapseElement.classList.add('collapsing'); reflow(collapseElement); // force reflow to enable transition collapseElement.style.height = '0px'; emulateTransitionEnd(collapseElement, function () { collapseElement.isAnimating = false; collapseElement.setAttribute('aria-expanded', 'false'); toggle.setAttribute('aria-expanded', 'false'); collapseElement.classList.remove('collapsing'); collapseElement.classList.add('collapse'); collapseElement.style.height = ''; dispatchCustomEvent.call(collapseElement, hiddenCustomEvent); }); } // public methods self.toggle = function (e) { if ((e && e.target.tagName === 'A') || element.tagName === 'A') { e.preventDefault(); } if (element.contains(e.target) || e.target === element) { if (!collapse.classList.contains('show')) { self.show(); } else { self.hide(); } } }; self.hide = function () { if (collapse.isAnimating) { return; } closeAction(collapse, element); element.classList.add('collapsed'); }; self.show = function () { var assign; if (accordion) { (assign = accordion.getElementsByClassName('collapse show'), activeCollapse = assign[0]); activeElement = activeCollapse && (queryElement(("[data-target=\"#" + (activeCollapse.id) + "\"]"), accordion) || queryElement(("[href=\"#" + (activeCollapse.id) + "\"]"), accordion)); } if (!collapse.isAnimating) { if (activeElement && activeCollapse !== collapse) { closeAction(activeCollapse, activeElement); activeElement.classList.add('collapsed'); } openAction(collapse, element); element.classList.remove('collapsed'); } }; self.dispose = function () { element.removeEventListener('click', self.toggle, false); delete element.Collapse; }; // init // initialization element element = queryElement(elem); // reset on re-init if (element.Collapse) { element.Collapse.dispose(); } // DATA API var accordionData = element.getAttribute('data-parent'); // custom events showCustomEvent = bootstrapCustomEvent('show', 'collapse'); shownCustomEvent = bootstrapCustomEvent('shown', 'collapse'); hideCustomEvent = bootstrapCustomEvent('hide', 'collapse'); hiddenCustomEvent = bootstrapCustomEvent('hidden', 'collapse'); // determine targets collapse = queryElement(options.target || element.getAttribute('data-target') || element.getAttribute('href')); if (collapse !== null) { collapse.isAnimating = false; } var accordionSelector = options.parent || accordionData; if (accordionSelector) { accordion = element.closest(accordionSelector); } else { accordion = null; } // prevent adding event handlers twice if (!element.Collapse) { element.addEventListener('click', self.toggle, false); } // associate target to init object element.Collapse = self; } function setFocus(element) { element.focus(); } /* Native JavaScript for Bootstrap 4 | Dropdown ----------------------------------------------- */ // DROPDOWN DEFINITION // =================== function Dropdown(elem, option) { var element; // bind var self = this; // custom events var showCustomEvent; var shownCustomEvent; var hideCustomEvent; var hiddenCustomEvent; // targets var relatedTarget = null; var parent; var menu; var menuItems = []; // option var persist; // preventDefault on empty anchor links function preventEmptyAnchor(anchor) { if ((anchor.hasAttribute('href') && anchor.href.slice(-1) === '#') || (anchor.parentNode && anchor.hasAttribute('href') && anchor.parentNode.href.slice(-1) === '#')) { this.preventDefault(); } } // toggle dismissible events function toggleDismiss() { var action = element.open ? 'addEventListener' : 'removeEventListener'; document[action]('click', dismissHandler, false); document[action]('keydown', preventScroll, false); document[action]('keyup', keyHandler, false); document[action]('focus', dismissHandler, false); } // handlers function dismissHandler(e) { var eventTarget = e.target; if (!eventTarget.getAttribute) { return; } // some weird FF bug #409 var hasData = ((eventTarget && (eventTarget.getAttribute('data-toggle'))) || (eventTarget.parentNode && eventTarget.parentNode.getAttribute && eventTarget.parentNode.getAttribute('data-toggle'))); if (e.type === 'focus' && (eventTarget === element || eventTarget === menu || menu.contains(eventTarget))) { return; } if ((eventTarget === menu || menu.contains(eventTarget)) && (persist || hasData)) { return; } relatedTarget = eventTarget === element || element.contains(eventTarget) ? element : null; self.hide(); preventEmptyAnchor.call(e, eventTarget); } function clickHandler(e) { relatedTarget = element; self.show(); preventEmptyAnchor.call(e, e.target); } function preventScroll(e) { var key = e.which || e.keyCode; if (key === 38 || key === 40) { e.preventDefault(); } } function keyHandler(e) { var key = e.which || e.keyCode; var activeItem = document.activeElement; var isSameElement = activeItem === element; var isInsideMenu = menu.contains(activeItem); var isMenuItem = activeItem.parentNode === menu || activeItem.parentNode.parentNode === menu; var idx = menuItems.indexOf(activeItem); if (isMenuItem) { // navigate up | down if (isSameElement) { idx = 0; } else if (key === 38) { idx = idx > 1 ? idx - 1 : 0; } else if (key === 40) { idx = idx < menuItems.length - 1 ? idx + 1 : idx; } if (menuItems[idx]) { setFocus(menuItems[idx]); } } if (((menuItems.length && isMenuItem) // menu has items || (!menuItems.length && (isInsideMenu || isSameElement)) // menu might be a form || !isInsideMenu) // or the focused element is not in the menu at all && element.open && key === 27 // menu must be open ) { self.toggle(); relatedTarget = null; } } // public methods self.show = function () { showCustomEvent = bootstrapCustomEvent('show', 'dropdown', { relatedTarget: relatedTarget }); dispatchCustomEvent.call(parent, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } menu.classList.add('show'); parent.classList.add('show'); element.setAttribute('aria-expanded', true); element.open = true; element.removeEventListener('click', clickHandler, false); setTimeout(function () { setFocus(menu.getElementsByTagName('INPUT')[0] || element); // focus the first input item | element toggleDismiss(); shownCustomEvent = bootstrapCustomEvent('shown', 'dropdown', { relatedTarget: relatedTarget }); dispatchCustomEvent.call(parent, shownCustomEvent); }, 1); }; self.hide = function () { hideCustomEvent = bootstrapCustomEvent('hide', 'dropdown', { relatedTarget: relatedTarget }); dispatchCustomEvent.call(parent, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } menu.classList.remove('show'); parent.classList.remove('show'); element.setAttribute('aria-expanded', false); element.open = false; toggleDismiss(); setFocus(element); setTimeout(function () { // only re-attach handler if the init is not disposed if (element.Dropdown) { element.addEventListener('click', clickHandler, false); } }, 1); hiddenCustomEvent = bootstrapCustomEvent('hidden', 'dropdown', { relatedTarget: relatedTarget }); dispatchCustomEvent.call(parent, hiddenCustomEvent); }; self.toggle = function () { if (parent.classList.contains('show') && element.open) { self.hide(); } else { self.show(); } }; self.dispose = function () { if (parent.classList.contains('show') && element.open) { self.hide(); } element.removeEventListener('click', clickHandler, false); delete element.Dropdown; }; // init // initialization element element = queryElement(elem); // reset on re-init if (element.Dropdown) { element.Dropdown.dispose(); } // set targets parent = element.parentNode; menu = queryElement('.dropdown-menu', parent); Array.from(menu.children).forEach(function (child) { if (child.children.length && child.children[0].tagName === 'A') { menuItems.push(child.children[0]); } if (child.tagName === 'A') { menuItems.push(child); } }); // prevent adding event handlers twice if (!element.Dropdown) { if (!('tabindex' in menu)) { menu.setAttribute('tabindex', '0'); } // Fix onblur on Chrome | Safari element.addEventListener('click', clickHandler, false); } // set option persist = option === true || element.getAttribute('data-persist') === 'true' || false; // set initial state to closed element.open = false; // associate element with init object element.Dropdown = self; } /* Native JavaScript for Bootstrap 4 | Modal -------------------------------------------- */ // MODAL DEFINITION // ================ function Modal(elem, opsInput) { // element can be the modal/triggering button var element; // set options var options = opsInput || {}; // bind, modal var self = this; var modal; // custom events var showCustomEvent; var shownCustomEvent; var hideCustomEvent; var hiddenCustomEvent; // event targets and other var relatedTarget = null; var scrollBarWidth; var overlay; var overlayDelay; // also find fixed-top / fixed-bottom items var fixedItems; var ops = {}; // private methods function setScrollbar() { var bodyClassList = document.body.classList; var openModal = bodyClassList.contains('modal-open'); var bodyPad = parseInt(getComputedStyle(document.body).paddingRight, 10); var docClientHeight = document.documentElement.clientHeight; var docScrollHeight = document.documentElement.scrollHeight; var bodyClientHeight = document.body.clientHeight; var bodyScrollHeight = document.body.scrollHeight; var bodyOverflow = docClientHeight !== docScrollHeight || bodyClientHeight !== bodyScrollHeight; var modalOverflow = modal.clientHeight !== modal.scrollHeight; scrollBarWidth = measureScrollbar(); modal.style.paddingRight = !modalOverflow && scrollBarWidth ? (scrollBarWidth + "px") : ''; document.body.style.paddingRight = modalOverflow || bodyOverflow ? ((bodyPad + (openModal ? 0 : scrollBarWidth)) + "px") : ''; if (fixedItems.length) { fixedItems.forEach(function (fixed) { var itemPad = getComputedStyle(fixed).paddingRight; fixed.style.paddingRight = modalOverflow || bodyOverflow ? ((parseInt(itemPad, 10) + (openModal ? 0 : scrollBarWidth)) + "px") : ((parseInt(itemPad, 10)) + "px"); }); } } function resetScrollbar() { document.body.style.paddingRight = ''; modal.style.paddingRight = ''; if (fixedItems.length) { fixedItems.forEach(function (fixed) { fixed.style.paddingRight = ''; }); } } function measureScrollbar() { var scrollDiv = document.createElement('div'); scrollDiv.className = 'modal-scrollbar-measure'; // this is here to stay document.body.appendChild(scrollDiv); var widthValue = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); return widthValue; } function createOverlay() { var newOverlay = document.createElement('div'); overlay = queryElement('.modal-backdrop'); if (overlay === null) { newOverlay.setAttribute('class', ("modal-backdrop" + (ops.animation ? ' fade' : ''))); overlay = newOverlay; document.body.appendChild(overlay); } return overlay; } function removeOverlay() { overlay = queryElement('.modal-backdrop'); if (overlay && !document.getElementsByClassName('modal show')[0]) { document.body.removeChild(overlay); overlay = null; } if (overlay === null) { document.body.classList.remove('modal-open'); resetScrollbar(); } } function toggleEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; window[action]('resize', self.update, passiveHandler); modal[action]('click', dismissHandler, false); document[action]('keydown', keyHandler, false); } // triggers function beforeShow() { modal.style.display = 'block'; setScrollbar(); if (!document.getElementsByClassName('modal show')[0]) { document.body.classList.add('modal-open'); } modal.classList.add('show'); modal.setAttribute('aria-hidden', false); if (modal.classList.contains('fade')) { emulateTransitionEnd(modal, triggerShow); } else { triggerShow(); } } function triggerShow() { setFocus(modal); modal.isAnimating = false; toggleEvents(1); shownCustomEvent = bootstrapCustomEvent('shown', 'modal', { relatedTarget: relatedTarget }); dispatchCustomEvent.call(modal, shownCustomEvent); } function triggerHide(force) { modal.style.display = ''; if (element) { setFocus(element); } overlay = queryElement('.modal-backdrop'); // force can also be the transitionEvent object, we wanna make sure it's not if (force !== 1 && overlay && overlay.classList.contains('show') && !document.getElementsByClassName('modal show')[0]) { overlay.classList.remove('show'); emulateTransitionEnd(overlay, removeOverlay); } else { removeOverlay(); } toggleEvents(); modal.isAnimating = false; hiddenCustomEvent = bootstrapCustomEvent('hidden', 'modal'); dispatchCustomEvent.call(modal, hiddenCustomEvent); } // handlers function clickHandler(e) { if (modal.isAnimating) { return; } var clickTarget = e.target; var modalID = "#" + (modal.getAttribute('id')); var targetAttrValue = clickTarget.getAttribute('data-target') || clickTarget.getAttribute('href'); var elemAttrValue = element.getAttribute('data-target') || element.getAttribute('href'); if (!modal.classList.contains('show') && ((clickTarget === element && targetAttrValue === modalID) || (element.contains(clickTarget) && elemAttrValue === modalID))) { modal.modalTrigger = element; relatedTarget = element; self.show(); e.preventDefault(); } } function keyHandler(ref) { var which = ref.which; if (!modal.isAnimating && ops.keyboard && which === 27 && modal.classList.contains('show')) { self.hide(); } } function dismissHandler(e) { if (modal.isAnimating) { return; } var clickTarget = e.target; var hasData = clickTarget.getAttribute('data-dismiss') === 'modal'; var parentWithData = clickTarget.closest('[data-dismiss="modal"]'); if (modal.classList.contains('show') && (parentWithData || hasData || (clickTarget === modal && ops.backdrop !== 'static'))) { self.hide(); relatedTarget = null; e.preventDefault(); } } // public methods self.toggle = function () { if (modal.classList.contains('show')) { self.hide(); } else { self.show(); } }; self.show = function () { if (modal.classList.contains('show') && !!modal.isAnimating) { return; } showCustomEvent = bootstrapCustomEvent('show', 'modal', { relatedTarget: relatedTarget }); dispatchCustomEvent.call(modal, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } modal.isAnimating = true; // we elegantly hide any opened modal var currentOpen = document.getElementsByClassName('modal show')[0]; if (currentOpen && currentOpen !== modal) { if (currentOpen.modalTrigger) { currentOpen.modalTrigger.Modal.hide(); } if (currentOpen.Modal) { currentOpen.Modal.hide(); } } if (ops.backdrop) { overlay = createOverlay(); } if (overlay && !currentOpen && !overlay.classList.contains('show')) { reflow(overlay); overlayDelay = getElementTransitionDuration(overlay); overlay.classList.add('show'); } if (!currentOpen) { setTimeout(beforeShow, overlay && overlayDelay ? overlayDelay : 0); } else { beforeShow(); } }; self.hide = function (force) { if (!modal.classList.contains('show')) { return; } hideCustomEvent = bootstrapCustomEvent('hide', 'modal'); dispatchCustomEvent.call(modal, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } modal.isAnimating = true; modal.classList.remove('show'); modal.setAttribute('aria-hidden', true); if (modal.classList.contains('fade') && force !== 1) { emulateTransitionEnd(modal, triggerHide); } else { triggerHide(); } }; self.setContent = function (content) { queryElement('.modal-content', modal).innerHTML = content; }; self.update = function () { if (modal.classList.contains('show')) { setScrollbar(); } }; self.dispose = function () { self.hide(1); if (element) { element.removeEventListener('click', clickHandler, false); delete element.Modal; } else { delete modal.Modal; } }; // init // the modal (both JavaScript / DATA API init) / triggering button element (DATA API) element = queryElement(elem); // determine modal, triggering element var checkModal = queryElement(element.getAttribute('data-target') || element.getAttribute('href')); modal = element.classList.contains('modal') ? element : checkModal; // set fixed items fixedItems = Array.from(document.getElementsByClassName('fixed-top')) .concat(Array.from(document.getElementsByClassName('fixed-bottom'))); if (element.classList.contains('modal')) { element = null; } // modal is now independent of it's triggering element // reset on re-init if (element && element.Modal) { element.Modal.dispose(); } if (modal && modal.Modal) { modal.Modal.dispose(); } // set options ops.keyboard = !(options.keyboard === false || modal.getAttribute('data-keyboard') === 'false'); ops.backdrop = options.backdrop === 'static' || modal.getAttribute('data-backdrop') === 'static' ? 'static' : true; ops.backdrop = options.backdrop === false || modal.getAttribute('data-backdrop') === 'false' ? false : ops.backdrop; ops.animation = !!modal.classList.contains('fade'); ops.content = options.content; // JavaScript only // set an initial state of the modal modal.isAnimating = false; // prevent adding event handlers over and over // modal is independent of a triggering element if (element && !element.Modal) { element.addEventListener('click', clickHandler, false); } if (ops.content) { self.setContent(ops.content.trim()); } // set associations if (element) { modal.modalTrigger = element; element.Modal = self; } else { modal.Modal = self; } } var mouseClickEvents = { down: 'mousedown', up: 'mouseup' }; // Popover, Tooltip & ScrollSpy function getScroll() { return { y: window.pageYOffset || document.documentElement.scrollTop, x: window.pageXOffset || document.documentElement.scrollLeft, }; } // both popovers and tooltips (target,tooltip,placement,elementToAppendTo) function styleTip(link, element, originalPosition, parent) { var tipPositions = /\b(top|bottom|left|right)+/; var elementDimensions = { w: element.offsetWidth, h: element.offsetHeight }; var windowWidth = (document.documentElement.clientWidth || document.body.clientWidth); var windowHeight = (document.documentElement.clientHeight || document.body.clientHeight); var rect = link.getBoundingClientRect(); var scroll = parent === document.body ? getScroll() : { x: parent.offsetLeft + parent.scrollLeft, y: parent.offsetTop + parent.scrollTop }; var linkDimensions = { w: rect.right - rect.left, h: rect.bottom - rect.top }; var isPopover = element.classList.contains('popover'); var arrow = element.getElementsByClassName('arrow')[0]; var halfTopExceed = rect.top + linkDimensions.h / 2 - elementDimensions.h / 2 < 0; var halfLeftExceed = rect.left + linkDimensions.w / 2 - elementDimensions.w / 2 < 0; var halfRightExceed = rect.left + elementDimensions.w / 2 + linkDimensions.w / 2 >= windowWidth; var halfBottomExceed = rect.top + elementDimensions.h / 2 + linkDimensions.h / 2 >= windowHeight; var topExceed = rect.top - elementDimensions.h < 0; var leftExceed = rect.left - elementDimensions.w < 0; var bottomExceed = rect.top + elementDimensions.h + linkDimensions.h >= windowHeight; var rightExceed = rect.left + elementDimensions.w + linkDimensions.w >= windowWidth; var position = originalPosition; // recompute position // first, when both left and right limits are exceeded, we fall back to top|bottom position = (position === 'left' || position === 'right') && leftExceed && rightExceed ? 'top' : position; position = position === 'top' && topExceed ? 'bottom' : position; position = position === 'bottom' && bottomExceed ? 'top' : position; position = position === 'left' && leftExceed ? 'right' : position; position = position === 'right' && rightExceed ? 'left' : position; var topPosition; var leftPosition; var arrowTop; var arrowLeft; // update tooltip/popover class if (element.className.indexOf(position) === -1) { element.className = element.className.replace(tipPositions, position); } // we check the computed width & height and update here var arrowWidth = arrow.offsetWidth; var arrowHeight = arrow.offsetHeight; // apply styling to tooltip or popover // secondary|side positions if (position === 'left' || position === 'right') { if (position === 'left') { // LEFT leftPosition = rect.left + scroll.x - elementDimensions.w - (isPopover ? arrowWidth : 0); } else { // RIGHT leftPosition = rect.left + scroll.x + linkDimensions.w; } // adjust top and arrow if (halfTopExceed) { topPosition = rect.top + scroll.y; arrowTop = linkDimensions.h / 2 - arrowWidth; } else if (halfBottomExceed) { topPosition = rect.top + scroll.y - elementDimensions.h + linkDimensions.h; arrowTop = elementDimensions.h - linkDimensions.h / 2 - arrowWidth; } else { topPosition = rect.top + scroll.y - elementDimensions.h / 2 + linkDimensions.h / 2; arrowTop = elementDimensions.h / 2 - (isPopover ? arrowHeight * 0.9 : arrowHeight / 2); } // primary|vertical positions } else if (position === 'top' || position === 'bottom') { if (position === 'top') { // TOP topPosition = rect.top + scroll.y - elementDimensions.h - (isPopover ? arrowHeight : 0); } else { // BOTTOM topPosition = rect.top + scroll.y + linkDimensions.h; } // adjust left | right and also the arrow if (halfLeftExceed) { leftPosition = 0; arrowLeft = rect.left + linkDimensions.w / 2 - arrowWidth; } else if (halfRightExceed) { leftPosition = windowWidth - elementDimensions.w * 1.01; arrowLeft = elementDimensions.w - (windowWidth - rect.left) + linkDimensions.w / 2 - arrowWidth / 2; } else { leftPosition = rect.left + scroll.x - elementDimensions.w / 2 + linkDimensions.w / 2; arrowLeft = elementDimensions.w / 2 - (isPopover ? arrowWidth : arrowWidth / 2); } } // apply style to tooltip/popover and its arrow element.style.top = topPosition + "px"; element.style.left = leftPosition + "px"; if (arrowTop) { arrow.style.top = arrowTop + "px"; } if (arrowLeft) { arrow.style.left = arrowLeft + "px"; } } /* Native JavaScript for Bootstrap 4 | Popover ---------------------------------------------- */ // POPOVER DEFINITION // ================== function Popover(elem, opsInput) { var element; // set instance options var options = opsInput || {}; // bind var self = this; // popover and timer var popover = null; var timer = 0; var isIphone = /(iPhone|iPod|iPad)/.test(navigator.userAgent); // title and content var titleString; var contentString; var placementClass; // options var ops = {}; // close btn for dissmissible popover var closeBtn; // custom events var showCustomEvent; var shownCustomEvent; var hideCustomEvent; var hiddenCustomEvent; // handlers function dismissibleHandler(e) { if (popover !== null && e.target === queryElement('.close', popover)) { self.hide(); } } // private methods function getAttr(att) { return options[att] || element.dataset[att] || null; } function getTitle() { return getAttr('title'); } function getContent() { return getAttr('content'); } function removePopover() { ops.container.removeChild(popover); timer = null; popover = null; } function createPopover() { titleString = getTitle(); contentString = getContent(); // fixing https://github.com/thednp/bootstrap.native/issues/233 contentString = contentString ? contentString.trim() : null; popover = document.createElement('div'); // popover arrow var popoverArrow = document.createElement('div'); popoverArrow.classList.add('arrow'); popover.appendChild(popoverArrow); // create the popover from data attributes if (contentString !== null && ops.template === null) { popover.setAttribute('role', 'tooltip'); if (titleString !== null) { var popoverTitle = document.createElement('h3'); popoverTitle.classList.add('popover-header'); popoverTitle.innerHTML = ops.dismissible ? titleString + closeBtn : titleString; popover.appendChild(popoverTitle); } // set popover content var popoverBodyMarkup = document.createElement('div'); popoverBodyMarkup.classList.add('popover-body'); popoverBodyMarkup.innerHTML = ops.dismissible && titleString === null ? contentString + closeBtn : contentString; popover.appendChild(popoverBodyMarkup); } else { // or create the popover from template var popoverTemplate = document.createElement('div'); popoverTemplate.innerHTML = ops.template.trim(); popover.className = popoverTemplate.firstChild.className; popover.innerHTML = popoverTemplate.firstChild.innerHTML; var popoverHeader = queryElement('.popover-header', popover); var popoverBody = queryElement('.popover-body', popover); // fill the template with content from data attributes if (titleString && popoverHeader) { popoverHeader.innerHTML = titleString.trim(); } if (contentString && popoverBody) { popoverBody.innerHTML = contentString.trim(); } } // append to the container ops.container.appendChild(popover); popover.style.display = 'block'; if (!popover.classList.contains('popover')) { popover.classList.add('popover'); } if (!popover.classList.contains(ops.animation)) { popover.classList.add(ops.animation); } if (!popover.classList.contains(placementClass)) { popover.classList.add(placementClass); } } function showPopover() { if (!popover.classList.contains('show')) { popover.classList.add('show'); } } function updatePopover() { styleTip(element, popover, ops.placement, ops.container); } function forceFocus() { if (popover === null) { element.focus(); } } function toggleEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; if (ops.trigger === 'hover') { element[action](mouseClickEvents.down, self.show); element[action](mouseHoverEvents[0], self.show); // mouseHover = ('onmouseleave' in document) // ? [ 'mouseenter', 'mouseleave'] // : [ 'mouseover', 'mouseout' ] if (!ops.dismissible) { element[action](mouseHoverEvents[1], self.hide); } } else if (ops.trigger === 'click') { element[action](ops.trigger, self.toggle); } else if (ops.trigger === 'focus') { if (isIphone) { element[action]('click', forceFocus, false); } element[action](ops.trigger, self.toggle); } } function touchHandler(e) { if ((popover && popover.contains(e.target)) || e.target === element || element.contains(e.target)) ; else { self.hide(); } } // event toggle function dismissHandlerToggle(add) { var action = add ? 'addEventListener' : 'removeEventListener'; if (ops.dismissible) { document[action]('click', dismissibleHandler, false); } else { if (ops.trigger === 'focus') { element[action]('blur', self.hide); } if (ops.trigger === 'hover') { document[action]('touchstart', touchHandler, passiveHandler); } } window[action]('resize', self.hide, passiveHandler); } // triggers function showTrigger() { dismissHandlerToggle(1); dispatchCustomEvent.call(element, shownCustomEvent); } function hideTrigger() { dismissHandlerToggle(); removePopover(); dispatchCustomEvent.call(element, hiddenCustomEvent); } // public methods / handlers self.toggle = function () { if (popover === null) { self.show(); } else { self.hide(); } }; self.show = function () { clearTimeout(timer); timer = setTimeout(function () { if (popover === null) { dispatchCustomEvent.call(element, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } createPopover(); updatePopover(); showPopover(); if (ops.animation) { emulateTransitionEnd(popover, showTrigger); } else { showTrigger(); } } }, 20); }; self.hide = function () { clearTimeout(timer); timer = setTimeout(function () { if (popover && popover !== null && popover.classList.contains('show')) { dispatchCustomEvent.call(element, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } popover.classList.remove('show'); if (ops.animation) { emulateTransitionEnd(popover, hideTrigger); } else { hideTrigger(); } } }, ops.delay); }; self.dispose = function () { self.hide(); toggleEvents(); delete element.Popover; }; // INIT // initialization element element = queryElement(elem); // reset on re-init if (element.Popover) { element.Popover.dispose(); } // DATA API var triggerData = element.getAttribute('data-trigger'); // click / hover / focus var animationData = element.getAttribute('data-animation'); // true / false var placementData = element.getAttribute('data-placement'); var dismissibleData = element.getAttribute('data-dismissible'); var delayData = element.getAttribute('data-delay'); var containerData = element.getAttribute('data-container'); // close btn for dissmissible popover closeBtn = '<button type="button" class="close">×</button>'; // custom events showCustomEvent = bootstrapCustomEvent('show', 'popover'); shownCustomEvent = bootstrapCustomEvent('shown', 'popover'); hideCustomEvent = bootstrapCustomEvent('hide', 'popover'); hiddenCustomEvent = bootstrapCustomEvent('hidden', 'popover'); // check container var containerElement = queryElement(options.container); var containerDataElement = queryElement(containerData); // maybe the element is inside a modal var modal = element.closest('.modal'); // maybe the element is inside a fixed navbar var navbarFixedTop = element.closest('.fixed-top'); var navbarFixedBottom = element.closest('.fixed-bottom'); // set instance options ops.template = options.template ? options.template : null; // JavaScript only ops.trigger = options.trigger ? options.trigger : triggerData || 'hover'; ops.animation = options.animation && options.animation !== 'fade' ? options.animation : animationData || 'fade'; ops.placement = options.placement ? options.placement : placementData || 'top'; ops.delay = parseInt((options.delay || delayData), 10) || 200; ops.dismissible = !!(options.dismissible || dismissibleData === 'true'); ops.container = containerElement || (containerDataElement || (navbarFixedTop || (navbarFixedBottom || (modal || document.body)))); placementClass = "bs-popover-" + (ops.placement); // invalidate titleString = getTitle(); contentString = getContent(); if (!contentString && !ops.template) { return; } // init if (!element.Popover) { // prevent adding event handlers twice toggleEvents(1); } // associate target to init object element.Popover = self; } /* Native JavaScript for Bootstrap 5 | ScrollSpy ------------------------------------------------ */ // SCROLLSPY DEFINITION // ==================== function ScrollSpy(elem, opsInput) { var element; // set options var options = opsInput || {}; // bind var self = this; // GC internals var vars; var links; // targets var spyTarget; // determine which is the real scrollTarget var scrollTarget; // options var ops = {}; // private methods // populate items and targets function updateTargets() { links = spyTarget.getElementsByTagName('A'); vars.scrollTop = vars.isWindow ? getScroll().y : element.scrollTop; // only update vars once or with each mutation if (vars.length !== links.length || getScrollHeight() !== vars.scrollHeight) { var href; var targetItem; var rect; // reset arrays & update vars.items = []; vars.offsets = []; vars.scrollHeight = getScrollHeight(); vars.maxScroll = vars.scrollHeight - getOffsetHeight(); Array.from(links).forEach(function (link) { href = link.getAttribute('href'); targetItem = href && href.charAt(0) === '#' && href.slice(-1) !== '#' && queryElement(href); if (targetItem) { vars.items.push(link); rect = targetItem.getBoundingClientRect(); vars.offsets.push((vars.isWindow ? rect.top + vars.scrollTop : targetItem.offsetTop) - ops.offset); } }); vars.length = vars.items.length; } } // item update function toggleEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; scrollTarget[action]('scroll', self.refresh, passiveHandler); window[action]('resize', self.refresh, passiveHandler); } function getScrollHeight() { return scrollTarget.scrollHeight || Math.max( document.body.scrollHeight, document.documentElement.scrollHeight ); } function getOffsetHeight() { return !vars.isWindow ? element.getBoundingClientRect().height : window.innerHeight; } function clear() { Array.from(links).map(function (item) { return item.classList.contains('active') && item.classList.remove('active'); }); } function activate(input) { var item = input; var itemClassList; clear(); vars.activeItem = item; item.classList.add('active'); // activate all parents var parents = []; while (item.parentNode !== document.body) { item = item.parentNode; itemClassList = item.classList; if (itemClassList.contains('dropdown-menu') || itemClassList.contains('nav')) { parents.push(item); } } parents.forEach(function (menuItem) { var parentLink = menuItem.previousElementSibling; if (parentLink && !parentLink.classList.contains('active')) { parentLink.classList.add('active'); } }); dispatchCustomEvent.call(element, bootstrapCustomEvent('activate', 'scrollspy', { relatedTarget: vars.activeItem })); } // public method self.refresh = function () { updateTargets(); if (vars.scrollTop >= vars.maxScroll) { var newActiveItem = vars.items[vars.length - 1]; if (vars.activeItem !== newActiveItem) { activate(newActiveItem); } return; } if (vars.activeItem && vars.scrollTop < vars.offsets[0] && vars.offsets[0] > 0) { vars.activeItem = null; clear(); return; } var i = vars.length; while (i > -1) { if (vars.activeItem !== vars.items[i] && vars.scrollTop >= vars.offsets[i] && (typeof vars.offsets[i + 1] === 'undefined' || vars.scrollTop < vars.offsets[i + 1])) { activate(vars.items[i]); } i -= 1; } }; self.dispose = function () { toggleEvents(); delete element.ScrollSpy; }; // init // initialization element, the element we spy on element = queryElement(elem); // reset on re-init if (element.ScrollSpy) { element.ScrollSpy.dispose(); } // event targets, constants // DATA API var targetData = element.getAttribute('data-target'); var offsetData = element.getAttribute('data-offset'); // targets spyTarget = queryElement(options.target || targetData); // determine which is the real scrollTarget scrollTarget = element.clientHeight < element.scrollHeight ? element : window; if (!spyTarget) { return; } // set instance option ops.offset = +(options.offset || offsetData) || 10; // set instance priority variables vars = {}; vars.length = 0; vars.items = []; vars.offsets = []; vars.isWindow = scrollTarget === window; vars.activeItem = null; vars.scrollHeight = 0; vars.maxScroll = 0; // prevent adding event handlers twice if (!element.ScrollSpy) { toggleEvents(1); } self.refresh(); // associate target with init object element.ScrollSpy = self; } /* Native JavaScript for Bootstrap 4 | Tab ------------------------------------------ */ // TAB DEFINITION // ============== function Tab(elem, opsInput) { var element; // set options var options = opsInput || {}; // bind var self = this; // event targets var tabs; var dropdown; // custom events var showCustomEvent; var shownCustomEvent; var hideCustomEvent; var hiddenCustomEvent; // more GC material var next; var tabsContentContainer = false; var activeTab; var activeContent; var nextContent; var containerHeight; var equalContents; var nextHeight; // triggers function triggerEnd() { tabsContentContainer.style.height = ''; tabsContentContainer.classList.remove('collapsing'); tabs.isAnimating = false; } function triggerShow() { if (tabsContentContainer) { // height animation if (equalContents) { triggerEnd(); } else { setTimeout(function () { // enables height animation tabsContentContainer.style.height = nextHeight + "px"; // height animation reflow(tabsContentContainer); emulateTransitionEnd(tabsContentContainer, triggerEnd); }, 50); } } else { tabs.isAnimating = false; } shownCustomEvent = bootstrapCustomEvent('shown', 'tab', { relatedTarget: activeTab }); dispatchCustomEvent.call(next, shownCustomEvent); } function triggerHide() { if (tabsContentContainer) { activeContent.style.float = 'left'; nextContent.style.float = 'left'; containerHeight = activeContent.scrollHeight; } showCustomEvent = bootstrapCustomEvent('show', 'tab', { relatedTarget: activeTab }); hiddenCustomEvent = bootstrapCustomEvent('hidden', 'tab', { relatedTarget: next }); dispatchCustomEvent.call(next, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } nextContent.classList.add('active'); activeContent.classList.remove('active'); if (tabsContentContainer) { nextHeight = nextContent.scrollHeight; equalContents = nextHeight === containerHeight; tabsContentContainer.classList.add('collapsing'); tabsContentContainer.style.height = containerHeight + "px"; // height animation reflow(tabsContentContainer); activeContent.style.float = ''; nextContent.style.float = ''; } if (nextContent.classList.contains('fade')) { setTimeout(function () { nextContent.classList.add('show'); emulateTransitionEnd(nextContent, triggerShow); }, 20); } else { triggerShow(); } dispatchCustomEvent.call(activeTab, hiddenCustomEvent); } // private methods function getActiveTab() { var assign; var activeTabs = tabs.getElementsByClassName('active'); if (activeTabs.length === 1 && !activeTabs[0].parentNode.classList.contains('dropdown')) { (assign = activeTabs, activeTab = assign[0]); } else if (activeTabs.length > 1) { activeTab = activeTabs[activeTabs.length - 1]; } return activeTab; } function getActiveContent() { return queryElement(getActiveTab().getAttribute('href')); } // handler function clickHandler(e) { e.preventDefault(); next = e.currentTarget; if (!tabs.isAnimating) { self.show(); } } // public method self.show = function () { // the tab we clicked is now the next tab next = next || element; if (!next.classList.contains('active')) { nextContent = queryElement(next.getAttribute('href')); // this is the actual object, the next tab content to activate activeTab = getActiveTab(); activeContent = getActiveContent(); hideCustomEvent = bootstrapCustomEvent('hide', 'tab', { relatedTarget: next }); dispatchCustomEvent.call(activeTab, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } tabs.isAnimating = true; activeTab.classList.remove('active'); activeTab.setAttribute('aria-selected', 'false'); next.classList.add('active'); next.setAttribute('aria-selected', 'true'); if (dropdown) { if (!element.parentNode.classList.contains('dropdown-menu')) { if (dropdown.classList.contains('active')) { dropdown.classList.remove('active'); } } else if (!dropdown.classList.contains('active')) { dropdown.classList.add('active'); } } if (activeContent.classList.contains('fade')) { activeContent.classList.remove('show'); emulateTransitionEnd(activeContent, triggerHide); } else { triggerHide(); } } }; self.dispose = function () { element.removeEventListener('click', clickHandler, false); delete element.Tab; }; // INIT // initialization element element = queryElement(elem); // reset on re-init if (element.Tab) { element.Tab.dispose(); } // DATA API var heightData = element.getAttribute('data-height'); // event targets tabs = element.closest('.nav'); dropdown = tabs && queryElement('.dropdown-toggle', tabs); // instance options var animateHeight = !(!supportTransition || (options.height === false || heightData === 'false')); // set default animation state tabs.isAnimating = false; // init if (!element.Tab) { // prevent adding event handlers twice element.addEventListener('click', clickHandler, false); } if (animateHeight) { tabsContentContainer = getActiveContent().parentNode; } // associate target with init object element.Tab = self; } /* Native JavaScript for Bootstrap 4 | Toast -------------------------------------------- */ // TOAST DEFINITION // ================== function Toast(elem, opsInput) { var element; // set options var options = opsInput || {}; // bind var self = this; // toast, timer var toast; var timer = 0; // custom events var showCustomEvent; var hideCustomEvent; var shownCustomEvent; var hiddenCustomEvent; var ops = {}; // private methods function showComplete() { toast.classList.remove('showing'); toast.classList.add('show'); dispatchCustomEvent.call(toast, shownCustomEvent); if (ops.autohide) { self.hide(); } } function hideComplete() { toast.classList.add('hide'); dispatchCustomEvent.call(toast, hiddenCustomEvent); } function close() { toast.classList.remove('show'); if (ops.animation) { emulateTransitionEnd(toast, hideComplete); } else { hideComplete(); } } function disposeComplete() { clearTimeout(timer); element.removeEventListener('click', self.hide, false); delete element.Toast; } // public methods self.show = function () { if (toast && !toast.classList.contains('show')) { dispatchCustomEvent.call(toast, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } if (ops.animation) { toast.classList.add('fade'); } toast.classList.remove('hide'); reflow(toast); // force reflow toast.classList.add('showing'); if (ops.animation) { emulateTransitionEnd(toast, showComplete); } else { showComplete(); } } }; self.hide = function (noTimer) { if (toast && toast.classList.contains('show')) { dispatchCustomEvent.call(toast, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } if (noTimer) { close(); } else { timer = setTimeout(close, ops.delay); } } }; self.dispose = function () { if (ops.animation) { emulateTransitionEnd(toast, disposeComplete); } else { disposeComplete(); } }; // init // initialization element element = queryElement(elem); // reset on re-init if (element.Toast) { element.Toast.dispose(); } // toast, timer toast = element.closest('.toast'); // DATA API var animationData = element.getAttribute('data-animation'); var autohideData = element.getAttribute('data-autohide'); var delayData = element.getAttribute('data-delay'); // custom events showCustomEvent = bootstrapCustomEvent('show', 'toast'); hideCustomEvent = bootstrapCustomEvent('hide', 'toast'); shownCustomEvent = bootstrapCustomEvent('shown', 'toast'); hiddenCustomEvent = bootstrapCustomEvent('hidden', 'toast'); // set instance options ops.animation = options.animation === false || animationData === 'false' ? 0 : 1; // true by default ops.autohide = options.autohide === false || autohideData === 'false' ? 0 : 1; // true by default ops.delay = parseInt((options.delay || delayData), 10) || 500; // 500ms default if (!element.Toast) { // prevent adding event handlers twice element.addEventListener('click', self.hide, false); } // associate targets to init object element.Toast = self; } /* Native JavaScript for Bootstrap 4 | Tooltip ---------------------------------------------- */ // TOOLTIP DEFINITION // ================== function Tooltip(elem, opsInput) { var element; // set options var options = opsInput || {}; // bind var self = this; // tooltip, timer, and title var tooltip = null; var timer = 0; var titleString; var placementClass; // custom events var showCustomEvent; var shownCustomEvent; var hideCustomEvent; var hiddenCustomEvent; var ops = {}; // private methods function getTitle() { return element.getAttribute('title') || element.getAttribute('data-title') || element.getAttribute('data-original-title'); } function removeToolTip() { ops.container.removeChild(tooltip); tooltip = null; timer = null; } function createToolTip() { titleString = getTitle(); // read the title again if (titleString) { // invalidate, maybe markup changed // create tooltip tooltip = document.createElement('div'); // set markup if (ops.template) { var tooltipMarkup = document.createElement('div'); tooltipMarkup.innerHTML = ops.template.trim(); tooltip.className = tooltipMarkup.firstChild.className; tooltip.innerHTML = tooltipMarkup.firstChild.innerHTML; queryElement('.tooltip-inner', tooltip).innerHTML = titleString.trim(); } else { // tooltip arrow var tooltipArrow = document.createElement('div'); tooltipArrow.classList.add('arrow'); tooltip.appendChild(tooltipArrow); // tooltip inner var tooltipInner = document.createElement('div'); tooltipInner.classList.add('tooltip-inner'); tooltip.appendChild(tooltipInner); tooltipInner.innerHTML = titleString; } // reset position tooltip.style.left = '0'; tooltip.style.top = '0'; // set class and role attribute tooltip.setAttribute('role', 'tooltip'); if (!tooltip.classList.contains('tooltip')) { tooltip.classList.add('tooltip'); } if (!tooltip.classList.contains(ops.animation)) { tooltip.classList.add(ops.animation); } if (!tooltip.classList.contains(placementClass)) { tooltip.classList.add(placementClass); } // append to container ops.container.appendChild(tooltip); } } function updateTooltip() { styleTip(element, tooltip, ops.placement, ops.container); } function showTooltip() { if (!tooltip.classList.contains('show')) { tooltip.classList.add('show'); } } function touchHandler(e) { if ((tooltip && tooltip.contains(e.target)) || e.target === element || element.contains(e.target)) ; else { self.hide(); } } // triggers function toggleAction(add) { var action = add ? 'addEventListener' : 'removeEventListener'; document[action]('touchstart', touchHandler, passiveHandler); window[action]('resize', self.hide, passiveHandler); } function showAction() { toggleAction(1); dispatchCustomEvent.call(element, shownCustomEvent); } function hideAction() { toggleAction(); removeToolTip(); dispatchCustomEvent.call(element, hiddenCustomEvent); } function toggleEvents(add) { var action = add ? 'addEventListener' : 'removeEventListener'; element[action](mouseClickEvents.down, self.show, false); element[action](mouseHoverEvents[0], self.show, false); element[action](mouseHoverEvents[1], self.hide, false); } // public methods self.show = function () { clearTimeout(timer); timer = setTimeout(function () { if (tooltip === null) { dispatchCustomEvent.call(element, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } // if(createToolTip() == false) return; if (createToolTip() !== false) { updateTooltip(); showTooltip(); if (ops.animation) { emulateTransitionEnd(tooltip, showAction); } else { showAction(); } } } }, 20); }; self.hide = function () { clearTimeout(timer); timer = setTimeout(function () { if (tooltip && tooltip.classList.contains('show')) { dispatchCustomEvent.call(element, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } tooltip.classList.remove('show'); if (ops.animation) { emulateTransitionEnd(tooltip, hideAction); } else { hideAction(); } } }, ops.delay); }; self.toggle = function () { if (!tooltip) { self.show(); } else { self.hide(); } }; self.dispose = function () { toggleEvents(); self.hide(); element.setAttribute('title', element.getAttribute('data-original-title')); element.removeAttribute('data-original-title'); delete element.Tooltip; }; // init // initialization element element = queryElement(elem); // reset on re-init if (element.Tooltip) { element.Tooltip.dispose(); } // DATA API var animationData = element.getAttribute('data-animation'); var placementData = element.getAttribute('data-placement'); var delayData = element.getAttribute('data-delay'); var containerData = element.getAttribute('data-container'); // check container var containerElement = queryElement(options.container); var containerDataElement = queryElement(containerData); // maybe the element is inside a modal var modal = element.closest('.modal'); // custom events showCustomEvent = bootstrapCustomEvent('show', 'tooltip'); shownCustomEvent = bootstrapCustomEvent('shown', 'tooltip'); hideCustomEvent = bootstrapCustomEvent('hide', 'tooltip'); hiddenCustomEvent = bootstrapCustomEvent('hidden', 'tooltip'); // maybe the element is inside a fixed navbar var navbarFixedTop = element.closest('.fixed-top'); var navbarFixedBottom = element.closest('.fixed-bottom'); // set instance options ops.animation = options.animation && options.animation !== 'fade' ? options.animation : animationData || 'fade'; ops.placement = options.placement ? options.placement : placementData || 'top'; ops.template = options.template ? options.template : null; // JavaScript only ops.delay = parseInt((options.delay || delayData), 10) || 200; ops.container = containerElement || (containerDataElement || (navbarFixedTop || (navbarFixedBottom || (modal || document.body)))); // set placement class placementClass = "bs-tooltip-" + (ops.placement); // set tooltip content titleString = getTitle(); // invalidate if (!titleString) { return; } // prevent adding event handlers twice if (!element.Tooltip) { element.setAttribute('data-original-title', titleString); element.removeAttribute('title'); toggleEvents(1); } // associate target to init object element.Tooltip = self; } var componentsInit = {}; /* Native JavaScript for Bootstrap | Initialize Data API -------------------------------------------------------- */ function initializeDataAPI(Constructor, collection) { Array.from(collection).map(function (x) { return new Constructor(x); }); } function initCallback(context) { var lookUp = context instanceof Element ? context : document; Object.keys(componentsInit).forEach(function (component) { initializeDataAPI(componentsInit[component][0], lookUp.querySelectorAll(componentsInit[component][1])); }); } componentsInit.Alert = [Alert, '[data-dismiss="alert"]']; componentsInit.Button = [Button, '[data-toggle="buttons"]']; componentsInit.Carousel = [Carousel, '[data-ride="carousel"]']; componentsInit.Collapse = [Collapse, '[data-toggle="collapse"]']; componentsInit.Dropdown = [Dropdown, '[data-toggle="dropdown"]']; componentsInit.Modal = [Modal, '[data-toggle="modal"]']; componentsInit.Popover = [Popover, '[data-toggle="popover"],[data-tip="popover"]']; componentsInit.ScrollSpy = [ScrollSpy, '[data-spy="scroll"]']; componentsInit.Tab = [Tab, '[data-toggle="tab"]']; componentsInit.Toast = [Toast, '[data-dismiss="toast"]']; componentsInit.Tooltip = [Tooltip, '[data-toggle="tooltip"],[data-tip="tooltip"]']; // bulk initialize all components if (document.body) { initCallback(); } else { document.addEventListener('DOMContentLoaded', function initWrapper() { initCallback(); document.removeEventListener('DOMContentLoaded', initWrapper, false); }, false); } /* Native JavaScript for Bootstrap | Remove Data API ---------------------------------------------------- */ function removeElementDataAPI(ConstructorName, collection) { Array.from(collection).map(function (x) { return x[ConstructorName].dispose(); }); } function removeDataAPI(context) { var lookUp = context instanceof Element ? context : document; Object.keys(componentsInit).forEach(function (component) { removeElementDataAPI(component, lookUp.querySelectorAll(componentsInit[component][1])); }); } var version = "4.0.7"; var indexV4 = { Alert: Alert, Button: Button, Carousel: Carousel, Collapse: Collapse, Dropdown: Dropdown, Modal: Modal, Popover: Popover, ScrollSpy: ScrollSpy, Tab: Tab, Toast: Toast, Tooltip: Tooltip, initCallback: initCallback, removeDataAPI: removeDataAPI, componentsInit: componentsInit, Version: version, }; export { indexV4 as default };
import {Person} from '../src/Person'; import Thing from '../src/Thing'; import mocha from 'mocha'; import should from 'should/as-function'; describe('Person interface', () => { it("Basics", (done) => { const john = new Person("John", null, "male"); const jane = john.mom('Jane'); should(john.mom('Jane').gender()).eql("female"); // Parents should be older than children should(Person.older(jane, john)).eql(true); should(jane.son()).eql(john); done(); }); it("Who Interface - absolute", (done) => { const john = new Person("John"); const mary = new Person("mary"); const jack = john.brother('jack'); const mark = john.dad('mark'); const albert = new Person("Albert Einstein"); albert.career = "Scientist"; should(albert.who()).eql("Scientist"); done(); }); // Family ties come before career it.only("Who Interface - relative", (done) => { // Who is John (in relation to jack) const john = new Person("John"); const jack = john.son('jack'); const mark = jack.son('mark'); const albert = new Person("Albert Einstein"); albert.career = "Scientist"; mark.son(albert); should(john.who(mark)).eql("grand-son"); should(albert.who()).eql("Scientist"); should(mark.who(albert)).eql("son"); should(albert.who(mark)).eql("dad"); done(); }); it("Person age - relative", (done) => { let john = new Person("John"); let mary = new Person("Mary"); let jane = new Person("Jane"); // John is 30 john.age(30); should(john.age()).eql(30); // Mary is 5 years older than John mary.older(john, 5); // Jane is 2 years younger than mary jane.older(john, 8); should(Person.older(mary, john)).eql(true); should(Person.older(mary, jane)).eql(false); // TODO - See why this is false // should(Person.older(jane, mary)).eql(true); should(mary.age()).eql(35); should(jane.age()).eql(38); done(); }); it("Person like direct", (done) => { const john = new Person("John"); const green = new Thing("green"); john.likes(green); should(john.likesFind(green)).eql([true, green]); done(); }); it("Person like in-direct", (done) => { let john = new Person("John"); let green = new Thing("green"); let color = new Thing("color"); green.isA(color); john.likes(green); should(john.likesFind(color)).eql([true, green]); done(); }); });
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['3453',"Tlece.WebApp.Controllers Namespace","topic_0000000000000013.html"],['3471',"WellKnownFileController Class","topic_0000000000000027.html"],['3473',"Methods","topic_0000000000000027_methods--.html"]];
'use strict'; const DEFAULT_CONFIG = { domain: 'localhost', port: '8888', devServerConfig: { // noInfo: true, // quiet: true, clientLogLevel: 'info', // 不启用压缩 compress: false, // enable hmr hot: true, hotOnly: true, // no lazy mode lazy: false, watchOptions: { ignored: /node_modules/, aggregateTimeout: 300, poll: false }, overlay: { warnings: false, error: true }, // options for formating the statistics stats: { children: false, errors: true, colors: true, chunks: false, chunkModules:false } } }; const DEFAULT_MOCK = { // 是否开启mock enable: false, // mock配置文件 configFile: '' }; module.exports = { config: DEFAULT_CONFIG, mock: DEFAULT_MOCK };
/* globals require console*/ "use strict"; let { ShoppingCart, Product } = require("./task-2")(); let sc = new ShoppingCart(); let p = new Product("food", "Bread", "1"); sc.add(new Product("beverages", "Whiskey", "25")); sc.add(p); sc.add(p); sc.add(p); sc.add(p); console.log(sc.showCost()); console.log(sc.showProductTypes()); console.log(sc.getInfo()); sc.remove(p); console.log(sc.getInfo());
/*! * DevExtreme (dx.messages.sv.js) * Version: 21.1.0 (build 20361-0317) * Build date: Sat Dec 26 2020 * * Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(root, factory) { if ("function" === typeof define && define.amd) { define((function(require) { factory(require("devextreme/localization")) })) } else if ("object" === typeof module && module.exports) { factory(require("devextreme/localization")) } else { factory(DevExpress.localization) } }(0, (function(localization) { localization.loadMessages({ sv: { Yes: "Ja", No: "Nej", Cancel: "Avbryt", Clear: "Rensa", Done: "Klar", Loading: "Laddar...", Select: "V\xe4lj...", Search: "S\xf6k", Back: "Tillbaka", OK: "OK", "dxCollectionWidget-noDataText": "Inget data att visa", "dxDropDownEditor-selectLabel": "V\xe4lj", "validation-required": "Kr\xe4vs", "validation-required-formatted": "{0} kr\xe4vs", "validation-numeric": "V\xe4rdet m\xe5ste vara ett nummer", "validation-numeric-formatted": "{0} m\xe5ste vara ett nummer", "validation-range": "V\xe4rdet utanf\xf6r till\xe5tet intervall", "validation-range-formatted": "{0} utanf\xf6r till\xe5tet intervall", "validation-stringLength": "L\xe4ngden p\xe5 v\xe4rdet \xe4r inte korrekt", "validation-stringLength-formatted": "L\xe4ngden p\xe5 {0} \xe4r inte korrekt", "validation-custom": "Ogiltigt v\xe4rde", "validation-custom-formatted": "{0} \xe4r ogiltigt", "validation-async": "Ogiltigt v\xe4rde", "validation-async-formatted": "{0} \xe4r ogiltigt", "validation-compare": "V\xe4rdena matchar inte", "validation-compare-formatted": "{0} matchar inte", "validation-pattern": "V\xe4rdet matchar inte m\xf6nster", "validation-pattern-formatted": "{0} matchar inte m\xf6nster", "validation-email": "E-post \xe4r ogiltigt", "validation-email-formatted": "{0} \xe4r ogiltigt", "validation-mask": "V\xe4rdet \xe4r ogiltigt", "dxLookup-searchPlaceholder": "Minsta antal tecken: {0}", "dxList-pullingDownText": "Dra ner\xe5t f\xf6r att uppdatera...", "dxList-pulledDownText": "Sl\xe4pp f\xf6r att uppdatera...", "dxList-refreshingText": "Uppdaterar...", "dxList-pageLoadingText": "Laddar...", "dxList-nextButtonText": "Mer", "dxList-selectAll": "V\xe4lj alla", "dxListEditDecorator-delete": "Radera", "dxListEditDecorator-more": "Mer", "dxScrollView-pullingDownText": "Dra ner\xe5t f\xf6r att uppdatera...", "dxScrollView-pulledDownText": "Sl\xe4pp f\xf6r att uppdatera...", "dxScrollView-refreshingText": "uppdaterar...", "dxScrollView-reachBottomText": "Laddar...", "dxDateBox-simulatedDataPickerTitleTime": "V\xe4lj tid", "dxDateBox-simulatedDataPickerTitleDate": "V\xe4lj datum", "dxDateBox-simulatedDataPickerTitleDateTime": "V\xe4lj datum och tid", "dxDateBox-validation-datetime": "V\xe4rdet m\xe5ste vara ett datum eller en tid", "dxFileUploader-selectFile": "V\xe4lj fil", "dxFileUploader-dropFile": "eller sl\xe4pp filen h\xe4r", "dxFileUploader-bytes": "byte", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "Ladda upp", "dxFileUploader-uploaded": "Uppladdad", "dxFileUploader-readyToUpload": "Klar att ladda upp", "dxFileUploader-uploadAbortedMessage": "TODO", "dxFileUploader-uploadFailedMessage": "Uppladdning misslyckades", "dxFileUploader-invalidFileExtension": "", "dxFileUploader-invalidMaxFileSize": "", "dxFileUploader-invalidMinFileSize": "", "dxRangeSlider-ariaFrom": "Fr\xe5n", "dxRangeSlider-ariaTill": "Till", "dxSwitch-switchedOnText": "P\xc5", "dxSwitch-switchedOffText": "AV", "dxForm-optionalMark": "valfri", "dxForm-requiredMessage": "{0} \xe4r n\xf6dv\xe4ndigt", "dxNumberBox-invalidValueMessage": "V\xe4rdet m\xe5ste vara ett nummer", "dxNumberBox-noDataText": "Inget data", "dxDataGrid-columnChooserTitle": "Kolumnv\xe4ljare", "dxDataGrid-columnChooserEmptyText": "Dra en kolumn hit f\xf6r att d\xf6lja den", "dxDataGrid-groupContinuesMessage": "Forts\xe4tter p\xe5 n\xe4sta sida", "dxDataGrid-groupContinuedMessage": "Forts\xe4ttning fr\xe5n f\xf6reg\xe5ende sida", "dxDataGrid-groupHeaderText": "Gruppera enligt denna kolumn", "dxDataGrid-ungroupHeaderText": "Avgruppera", "dxDataGrid-ungroupAllText": "Avgruppera allt", "dxDataGrid-editingEditRow": "Redigera", "dxDataGrid-editingSaveRowChanges": "Spara", "dxDataGrid-editingCancelRowChanges": "Avbryt", "dxDataGrid-editingDeleteRow": "Radera", "dxDataGrid-editingUndeleteRow": "\xc5ngra radering", "dxDataGrid-editingConfirmDeleteMessage": "\xc4r du s\xe4ker p\xe5 att du vill radera denna post?", "dxDataGrid-validationCancelChanges": "Avbryt \xe4ndringarna", "dxDataGrid-groupPanelEmptyText": "Dra en kolumnrubrik hit f\xf6r att gruppera enligt den kolumnen", "dxDataGrid-noDataText": "Inget data", "dxDataGrid-searchPanelPlaceholder": "S\xf6k...", "dxDataGrid-filterRowShowAllText": "(Allt)", "dxDataGrid-filterRowResetOperationText": "\xc5terst\xe4ll", "dxDataGrid-filterRowOperationEquals": "\xc4r lika med", "dxDataGrid-filterRowOperationNotEquals": "\xc4r olika", "dxDataGrid-filterRowOperationLess": "Mindre \xe4n", "dxDataGrid-filterRowOperationLessOrEquals": "Mindre \xe4n eller lika med", "dxDataGrid-filterRowOperationGreater": "St\xf6rre \xe4n", "dxDataGrid-filterRowOperationGreaterOrEquals": "St\xf6rre \xe4n eller lika med", "dxDataGrid-filterRowOperationStartsWith": "B\xf6rjar med", "dxDataGrid-filterRowOperationContains": "Inneh\xe5ller", "dxDataGrid-filterRowOperationNotContains": "Inneh\xe5ller inte", "dxDataGrid-filterRowOperationEndsWith": "Slutar med", "dxDataGrid-filterRowOperationBetween": "Mellan", "dxDataGrid-filterRowOperationBetweenStartText": "Start", "dxDataGrid-filterRowOperationBetweenEndText": "Slut", "dxDataGrid-applyFilterText": "Anv\xe4nd filter", "dxDataGrid-trueText": "sant", "dxDataGrid-falseText": "falskt", "dxDataGrid-sortingAscendingText": "Sortera stigande", "dxDataGrid-sortingDescendingText": "Sortera fallande", "dxDataGrid-sortingClearText": "Rensa sortering", "dxDataGrid-editingSaveAllChanges": "Spara \xe4ndringar", "dxDataGrid-editingCancelAllChanges": "\xc5ngra \xe4ndringar", "dxDataGrid-editingAddRow": "L\xe4gg till rad", "dxDataGrid-summaryMin": "Min: {0}", "dxDataGrid-summaryMinOtherColumn": "Minimi av {1} \xe4r {0}", "dxDataGrid-summaryMax": "Max: {0}", "dxDataGrid-summaryMaxOtherColumn": "Maximi av {1} \xe4r {0}", "dxDataGrid-summaryAvg": "Medel: {0}", "dxDataGrid-summaryAvgOtherColumn": "Medeltal av {1} \xe4r {0}", "dxDataGrid-summarySum": "Sum: {0}", "dxDataGrid-summarySumOtherColumn": "Summan av {1} \xe4r {0}", "dxDataGrid-summaryCount": "Antal: {0}", "dxDataGrid-columnFixingFix": "Fixera", "dxDataGrid-columnFixingUnfix": "Avfixera", "dxDataGrid-columnFixingLeftPosition": "Till v\xe4nster", "dxDataGrid-columnFixingRightPosition": "Till h\xf6ger", "dxDataGrid-exportTo": "Exportera", "dxDataGrid-exportToExcel": "Exportera till Excel fil", "dxDataGrid-exporting": "Exportera...", "dxDataGrid-excelFormat": "Excel fil", "dxDataGrid-selectedRows": "Valda rader", "dxDataGrid-exportSelectedRows": "Exportera valda rader", "dxDataGrid-exportAll": "Exportera allt", "dxDataGrid-headerFilterEmptyValue": "(Tomma)", "dxDataGrid-headerFilterOK": "OK", "dxDataGrid-headerFilterCancel": "Avbryt", "dxDataGrid-ariaColumn": "Kolumn", "dxDataGrid-ariaValue": "V\xe4rde", "dxDataGrid-ariaFilterCell": "Filtrera cell", "dxDataGrid-ariaCollapse": "Kollapsa", "dxDataGrid-ariaExpand": "Expandera", "dxDataGrid-ariaDataGrid": "Datarutn\xe4t", "dxDataGrid-ariaSearchInGrid": "S\xf6k i datarutn\xe4tet", "dxDataGrid-ariaSelectAll": "V\xe4lj allt", "dxDataGrid-ariaSelectRow": "V\xe4lj rad", "dxDataGrid-filterBuilderPopupTitle": "Filterverktyg", "dxDataGrid-filterPanelCreateFilter": "Skapa filter", "dxDataGrid-filterPanelClearFilter": "Rensa", "dxDataGrid-filterPanelFilterEnabledHint": "Aktivera filter", "dxTreeList-ariaTreeList": "Tr\xe4dlista", "dxTreeList-editingAddRowToNode": "L\xe4gg till", "dxPager-infoText": "Sida {0} av {1} ({2} uppgifter)", "dxPager-pagesCountText": "av", "dxPager-pageSizesAllText": "Allt", "dxPivotGrid-grandTotal": "Totalsumma", "dxPivotGrid-total": "{0} Summa", "dxPivotGrid-fieldChooserTitle": "F\xe4ltv\xe4ljare", "dxPivotGrid-showFieldChooser": "Visa f\xe4ltv\xe4ljare", "dxPivotGrid-expandAll": "Expandera alla", "dxPivotGrid-collapseAll": "Kollapsa alla", "dxPivotGrid-sortColumnBySummary": 'Sortera "{0}" enligt denna kolumn', "dxPivotGrid-sortRowBySummary": 'Sortera "{0}" enligt denna rad', "dxPivotGrid-removeAllSorting": "Avl\xe4gsna all sortering", "dxPivotGrid-dataNotAvailable": "Saknas", "dxPivotGrid-rowFields": "Radf\xe4lt", "dxPivotGrid-columnFields": "Kolumnf\xe4lt", "dxPivotGrid-dataFields": "Dataf\xe4lt", "dxPivotGrid-filterFields": "Filterf\xe4lt", "dxPivotGrid-allFields": "Alla f\xe4lt", "dxPivotGrid-columnFieldArea": "Sl\xe4pp kolumnf\xe4lt h\xe4r", "dxPivotGrid-dataFieldArea": "Sl\xe4pp dataf\xe4lt h\xe4r", "dxPivotGrid-rowFieldArea": "Sl\xe4pp radf\xe4lt h\xe4r", "dxPivotGrid-filterFieldArea": "Sl\xe4pp filterf\xe4lt h\xe4r", "dxScheduler-editorLabelTitle": "\xc4mne", "dxScheduler-editorLabelStartDate": "Startdatum", "dxScheduler-editorLabelEndDate": "Slutdatum", "dxScheduler-editorLabelDescription": "Beskrivning", "dxScheduler-editorLabelRecurrence": "Upprepa", "dxScheduler-openAppointment": "\xd6ppna avtalad tid", "dxScheduler-recurrenceNever": "Aldrig", "dxScheduler-recurrenceMinutely": "Minutely", "dxScheduler-recurrenceHourly": "Hourly", "dxScheduler-recurrenceDaily": "Varje dag", "dxScheduler-recurrenceWeekly": "Varje vecka", "dxScheduler-recurrenceMonthly": "Varje m\xe5nad", "dxScheduler-recurrenceYearly": "Varje \xe5r", "dxScheduler-recurrenceRepeatEvery": "Varje", "dxScheduler-recurrenceRepeatOn": "Repeat On", "dxScheduler-recurrenceEnd": "Upprepning slutar", "dxScheduler-recurrenceAfter": "Efter", "dxScheduler-recurrenceOn": "P\xe5", "dxScheduler-recurrenceRepeatMinutely": "minute(s)", "dxScheduler-recurrenceRepeatHourly": "hour(s)", "dxScheduler-recurrenceRepeatDaily": "dagar", "dxScheduler-recurrenceRepeatWeekly": "veckor", "dxScheduler-recurrenceRepeatMonthly": "m\xe5nader", "dxScheduler-recurrenceRepeatYearly": "\xe5r", "dxScheduler-switcherDay": "Dag", "dxScheduler-switcherWeek": "Vecka", "dxScheduler-switcherWorkWeek": "Arbetsvecka", "dxScheduler-switcherMonth": "M\xe5nad", "dxScheduler-switcherAgenda": "Agenda", "dxScheduler-switcherTimelineDay": "Tidslinje dag", "dxScheduler-switcherTimelineWeek": "Tidslinje vecka", "dxScheduler-switcherTimelineWorkWeek": "Tidslinje arbetsvecka", "dxScheduler-switcherTimelineMonth": "Tidslinje m\xe5nad", "dxScheduler-recurrenceRepeatOnDate": "p\xe5 datumet", "dxScheduler-recurrenceRepeatCount": "upprepning(ar)", "dxScheduler-allDay": "Hela dagen", "dxScheduler-confirmRecurrenceEditMessage": "Vill du redigera bara denna avtalade tid eller hela serien?", "dxScheduler-confirmRecurrenceDeleteMessage": "Vill du radera bara denna avtalade tid eller hela serien?", "dxScheduler-confirmRecurrenceEditSeries": "Redigera serien", "dxScheduler-confirmRecurrenceDeleteSeries": "Radera serien", "dxScheduler-confirmRecurrenceEditOccurrence": "Redigera avtalad tid", "dxScheduler-confirmRecurrenceDeleteOccurrence": "Radera avtalad tid", "dxScheduler-noTimezoneTitle": "Ingen tidszon", "dxScheduler-moreAppointments": "{0} mer", "dxCalendar-todayButtonText": "I dag", "dxCalendar-ariaWidgetName": "Kalender", "dxColorView-ariaRed": "R\xf6d", "dxColorView-ariaGreen": "Gr\xf6n", "dxColorView-ariaBlue": "Bl\xe5", "dxColorView-ariaAlpha": "Transparens", "dxColorView-ariaHex": "F\xe4rgkod", "dxTagBox-selected": "{0} valda", "dxTagBox-allSelected": "Alla valda ({0})", "dxTagBox-moreSelected": "{0} mer", "vizExport-printingButtonText": "Skriv ut", "vizExport-titleMenuText": "Export/Utskrift", "vizExport-exportButtonText": "{0} fil", "dxFilterBuilder-and": "Och", "dxFilterBuilder-or": "Eller", "dxFilterBuilder-notAnd": "Inte och", "dxFilterBuilder-notOr": "Inte eller", "dxFilterBuilder-addCondition": "L\xe4gg till villkor", "dxFilterBuilder-addGroup": "L\xe4gg till grupp", "dxFilterBuilder-enterValueText": "<ange v\xe4rde>", "dxFilterBuilder-filterOperationEquals": "\xc4r lika med", "dxFilterBuilder-filterOperationNotEquals": "\xc4r olika", "dxFilterBuilder-filterOperationLess": "Mindre \xe4n", "dxFilterBuilder-filterOperationLessOrEquals": "Mindre \xe4n eller lika med", "dxFilterBuilder-filterOperationGreater": "St\xf6rre \xe4n", "dxFilterBuilder-filterOperationGreaterOrEquals": "St\xf6rre \xe4n eller lika med", "dxFilterBuilder-filterOperationStartsWith": "B\xf6rjar med", "dxFilterBuilder-filterOperationContains": "Inneh\xe5ller", "dxFilterBuilder-filterOperationNotContains": "Inneh\xe5ller inte", "dxFilterBuilder-filterOperationEndsWith": "Slutar med", "dxFilterBuilder-filterOperationIsBlank": "\xc4r tom", "dxFilterBuilder-filterOperationIsNotBlank": "\xc4r inte tom", "dxFilterBuilder-filterOperationBetween": "Mellan", "dxFilterBuilder-filterOperationAnyOf": "N\xe5gon av", "dxFilterBuilder-filterOperationNoneOf": "Ingen av", "dxHtmlEditor-dialogColorCaption": "!TODO!", "dxHtmlEditor-dialogBackgroundCaption": "!TODO!", "dxHtmlEditor-dialogLinkCaption": "!TODO!", "dxHtmlEditor-dialogLinkUrlField": "!TODO!", "dxHtmlEditor-dialogLinkTextField": "!TODO!", "dxHtmlEditor-dialogLinkTargetField": "!TODO!", "dxHtmlEditor-dialogImageCaption": "!TODO!", "dxHtmlEditor-dialogImageUrlField": "!TODO!", "dxHtmlEditor-dialogImageAltField": "!TODO!", "dxHtmlEditor-dialogImageWidthField": "!TODO!", "dxHtmlEditor-dialogImageHeightField": "!TODO!", "dxHtmlEditor-dialogInsertTableRowsField": "!TODO", "dxHtmlEditor-dialogInsertTableColumnsField": "!TODO", "dxHtmlEditor-dialogInsertTableCaption": "!TODO", "dxHtmlEditor-heading": "!TODO!", "dxHtmlEditor-normalText": "!TODO!", "dxFileManager-newDirectoryName": "TODO", "dxFileManager-rootDirectoryName": "TODO", "dxFileManager-errorNoAccess": "TODO", "dxFileManager-errorDirectoryExistsFormat": "TODO", "dxFileManager-errorFileExistsFormat": "TODO", "dxFileManager-errorFileNotFoundFormat": "TODO", "dxFileManager-errorDirectoryNotFoundFormat": "TODO", "dxFileManager-errorWrongFileExtension": "TODO", "dxFileManager-errorMaxFileSizeExceeded": "TODO", "dxFileManager-errorInvalidSymbols": "TODO", "dxFileManager-errorDefault": "TODO", "dxFileManager-errorDirectoryOpenFailed": "TODO", "dxDiagram-categoryGeneral": "TODO", "dxDiagram-categoryFlowchart": "TODO", "dxDiagram-categoryOrgChart": "TODO", "dxDiagram-categoryContainers": "TODO", "dxDiagram-categoryCustom": "TODO", "dxDiagram-commandExportToSvg": "TODO", "dxDiagram-commandExportToPng": "TODO", "dxDiagram-commandExportToJpg": "TODO", "dxDiagram-commandUndo": "TODO", "dxDiagram-commandRedo": "TODO", "dxDiagram-commandFontName": "TODO", "dxDiagram-commandFontSize": "TODO", "dxDiagram-commandBold": "TODO", "dxDiagram-commandItalic": "TODO", "dxDiagram-commandUnderline": "TODO", "dxDiagram-commandTextColor": "TODO", "dxDiagram-commandLineColor": "TODO", "dxDiagram-commandLineWidth": "TODO", "dxDiagram-commandLineStyle": "TODO", "dxDiagram-commandLineStyleSolid": "TODO", "dxDiagram-commandLineStyleDotted": "TODO", "dxDiagram-commandLineStyleDashed": "TODO", "dxDiagram-commandFillColor": "TODO", "dxDiagram-commandAlignLeft": "TODO", "dxDiagram-commandAlignCenter": "TODO", "dxDiagram-commandAlignRight": "TODO", "dxDiagram-commandConnectorLineType": "TODO", "dxDiagram-commandConnectorLineStraight": "TODO", "dxDiagram-commandConnectorLineOrthogonal": "TODO", "dxDiagram-commandConnectorLineStart": "TODO", "dxDiagram-commandConnectorLineEnd": "TODO", "dxDiagram-commandConnectorLineNone": "TODO", "dxDiagram-commandConnectorLineArrow": "TODO", "dxDiagram-commandFullscreen": "TODO", "dxDiagram-commandUnits": "TODO", "dxDiagram-commandPageSize": "TODO", "dxDiagram-commandPageOrientation": "TODO", "dxDiagram-commandPageOrientationLandscape": "TODO", "dxDiagram-commandPageOrientationPortrait": "TODO", "dxDiagram-commandPageColor": "TODO", "dxDiagram-commandShowGrid": "TODO", "dxDiagram-commandSnapToGrid": "TODO", "dxDiagram-commandGridSize": "TODO", "dxDiagram-commandZoomLevel": "TODO", "dxDiagram-commandAutoZoom": "TODO", "dxDiagram-commandFitToContent": "TODO", "dxDiagram-commandFitToWidth": "TODO", "dxDiagram-commandAutoZoomByContent": "TODO", "dxDiagram-commandAutoZoomByWidth": "TODO", "dxDiagram-commandSimpleView": "TODO", "dxDiagram-commandCut": "TODO", "dxDiagram-commandCopy": "TODO", "dxDiagram-commandPaste": "TODO", "dxDiagram-commandSelectAll": "TODO", "dxDiagram-commandDelete": "TODO", "dxDiagram-commandBringToFront": "TODO", "dxDiagram-commandSendToBack": "TODO", "dxDiagram-commandLock": "TODO", "dxDiagram-commandUnlock": "TODO", "dxDiagram-commandInsertShapeImage": "TODO", "dxDiagram-commandEditShapeImage": "TODO", "dxDiagram-commandDeleteShapeImage": "TODO", "dxDiagram-commandLayoutLeftToRight": "TODO", "dxDiagram-commandLayoutRightToLeft": "TODO", "dxDiagram-commandLayoutTopToBottom": "TODO", "dxDiagram-commandLayoutBottomToTop": "TODO", "dxDiagram-unitIn": "TODO", "dxDiagram-unitCm": "TODO", "dxDiagram-unitPx": "TODO", "dxDiagram-dialogButtonOK": "TODO", "dxDiagram-dialogButtonCancel": "TODO", "dxDiagram-dialogInsertShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageSelectButton": "TODO", "dxDiagram-dialogEditShapeImageLabelText": "TODO", "dxDiagram-uiExport": "TODO", "dxDiagram-uiProperties": "TODO", "dxDiagram-uiSettings": "TODO", "dxDiagram-uiShowToolbox": "TODO", "dxDiagram-uiSearch": "TODO", "dxDiagram-uiStyle": "TODO", "dxDiagram-uiLayout": "TODO", "dxDiagram-uiLayoutTree": "TODO", "dxDiagram-uiLayoutLayered": "TODO", "dxDiagram-uiDiagram": "TODO", "dxDiagram-uiText": "TODO", "dxDiagram-uiObject": "TODO", "dxDiagram-uiConnector": "TODO", "dxDiagram-uiPage": "TODO", "dxDiagram-shapeText": "TODO", "dxDiagram-shapeRectangle": "TODO", "dxDiagram-shapeEllipse": "TODO", "dxDiagram-shapeCross": "TODO", "dxDiagram-shapeTriangle": "TODO", "dxDiagram-shapeDiamond": "TODO", "dxDiagram-shapeHeart": "TODO", "dxDiagram-shapePentagon": "TODO", "dxDiagram-shapeHexagon": "TODO", "dxDiagram-shapeOctagon": "TODO", "dxDiagram-shapeStar": "TODO", "dxDiagram-shapeArrowLeft": "TODO", "dxDiagram-shapeArrowUp": "TODO", "dxDiagram-shapeArrowRight": "TODO", "dxDiagram-shapeArrowDown": "TODO", "dxDiagram-shapeArrowUpDown": "TODO", "dxDiagram-shapeArrowLeftRight": "TODO", "dxDiagram-shapeProcess": "TODO", "dxDiagram-shapeDecision": "TODO", "dxDiagram-shapeTerminator": "TODO", "dxDiagram-shapePredefinedProcess": "TODO", "dxDiagram-shapeDocument": "TODO", "dxDiagram-shapeMultipleDocuments": "TODO", "dxDiagram-shapeManualInput": "TODO", "dxDiagram-shapePreparation": "TODO", "dxDiagram-shapeData": "TODO", "dxDiagram-shapeDatabase": "TODO", "dxDiagram-shapeHardDisk": "TODO", "dxDiagram-shapeInternalStorage": "TODO", "dxDiagram-shapePaperTape": "TODO", "dxDiagram-shapeManualOperation": "TODO", "dxDiagram-shapeDelay": "TODO", "dxDiagram-shapeStoredData": "TODO", "dxDiagram-shapeDisplay": "TODO", "dxDiagram-shapeMerge": "TODO", "dxDiagram-shapeConnector": "TODO", "dxDiagram-shapeOr": "TODO", "dxDiagram-shapeSummingJunction": "TODO", "dxDiagram-shapeContainerDefaultText": "TODO", "dxDiagram-shapeVerticalContainer": "TODO", "dxDiagram-shapeHorizontalContainer": "TODO", "dxDiagram-shapeCardDefaultText": "TODO", "dxDiagram-shapeCardWithImageOnLeft": "TODO", "dxDiagram-shapeCardWithImageOnTop": "TODO", "dxDiagram-shapeCardWithImageOnRight": "TODO", "dxGantt-dialogTitle": "TODO", "dxGantt-dialogStartTitle": "TODO", "dxGantt-dialogEndTitle": "TODO", "dxGantt-dialogProgressTitle": "TODO", "dxGantt-dialogResourcesTitle": "TODO", "dxGantt-dialogResourceManagerTitle": "TODO", "dxGantt-dialogTaskDetailsTitle": "TODO", "dxGantt-dialogEditResourceListHint": "TODO", "dxGantt-dialogEditNoResources": "TODO", "dxGantt-dialogButtonAdd": "TODO", "dxGantt-contextMenuNewTask": "TODO", "dxGantt-contextMenuNewSubtask": "TODO", "dxGantt-contextMenuDeleteTask": "TODO", "dxGantt-contextMenuDeleteDependency": "TODO", "dxGantt-dialogTaskDeleteConfirmation": "TODO", "dxGantt-dialogDependencyDeleteConfirmation": "TODO", "dxGantt-dialogResourcesDeleteConfirmation": "TODO", "dxGantt-dialogConstraintCriticalViolationMessage": "TODO", "dxGantt-dialogConstraintViolationMessage": "TODO", "dxGantt-dialogCancelOperationMessage": "TODO", "dxGantt-dialogDeleteDependencyMessage": "TODO", "dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO", "dxGantt-undo": "TODO", "dxGantt-redo": "TODO", "dxGantt-expandAll": "TODO", "dxGantt-collapseAll": "TODO", "dxGantt-addNewTask": "TODO", "dxGantt-deleteSelectedTask": "TODO", "dxGantt-zoomIn": "TODO", "dxGantt-zoomOut": "TODO", "dxGantt-fullScreen": "TODO", "dxGantt-quarter": "TODO" } }) }));
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var GetBottom = require('../../bounds/GetBottom'); var GetRight = require('../../bounds/GetRight'); var SetRight = require('../../bounds/SetRight'); var SetTop = require('../../bounds/SetTop'); /** * Takes given Game Object and aligns it so that it is positioned next to the bottom right position of the other. * * @function Phaser.Display.Align.To.BottomRight * @since 3.0.0 * * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] * * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. * @param {number} [offsetX=0] - Optional horizontal offset from the position. * @param {number} [offsetY=0] - Optional vertical offset from the position. * * @return {Phaser.GameObjects.GameObject} The Game Object that was aligned. */ var BottomRight = function (gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } SetRight(gameObject, GetRight(alignTo) + offsetX); SetTop(gameObject, GetBottom(alignTo) + offsetY); return gameObject; }; module.exports = BottomRight;
#!/usr/bin/env node var vows = require('vows'), assert = require('assert'), path = require('path'), basename = path.basename(__filename), Template = require('../lib/Template'); /** * @private */ function assertTopicPropertyContext(value, toString) { value = toString ? value.toString() : value; var context = { topic: function (topic) { return topic[this.context.name]; } } context["is " + value] = function (topic) { assert.strictEqual(toString ? topic.toString() : topic, value); }; return context; } /** * @private */ function assertAppliedStringContext(value) { var context = { topic: function (template) { return template.process(this.context.name); } }; context["is " + value] = function (applied) { assert.strictEqual(applied, value); }; return context; } /** * Test suite */ vows.describe(basename).addBatch({ "template": { topic: new Template(), "instanceof Template": function (template) { assert.strictEqual(template instanceof Template, true); }, "property": { // proto "type": assertTopicPropertyContext('txt'), "settings": { topic: function (template) { return template.settings; }, "tagStart": assertTopicPropertyContext('#{'), "tagEnd": assertTopicPropertyContext('}#') } }, "process": { topic: function (template) { template.def = { DEBUG: false, PARTIAL: 'This is a partial.', argv: { RELEASE: true } } return template; }, "compile-time": { "Testing some string here. IS DEBUG: #{#def.DEBUG}#": assertAppliedStringContext('Testing some string here. IS DEBUG: false'), "Testing some string here#{##def.NEW_PARTIAL:This is a new partial.#}# ok what.": assertAppliedStringContext('Testing some string here ok what.'), "Testing#{##def.NEW_PARTIAL:This should change anything.#}# ok what.": assertAppliedStringContext('Testing ok what.'), "Testing #{#def.ANOTHER_PARTIAL='yet another partial.'}# ok what.": assertAppliedStringContext('Testing yet another partial. ok what.'), "Testing some string here. #{#def.PARTIAL}# #{#def.NEW_PARTIAL}#": assertAppliedStringContext('Testing some string here. This is a partial. This is a new partial.') }, "run-time": { "Testing some string here#{?DEBUG}# ok what#{?}# is it.": assertAppliedStringContext('Testing some string here is it.'), "Testing some string here#{?argv.RELEASE}# ok what#{?}# is it.": assertAppliedStringContext('Testing some string here ok what is it.'), "Testing some string here. #{=PARTIAL}# #{=NEW_PARTIAL}# #{=ANOTHER_PARTIAL}#": assertAppliedStringContext('Testing some string here. This is a partial. This is a new partial. yet another partial.'), "Testing some string here #{?argv.RELEASE}##{=ANOTHER_PARTIAL}##{?}# is it.": assertAppliedStringContext('Testing some string here yet another partial. is it.'), "Testing some string here #{?DEBUG}##{=NEW_PARTIAL}##{?}# is it.": assertAppliedStringContext('Testing some string here is it.'), } } } }).export(module);
"use strict"; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange') const { ExchangeError } = require ('./base/errors') // --------------------------------------------------------------------------- module.exports = class btcturk extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'btcturk', 'name': 'BTCTurk', 'countries': 'TR', // Turkey 'rateLimit': 1000, 'hasCORS': true, 'hasFetchTickers': true, 'hasFetchOHLCV': true, 'timeframes': { '1d': '1d', }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/27992709-18e15646-64a3-11e7-9fa2-b0950ec7712f.jpg', 'api': 'https://www.btcturk.com/api', 'www': 'https://www.btcturk.com', 'doc': 'https://github.com/BTCTrader/broker-api-docs', }, 'api': { 'public': { 'get': [ 'ohlcdata', // ?last=COUNT 'orderbook', 'ticker', 'trades', // ?last=COUNT (max 50) ], }, 'private': { 'get': [ 'balance', 'openOrders', 'userTransactions', // ?offset=0&limit=25&sort=asc ], 'post': [ 'buy', 'cancelOrder', 'sell', ], }, }, 'markets': { 'BTC/TRY': { 'id': 'BTCTRY', 'symbol': 'BTC/TRY', 'base': 'BTC', 'quote': 'TRY', 'maker': 0.002 * 1.18, 'taker': 0.0035 * 1.18 }, 'ETH/TRY': { 'id': 'ETHTRY', 'symbol': 'ETH/TRY', 'base': 'ETH', 'quote': 'TRY', 'maker': 0.002 * 1.18, 'taker': 0.0035 * 1.18 }, 'ETH/BTC': { 'id': 'ETHBTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'maker': 0.002 * 1.18, 'taker': 0.0035 * 1.18 }, }, }); } async fetchBalance (params = {}) { let response = await this.privateGetBalance (); let result = { 'info': response }; let base = { 'free': response['bitcoin_available'], 'used': response['bitcoin_reserved'], 'total': response['bitcoin_balance'], }; let quote = { 'free': response['money_available'], 'used': response['money_reserved'], 'total': response['money_balance'], }; let symbol = this.symbols[0]; let market = this.markets[symbol]; result[market['base']] = base; result[market['quote']] = quote; return this.parseBalance (result); } async fetchOrderBook (symbol, params = {}) { let market = this.market (symbol); let orderbook = await this.publicGetOrderbook (this.extend ({ 'pairSymbol': market['id'], }, params)); let timestamp = parseInt (orderbook['timestamp'] * 1000); return this.parseOrderBook (orderbook, timestamp); } parseTicker (ticker, market = undefined) { let symbol = undefined; if (market) symbol = market['symbol']; let timestamp = parseInt (ticker['timestamp']) * 1000; return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'high': parseFloat (ticker['high']), 'low': parseFloat (ticker['low']), 'bid': parseFloat (ticker['bid']), 'ask': parseFloat (ticker['ask']), 'vwap': undefined, 'open': parseFloat (ticker['open']), 'close': undefined, 'first': undefined, 'last': parseFloat (ticker['last']), 'change': undefined, 'percentage': undefined, 'average': parseFloat (ticker['average']), 'baseVolume': parseFloat (ticker['volume']), 'quoteVolume': undefined, 'info': ticker, }; } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); let tickers = await this.publicGetTicker (params); let result = {}; for (let i = 0; i < tickers.length; i++) { let ticker = tickers[i]; let symbol = ticker['pair']; let market = undefined; if (symbol in this.markets_by_id) { market = this.markets_by_id[symbol]; symbol = market['symbol']; } result[symbol] = this.parseTicker (ticker, market); } return result; } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); let tickers = await this.fetchTickers (); let result = undefined; if (symbol in tickers) result = tickers[symbol]; return result; } parseTrade (trade, market) { let timestamp = trade['date'] * 1000; return { 'id': trade['tid'], 'info': trade, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': market['symbol'], 'type': undefined, 'side': undefined, 'price': trade['price'], 'amount': trade['amount'], }; } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { let market = this.market (symbol); // let maxCount = 50; let response = await this.publicGetTrades (this.extend ({ 'pairSymbol': market['id'], }, params)); return this.parseTrades (response, market, since, limit); } parseOHLCV (ohlcv, market = undefined, timeframe = '1d', since = undefined, limit = undefined) { let timestamp = this.parse8601 (ohlcv['Time']); return [ timestamp, ohlcv['Open'], ohlcv['High'], ohlcv['Low'], ohlcv['Close'], ohlcv['Volume'], ]; } async fetchOHLCV (symbol, timeframe = '1d', since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let market = this.market (symbol); let request = {}; if (limit) request['last'] = limit; let response = await this.publicGetOhlcdata (this.extend (request, params)); return this.parseOHLCVs (response, market, timeframe, since, limit); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { let method = 'privatePost' + this.capitalize (side); let order = { 'Type': (side == 'buy') ? 'BuyBtc' : 'SelBtc', 'IsMarketOrder': (type == 'market') ? 1 : 0, }; if (type == 'market') { if (side == 'buy') order['Total'] = amount; else order['Amount'] = amount; } else { order['Price'] = price; order['Amount'] = amount; } let response = await this[method] (this.extend (order, params)); return { 'info': response, 'id': response['id'], }; } async cancelOrder (id, symbol = undefined, params = {}) { return await this.privatePostCancelOrder ({ 'id': id }); } nonce () { return this.milliseconds (); } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { if (this.id == 'btctrader') throw new ExchangeError (this.id + ' is an abstract base API for BTCExchange, BTCTurk'); let url = this.urls['api'] + '/' + path; if (api == 'public') { if (Object.keys (params).length) url += '?' + this.urlencode (params); } else { this.checkRequiredCredentials (); let nonce = this.nonce ().toString (); body = this.urlencode (params); let secret = this.base64ToBinary (this.secret); let auth = this.apiKey + nonce; headers = { 'X-PCK': this.apiKey, 'X-Stamp': nonce, 'X-Signature': this.stringToBase64(this.hmac (this.encode (auth), secret, 'sha256', 'binary')), 'Content-Type': 'application/x-www-form-urlencoded', }; } return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } }
/*! * DevExtreme (dx.messages.en.js) * Version: 20.1.8 * Build date: Fri Oct 09 2020 * * Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(root, factory) { if ("function" === typeof define && define.amd) { define(function(require) { factory(require("devextreme/localization")) }) } else { if ("object" === typeof module && module.exports) { factory(require("devextreme/localization")) } else { factory(DevExpress.localization) } } }(this, function(localization) { localization.loadMessages({ en: { Yes: "Yes", No: "No", Cancel: "Cancel", Clear: "Clear", Done: "Done", Loading: "Loading...", Select: "Select...", Search: "Search", Back: "Back", OK: "OK", "dxCollectionWidget-noDataText": "No data to display", "dxDropDownEditor-selectLabel": "Select", "validation-required": "Required", "validation-required-formatted": "{0} is required", "validation-numeric": "Value must be a number", "validation-numeric-formatted": "{0} must be a number", "validation-range": "Value is out of range", "validation-range-formatted": "{0} is out of range", "validation-stringLength": "The length of the value is not correct", "validation-stringLength-formatted": "The length of {0} is not correct", "validation-custom": "Value is invalid", "validation-custom-formatted": "{0} is invalid", "validation-async": "Value is invalid", "validation-async-formatted": "{0} is invalid", "validation-compare": "Values do not match", "validation-compare-formatted": "{0} does not match", "validation-pattern": "Value does not match pattern", "validation-pattern-formatted": "{0} does not match pattern", "validation-email": "Email is invalid", "validation-email-formatted": "{0} is invalid", "validation-mask": "Value is invalid", "dxLookup-searchPlaceholder": "Minimum character number: {0}", "dxList-pullingDownText": "Pull down to refresh...", "dxList-pulledDownText": "Release to refresh...", "dxList-refreshingText": "Refreshing...", "dxList-pageLoadingText": "Loading...", "dxList-nextButtonText": "More", "dxList-selectAll": "Select All", "dxListEditDecorator-delete": "Delete", "dxListEditDecorator-more": "More", "dxScrollView-pullingDownText": "Pull down to refresh...", "dxScrollView-pulledDownText": "Release to refresh...", "dxScrollView-refreshingText": "Refreshing...", "dxScrollView-reachBottomText": "Loading...", "dxDateBox-simulatedDataPickerTitleTime": "Select time", "dxDateBox-simulatedDataPickerTitleDate": "Select date", "dxDateBox-simulatedDataPickerTitleDateTime": "Select date and time", "dxDateBox-validation-datetime": "Value must be a date or time", "dxFileUploader-selectFile": "Select file", "dxFileUploader-dropFile": "or Drop file here", "dxFileUploader-bytes": "bytes", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "Upload", "dxFileUploader-uploaded": "Uploaded", "dxFileUploader-readyToUpload": "Ready to upload", "dxFileUploader-uploadFailedMessage": "Upload failed", "dxFileUploader-invalidFileExtension": "File type is not allowed", "dxFileUploader-invalidMaxFileSize": "File is too large", "dxFileUploader-invalidMinFileSize": "File is too small", "dxRangeSlider-ariaFrom": "From", "dxRangeSlider-ariaTill": "Till", "dxSwitch-switchedOnText": "ON", "dxSwitch-switchedOffText": "OFF", "dxForm-optionalMark": "optional", "dxForm-requiredMessage": "{0} is required", "dxNumberBox-invalidValueMessage": "Value must be a number", "dxNumberBox-noDataText": "No data", "dxDataGrid-columnChooserTitle": "Column Chooser", "dxDataGrid-columnChooserEmptyText": "Drag a column here to hide it", "dxDataGrid-groupContinuesMessage": "Continues on the next page", "dxDataGrid-groupContinuedMessage": "Continued from the previous page", "dxDataGrid-groupHeaderText": "Group by This Column", "dxDataGrid-ungroupHeaderText": "Ungroup", "dxDataGrid-ungroupAllText": "Ungroup All", "dxDataGrid-editingEditRow": "Edit", "dxDataGrid-editingSaveRowChanges": "Save", "dxDataGrid-editingCancelRowChanges": "Cancel", "dxDataGrid-editingDeleteRow": "Delete", "dxDataGrid-editingUndeleteRow": "Undelete", "dxDataGrid-editingConfirmDeleteMessage": "Are you sure you want to delete this record?", "dxDataGrid-validationCancelChanges": "Cancel changes", "dxDataGrid-groupPanelEmptyText": "Drag a column header here to group by that column", "dxDataGrid-noDataText": "No data", "dxDataGrid-searchPanelPlaceholder": "Search...", "dxDataGrid-filterRowShowAllText": "(All)", "dxDataGrid-filterRowResetOperationText": "Reset", "dxDataGrid-filterRowOperationEquals": "Equals", "dxDataGrid-filterRowOperationNotEquals": "Does not equal", "dxDataGrid-filterRowOperationLess": "Less than", "dxDataGrid-filterRowOperationLessOrEquals": "Less than or equal to", "dxDataGrid-filterRowOperationGreater": "Greater than", "dxDataGrid-filterRowOperationGreaterOrEquals": "Greater than or equal to", "dxDataGrid-filterRowOperationStartsWith": "Starts with", "dxDataGrid-filterRowOperationContains": "Contains", "dxDataGrid-filterRowOperationNotContains": "Does not contain", "dxDataGrid-filterRowOperationEndsWith": "Ends with", "dxDataGrid-filterRowOperationBetween": "Between", "dxDataGrid-filterRowOperationBetweenStartText": "Start", "dxDataGrid-filterRowOperationBetweenEndText": "End", "dxDataGrid-applyFilterText": "Apply filter", "dxDataGrid-trueText": "true", "dxDataGrid-falseText": "false", "dxDataGrid-sortingAscendingText": "Sort Ascending", "dxDataGrid-sortingDescendingText": "Sort Descending", "dxDataGrid-sortingClearText": "Clear Sorting", "dxDataGrid-editingSaveAllChanges": "Save changes", "dxDataGrid-editingCancelAllChanges": "Discard changes", "dxDataGrid-editingAddRow": "Add a row", "dxDataGrid-summaryMin": "Min: {0}", "dxDataGrid-summaryMinOtherColumn": "Min of {1} is {0}", "dxDataGrid-summaryMax": "Max: {0}", "dxDataGrid-summaryMaxOtherColumn": "Max of {1} is {0}", "dxDataGrid-summaryAvg": "Avg: {0}", "dxDataGrid-summaryAvgOtherColumn": "Avg of {1} is {0}", "dxDataGrid-summarySum": "Sum: {0}", "dxDataGrid-summarySumOtherColumn": "Sum of {1} is {0}", "dxDataGrid-summaryCount": "Count: {0}", "dxDataGrid-columnFixingFix": "Fix", "dxDataGrid-columnFixingUnfix": "Unfix", "dxDataGrid-columnFixingLeftPosition": "To the left", "dxDataGrid-columnFixingRightPosition": "To the right", "dxDataGrid-exportTo": "Export", "dxDataGrid-exportToExcel": "Export to Excel file", "dxDataGrid-exporting": "Exporting...", "dxDataGrid-excelFormat": "Excel file", "dxDataGrid-selectedRows": "Selected rows", "dxDataGrid-exportSelectedRows": "Export selected rows", "dxDataGrid-exportAll": "Export all data", "dxDataGrid-headerFilterEmptyValue": "(Blanks)", "dxDataGrid-headerFilterOK": "OK", "dxDataGrid-headerFilterCancel": "Cancel", "dxDataGrid-ariaColumn": "Column", "dxDataGrid-ariaValue": "Value", "dxDataGrid-ariaFilterCell": "Filter cell", "dxDataGrid-ariaCollapse": "Collapse", "dxDataGrid-ariaExpand": "Expand", "dxDataGrid-ariaDataGrid": "Data grid", "dxDataGrid-ariaSearchInGrid": "Search in data grid", "dxDataGrid-ariaSelectAll": "Select all", "dxDataGrid-ariaSelectRow": "Select row", "dxDataGrid-filterBuilderPopupTitle": "Filter Builder", "dxDataGrid-filterPanelCreateFilter": "Create Filter", "dxDataGrid-filterPanelClearFilter": "Clear", "dxDataGrid-filterPanelFilterEnabledHint": "Enable the filter", "dxTreeList-ariaTreeList": "Tree list", "dxTreeList-editingAddRowToNode": "Add", "dxPager-infoText": "Page {0} of {1} ({2} items)", "dxPager-pagesCountText": "of", "dxPivotGrid-grandTotal": "Grand Total", "dxPivotGrid-total": "{0} Total", "dxPivotGrid-fieldChooserTitle": "Field Chooser", "dxPivotGrid-showFieldChooser": "Show Field Chooser", "dxPivotGrid-expandAll": "Expand All", "dxPivotGrid-collapseAll": "Collapse All", "dxPivotGrid-sortColumnBySummary": 'Sort "{0}" by This Column', "dxPivotGrid-sortRowBySummary": 'Sort "{0}" by This Row', "dxPivotGrid-removeAllSorting": "Remove All Sorting", "dxPivotGrid-dataNotAvailable": "N/A", "dxPivotGrid-rowFields": "Row Fields", "dxPivotGrid-columnFields": "Column Fields", "dxPivotGrid-dataFields": "Data Fields", "dxPivotGrid-filterFields": "Filter Fields", "dxPivotGrid-allFields": "All Fields", "dxPivotGrid-columnFieldArea": "Drop Column Fields Here", "dxPivotGrid-dataFieldArea": "Drop Data Fields Here", "dxPivotGrid-rowFieldArea": "Drop Row Fields Here", "dxPivotGrid-filterFieldArea": "Drop Filter Fields Here", "dxScheduler-editorLabelTitle": "Subject", "dxScheduler-editorLabelStartDate": "Start Date", "dxScheduler-editorLabelEndDate": "End Date", "dxScheduler-editorLabelDescription": "Description", "dxScheduler-editorLabelRecurrence": "Repeat", "dxScheduler-openAppointment": "Open appointment", "dxScheduler-recurrenceNever": "Never", "dxScheduler-recurrenceMinutely": "Every minute", "dxScheduler-recurrenceHourly": "Hourly", "dxScheduler-recurrenceDaily": "Daily", "dxScheduler-recurrenceWeekly": "Weekly", "dxScheduler-recurrenceMonthly": "Monthly", "dxScheduler-recurrenceYearly": "Yearly", "dxScheduler-recurrenceRepeatEvery": "Repeat Every", "dxScheduler-recurrenceRepeatOn": "Repeat On", "dxScheduler-recurrenceEnd": "End repeat", "dxScheduler-recurrenceAfter": "After", "dxScheduler-recurrenceOn": "On", "dxScheduler-recurrenceRepeatMinutely": "minute(s)", "dxScheduler-recurrenceRepeatHourly": "hour(s)", "dxScheduler-recurrenceRepeatDaily": "day(s)", "dxScheduler-recurrenceRepeatWeekly": "week(s)", "dxScheduler-recurrenceRepeatMonthly": "month(s)", "dxScheduler-recurrenceRepeatYearly": "year(s)", "dxScheduler-switcherDay": "Day", "dxScheduler-switcherWeek": "Week", "dxScheduler-switcherWorkWeek": "Work Week", "dxScheduler-switcherMonth": "Month", "dxScheduler-switcherAgenda": "Agenda", "dxScheduler-switcherTimelineDay": "Timeline Day", "dxScheduler-switcherTimelineWeek": "Timeline Week", "dxScheduler-switcherTimelineWorkWeek": "Timeline Work Week", "dxScheduler-switcherTimelineMonth": "Timeline Month", "dxScheduler-recurrenceRepeatOnDate": "on date", "dxScheduler-recurrenceRepeatCount": "occurrence(s)", "dxScheduler-allDay": "All day", "dxScheduler-confirmRecurrenceEditMessage": "Do you want to edit only this appointment or the whole series?", "dxScheduler-confirmRecurrenceDeleteMessage": "Do you want to delete only this appointment or the whole series?", "dxScheduler-confirmRecurrenceEditSeries": "Edit series", "dxScheduler-confirmRecurrenceDeleteSeries": "Delete series", "dxScheduler-confirmRecurrenceEditOccurrence": "Edit appointment", "dxScheduler-confirmRecurrenceDeleteOccurrence": "Delete appointment", "dxScheduler-noTimezoneTitle": "No timezone", "dxScheduler-moreAppointments": "{0} more", "dxCalendar-todayButtonText": "Today", "dxCalendar-ariaWidgetName": "Calendar", "dxColorView-ariaRed": "Red", "dxColorView-ariaGreen": "Green", "dxColorView-ariaBlue": "Blue", "dxColorView-ariaAlpha": "Transparency", "dxColorView-ariaHex": "Color code", "dxTagBox-selected": "{0} selected", "dxTagBox-allSelected": "All selected ({0})", "dxTagBox-moreSelected": "{0} more", "vizExport-printingButtonText": "Print", "vizExport-titleMenuText": "Exporting/Printing", "vizExport-exportButtonText": "{0} file", "dxFilterBuilder-and": "And", "dxFilterBuilder-or": "Or", "dxFilterBuilder-notAnd": "Not And", "dxFilterBuilder-notOr": "Not Or", "dxFilterBuilder-addCondition": "Add Condition", "dxFilterBuilder-addGroup": "Add Group", "dxFilterBuilder-enterValueText": "<enter a value>", "dxFilterBuilder-filterOperationEquals": "Equals", "dxFilterBuilder-filterOperationNotEquals": "Does not equal", "dxFilterBuilder-filterOperationLess": "Is less than", "dxFilterBuilder-filterOperationLessOrEquals": "Is less than or equal to", "dxFilterBuilder-filterOperationGreater": "Is greater than", "dxFilterBuilder-filterOperationGreaterOrEquals": "Is greater than or equal to", "dxFilterBuilder-filterOperationStartsWith": "Starts with", "dxFilterBuilder-filterOperationContains": "Contains", "dxFilterBuilder-filterOperationNotContains": "Does not contain", "dxFilterBuilder-filterOperationEndsWith": "Ends with", "dxFilterBuilder-filterOperationIsBlank": "Is blank", "dxFilterBuilder-filterOperationIsNotBlank": "Is not blank", "dxFilterBuilder-filterOperationBetween": "Is between", "dxFilterBuilder-filterOperationAnyOf": "Is any of", "dxFilterBuilder-filterOperationNoneOf": "Is none of", "dxHtmlEditor-dialogColorCaption": "Change Font Color", "dxHtmlEditor-dialogBackgroundCaption": "Change Background Color", "dxHtmlEditor-dialogLinkCaption": "Add Link", "dxHtmlEditor-dialogLinkUrlField": "URL", "dxHtmlEditor-dialogLinkTextField": "Text", "dxHtmlEditor-dialogLinkTargetField": "Open link in new window", "dxHtmlEditor-dialogImageCaption": "Add Image", "dxHtmlEditor-dialogImageUrlField": "URL", "dxHtmlEditor-dialogImageAltField": "Alternate text", "dxHtmlEditor-dialogImageWidthField": "Width (px)", "dxHtmlEditor-dialogImageHeightField": "Height (px)", "dxHtmlEditor-heading": "Heading", "dxHtmlEditor-normalText": "Normal text", "dxFileManager-newDirectoryName": "Untitled directory", "dxFileManager-rootDirectoryName": "Files", "dxFileManager-errorNoAccess": "Access Denied. Operation could not be completed.", "dxFileManager-errorDirectoryExistsFormat": "Directory '{0}' already exists.", "dxFileManager-errorFileExistsFormat": "File '{0}' already exists.", "dxFileManager-errorFileNotFoundFormat": "File '{0}' not found.", "dxFileManager-errorDirectoryNotFoundFormat": "Directory '{0}' not found.", "dxFileManager-errorWrongFileExtension": "File extension is not allowed.", "dxFileManager-errorMaxFileSizeExceeded": "File size exceeds the maximum allowed size.", "dxFileManager-errorInvalidSymbols": "This name contains invalid characters.", "dxFileManager-errorDefault": "Unspecified error.", "dxFileManager-errorDirectoryOpenFailed": "The directory cannot be opened", "dxFileManager-commandCreate": "New directory", "dxFileManager-commandRename": "Rename", "dxFileManager-commandMove": "Move to", "dxFileManager-commandCopy": "Copy to", "dxFileManager-commandDelete": "Delete", "dxFileManager-commandDownload": "Download", "dxFileManager-commandUpload": "Upload files", "dxFileManager-commandRefresh": "Refresh", "dxFileManager-commandThumbnails": "Thumbnails View", "dxFileManager-commandDetails": "Details View", "dxFileManager-commandClearSelection": "Clear selection", "dxFileManager-commandShowNavPane": "Toggle navigation pane", "dxFileManager-dialogDirectoryChooserMoveTitle": "Move to", "dxFileManager-dialogDirectoryChooserMoveButtonText": "Move", "dxFileManager-dialogDirectoryChooserCopyTitle": "Copy to", "dxFileManager-dialogDirectoryChooserCopyButtonText": "Copy", "dxFileManager-dialogRenameItemTitle": "Rename", "dxFileManager-dialogRenameItemButtonText": "Save", "dxFileManager-dialogCreateDirectoryTitle": "New directory", "dxFileManager-dialogCreateDirectoryButtonText": "Create", "dxFileManager-dialogDeleteItemTitle": "Delete", "dxFileManager-dialogDeleteItemButtonText": "Delete", "dxFileManager-dialogDeleteItemSingleItemConfirmation": "Are you sure you want to delete {0}?", "dxFileManager-dialogDeleteItemMultipleItemsConfirmation": "Are you sure you want to delete {0} items?", "dxFileManager-dialogButtonCancel": "Cancel", "dxFileManager-editingCreateSingleItemProcessingMessage": "Creating a directory inside {0}", "dxFileManager-editingCreateSingleItemSuccessMessage": "Created a directory inside {0}", "dxFileManager-editingCreateSingleItemErrorMessage": "Directory was not created", "dxFileManager-editingCreateCommonErrorMessage": "Directory was not created", "dxFileManager-editingRenameSingleItemProcessingMessage": "Renaming an item inside {0}", "dxFileManager-editingRenameSingleItemSuccessMessage": "Renamed an item inside {0}", "dxFileManager-editingRenameSingleItemErrorMessage": "Item was not renamed", "dxFileManager-editingRenameCommonErrorMessage": "Item was not renamed", "dxFileManager-editingDeleteSingleItemProcessingMessage": "Deleting an item from {0}", "dxFileManager-editingDeleteMultipleItemsProcessingMessage": "Deleting {0} items from {1}", "dxFileManager-editingDeleteSingleItemSuccessMessage": "Deleted an item from {0}", "dxFileManager-editingDeleteMultipleItemsSuccessMessage": "Deleted {0} items from {1}", "dxFileManager-editingDeleteSingleItemErrorMessage": "Item was not deleted", "dxFileManager-editingDeleteMultipleItemsErrorMessage": "{0} items were not deleted", "dxFileManager-editingDeleteCommonErrorMessage": "Some items were not deleted", "dxFileManager-editingMoveSingleItemProcessingMessage": "Moving an item to {0}", "dxFileManager-editingMoveMultipleItemsProcessingMessage": "Moving {0} items to {1}", "dxFileManager-editingMoveSingleItemSuccessMessage": "Moved an item to {0}", "dxFileManager-editingMoveMultipleItemsSuccessMessage": "Moved {0} items to {1}", "dxFileManager-editingMoveSingleItemErrorMessage": "Item was not moved", "dxFileManager-editingMoveMultipleItemsErrorMessage": "{0} items were not moved", "dxFileManager-editingMoveCommonErrorMessage": "Some items were not moved", "dxFileManager-editingCopySingleItemProcessingMessage": "Copying an item to {0}", "dxFileManager-editingCopyMultipleItemsProcessingMessage": "Copying {0} items to {1}", "dxFileManager-editingCopySingleItemSuccessMessage": "Copied an item to {0}", "dxFileManager-editingCopyMultipleItemsSuccessMessage": "Copied {0} items to {1}", "dxFileManager-editingCopySingleItemErrorMessage": "Item was not copied", "dxFileManager-editingCopyMultipleItemsErrorMessage": "{0} items were not copied", "dxFileManager-editingCopyCommonErrorMessage": "Some items were not copied", "dxFileManager-editingUploadSingleItemProcessingMessage": "Uploading an item to {0}", "dxFileManager-editingUploadMultipleItemsProcessingMessage": "Uploading {0} items to {1}", "dxFileManager-editingUploadSingleItemSuccessMessage": "Uploaded an item to {0}", "dxFileManager-editingUploadMultipleItemsSuccessMessage": "Uploaded {0} items to {1}", "dxFileManager-editingUploadSingleItemErrorMessage": "Item was not uploaded", "dxFileManager-editingUploadMultipleItemsErrorMessage": "{0} items were not uploaded", "dxFileManager-editingUploadCanceledMessage": "Canceled", "dxFileManager-listDetailsColumnCaptionName": "Name", "dxFileManager-listDetailsColumnCaptionDateModified": "Date Modified", "dxFileManager-listDetailsColumnCaptionFileSize": "File Size", "dxFileManager-listThumbnailsTooltipTextSize": "Size", "dxFileManager-listThumbnailsTooltipTextDateModified": "Date Modified", "dxFileManager-notificationProgressPanelTitle": "Progress", "dxFileManager-notificationProgressPanelEmptyListText": "No operations", "dxFileManager-notificationProgressPanelOperationCanceled": "Canceled", "dxDiagram-categoryGeneral": "General", "dxDiagram-categoryFlowchart": "Flowchart", "dxDiagram-categoryOrgChart": "Org Chart", "dxDiagram-categoryContainers": "Containers", "dxDiagram-categoryCustom": "Custom", "dxDiagram-commandExportToSvg": "Export to SVG", "dxDiagram-commandExportToPng": "Export to PNG", "dxDiagram-commandExportToJpg": "Export to JPEG", "dxDiagram-commandUndo": "Undo", "dxDiagram-commandRedo": "Redo", "dxDiagram-commandFontName": "Font Name", "dxDiagram-commandFontSize": "Font Size", "dxDiagram-commandBold": "Bold", "dxDiagram-commandItalic": "Italic", "dxDiagram-commandUnderline": "Underline", "dxDiagram-commandTextColor": "Font Color", "dxDiagram-commandLineColor": "Line Color", "dxDiagram-commandLineWidth": "Line Width", "dxDiagram-commandLineStyle": "Line Style", "dxDiagram-commandLineStyleSolid": "Solid", "dxDiagram-commandLineStyleDotted": "Dotted", "dxDiagram-commandLineStyleDashed": "Dashed", "dxDiagram-commandFillColor": "Fill Color", "dxDiagram-commandAlignLeft": "Align Left", "dxDiagram-commandAlignCenter": "Align Center", "dxDiagram-commandAlignRight": "Align Right", "dxDiagram-commandConnectorLineType": "Connector Line Type", "dxDiagram-commandConnectorLineStraight": "Straight", "dxDiagram-commandConnectorLineOrthogonal": "Orthogonal", "dxDiagram-commandConnectorLineStart": "Connector Line Start", "dxDiagram-commandConnectorLineEnd": "Connector Line End", "dxDiagram-commandConnectorLineNone": "None", "dxDiagram-commandConnectorLineArrow": "Arrow", "dxDiagram-commandFullscreen": "Full Screen", "dxDiagram-commandUnits": "Units", "dxDiagram-commandPageSize": "Page Size", "dxDiagram-commandPageOrientation": "Page Orientation", "dxDiagram-commandPageOrientationLandscape": "Landscape", "dxDiagram-commandPageOrientationPortrait": "Portrait", "dxDiagram-commandPageColor": "Page Color", "dxDiagram-commandShowGrid": "Show Grid", "dxDiagram-commandSnapToGrid": "Snap to Grid", "dxDiagram-commandGridSize": "Grid Size", "dxDiagram-commandZoomLevel": "Zoom Level", "dxDiagram-commandAutoZoom": "Auto Zoom", "dxDiagram-commandFitToContent": "Fit to Content", "dxDiagram-commandFitToWidth": "Fit to Width", "dxDiagram-commandAutoZoomByContent": "Auto Zoom by Content", "dxDiagram-commandAutoZoomByWidth": "Auto Zoom by Width", "dxDiagram-commandSimpleView": "Simple View", "dxDiagram-commandCut": "Cut", "dxDiagram-commandCopy": "Copy", "dxDiagram-commandPaste": "Paste", "dxDiagram-commandSelectAll": "Select All", "dxDiagram-commandDelete": "Delete", "dxDiagram-commandBringToFront": "Bring to Front", "dxDiagram-commandSendToBack": "Send to Back", "dxDiagram-commandLock": "Lock", "dxDiagram-commandUnlock": "Unlock", "dxDiagram-commandInsertShapeImage": "Insert Image...", "dxDiagram-commandEditShapeImage": "Change Image...", "dxDiagram-commandDeleteShapeImage": "Delete Image", "dxDiagram-commandLayoutLeftToRight": "Left-to-right", "dxDiagram-commandLayoutRightToLeft": "Right-to-left", "dxDiagram-commandLayoutTopToBottom": "Top-to-bottom", "dxDiagram-commandLayoutBottomToTop": "Bottom-to-top", "dxDiagram-unitIn": "in", "dxDiagram-unitCm": "cm", "dxDiagram-unitPx": "px", "dxDiagram-dialogButtonOK": "OK", "dxDiagram-dialogButtonCancel": "Cancel", "dxDiagram-dialogInsertShapeImageTitle": "Insert Image", "dxDiagram-dialogEditShapeImageTitle": "Change Image", "dxDiagram-dialogEditShapeImageSelectButton": "Select image", "dxDiagram-dialogEditShapeImageLabelText": "or drop file here", "dxDiagram-uiExport": "Export", "dxDiagram-uiProperties": "Properties", "dxDiagram-uiSettings": "Settings", "dxDiagram-uiShowToolbox": "Show Toolbox", "dxDiagram-uiSearch": "Search", "dxDiagram-uiStyle": "Style", "dxDiagram-uiLayout": "Layout", "dxDiagram-uiLayoutTree": "Tree", "dxDiagram-uiLayoutLayered": "Layered", "dxDiagram-uiDiagram": "Diagram", "dxDiagram-uiText": "Text", "dxDiagram-uiObject": "Object", "dxDiagram-uiConnector": "Connector", "dxDiagram-uiPage": "Page", "dxDiagram-shapeText": "Text", "dxDiagram-shapeRectangle": "Rectangle", "dxDiagram-shapeEllipse": "Ellipse", "dxDiagram-shapeCross": "Cross", "dxDiagram-shapeTriangle": "Triangle", "dxDiagram-shapeDiamond": "Diamond", "dxDiagram-shapeHeart": "Heart", "dxDiagram-shapePentagon": "Pentagon", "dxDiagram-shapeHexagon": "Hexagon", "dxDiagram-shapeOctagon": "Octagon", "dxDiagram-shapeStar": "Star", "dxDiagram-shapeArrowLeft": "Left Arrow", "dxDiagram-shapeArrowUp": "Up Arrow", "dxDiagram-shapeArrowRight": "Right Arrow", "dxDiagram-shapeArrowDown": "Down Arrow", "dxDiagram-shapeArrowUpDown": "Up Down Arrow", "dxDiagram-shapeArrowLeftRight": "Left Right Arrow", "dxDiagram-shapeProcess": "Process", "dxDiagram-shapeDecision": "Decision", "dxDiagram-shapeTerminator": "Terminator", "dxDiagram-shapePredefinedProcess": "Predefined Process", "dxDiagram-shapeDocument": "Document", "dxDiagram-shapeMultipleDocuments": "Multiple Documents", "dxDiagram-shapeManualInput": "Manual Input", "dxDiagram-shapePreparation": "Preparation", "dxDiagram-shapeData": "Data", "dxDiagram-shapeDatabase": "Database", "dxDiagram-shapeHardDisk": "Hard Disk", "dxDiagram-shapeInternalStorage": "Internal Storage", "dxDiagram-shapePaperTape": "Paper Tape", "dxDiagram-shapeManualOperation": "Manual Operation", "dxDiagram-shapeDelay": "Delay", "dxDiagram-shapeStoredData": "Stored Data", "dxDiagram-shapeDisplay": "Display", "dxDiagram-shapeMerge": "Merge", "dxDiagram-shapeConnector": "Connector", "dxDiagram-shapeOr": "Or", "dxDiagram-shapeSummingJunction": "Summing Junction", "dxDiagram-shapeContainerDefaultText": "Container", "dxDiagram-shapeVerticalContainer": "Vertical Container", "dxDiagram-shapeHorizontalContainer": "Horizontal Container", "dxDiagram-shapeCardDefaultText": "Person's Name", "dxDiagram-shapeCardWithImageOnLeft": "Card with Image on the Left", "dxDiagram-shapeCardWithImageOnTop": "Card with Image on the Top", "dxDiagram-shapeCardWithImageOnRight": "Card with Image on the Right", "dxGantt-dialogTitle": "Title", "dxGantt-dialogStartTitle": "Start", "dxGantt-dialogEndTitle": "End", "dxGantt-dialogProgressTitle": "Progress", "dxGantt-dialogResourcesTitle": "Resources", "dxGantt-dialogResourceManagerTitle": "Resource Manager", "dxGantt-dialogTaskDetailsTitle": "Task Details", "dxGantt-dialogEditResourceListHint": "Edit Resource List", "dxGantt-dialogEditNoResources": "No resources", "dxGantt-dialogButtonAdd": "Add", "dxGantt-contextMenuNewTask": "New Task", "dxGantt-contextMenuNewSubtask": "New Subtask", "dxGantt-contextMenuDeleteTask": "Delete Task", "dxGantt-contextMenuDeleteDependency": "Delete Dependency", "dxGantt-dialogTaskDeleteConfirmation": "Deleting a task also deletes all its dependencies and subtasks. Are you sure you want to delete this task?", "dxGantt-dialogDependencyDeleteConfirmation": "Are you sure you want to delete the dependency from the task?", "dxGantt-dialogResourcesDeleteConfirmation": "Deleting a resource also deletes it from tasks to which this resource is assigned. Are you sure you want to delete these resources? Resource: {0}", "dxGantt-dialogConstraintCriticalViolationMessage": "The task you are attempting to move is linked to a second task by a dependency relation. This change would conflict with dependency rules. How would you like to proceed?", "dxGantt-dialogConstraintViolationMessage": "The task you are attempting to move is linked to a second task by a dependency relation. How would you like to proceed?", "dxGantt-dialogCancelOperationMessage": "Cancel the operation", "dxGantt-dialogDeleteDependencyMessage": "Delete the dependency", "dxGantt-dialogMoveTaskAndKeepDependencyMessage": "Move the task and keep the dependency", "dxGantt-undo": "Undo", "dxGantt-redo": "Redo", "dxGantt-expandAll": "Expand All", "dxGantt-collapseAll": "Collapse All", "dxGantt-addNewTask": "Add New Task", "dxGantt-deleteSelectedTask": "Delete Selected Task", "dxGantt-zoomIn": "Zoom In", "dxGantt-zoomOut": "Zoom Out", "dxGantt-fullScreen": "Full Screen" } }) });
import React, { Component, PropTypes } from 'react' import Todo from './todo' class TodoList extends Component { render() { const { todos } = this.props; return( <div> List of things todo: <ul> {todos.map(todo => <Todo {...todo} key={todo.id}/> )} </ul> </div> ) } } TodoList.propTypes = { todos: PropTypes.array } export default TodoList;
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /*! * Next JS * Copyright (c)2011 Xenophy.CO.,LTD All rights Reserved. * http://www.xenophy.com */ // {{{ NX.app.controller.Abstract.constructor module.exports = function(config) { config = config || {}; NX.apply(this, config); NX.apply(this, { actions: [] }); }; // }}} /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */
'use strict'; // default websocket configs // looks for Rails' <%= action_cable_meta_tag %> in this format: // <meta name="action-cable-url" content="ws://localhost:3000/cable"/> ngActionCable.factory('ActionCableConfig', function() { var defaultWsUri= 'wss://please.add.an.actioncable.meta.tag.invalid:12345/path/to/cable'; var _wsUri; var config= { autoStart: true, debug: false, protocols: [] }; Object.defineProperty(config, 'wsUri', { get: function () { _wsUri= _wsUri || actioncable_meta_tag_content() || defaultWsUri; return _wsUri; }, set: function(newWsUri) { _wsUri= newWsUri; return _wsUri; } }); return config; function actioncable_meta_tag_content() { var metaTags= document.getElementsByTagName('meta'); var metaTagContent= false; for (var index = 0; index < metaTags.length; index++) { if (metaTags[index].hasAttribute('name') && metaTags[index].hasAttribute('content')) { if (metaTags[index].getAttribute('name')=== 'action-cable-url' ){ metaTagContent= metaTags[index].getAttribute('content'); break; } } } return metaTagContent; } });
"use strict"; var gulp = require("gulp"), rimraf = require("rimraf"), concat = require("gulp-concat"), cssmin = require("gulp-cssmin"), htmlmin = require("gulp-htmlmin"), //uglify = require("gulp-uglify"), merge = require("merge-stream"), del = require("del"), order = require("gulp-order"), uglify = require("gulp-uglify"); var paths = { webroot: "./wwwroot/" }; paths.js = paths.webroot + "js/"; paths.libs = paths.webroot + "lib/"; paths.minJs = paths.webroot + "js/**/*.min.js"; paths.css = paths.webroot + "css/**/*.css"; paths.minCss = paths.webroot + "css/**/*.min.css"; paths.concatJsDest = paths.webroot + "js/site.min.js"; paths.concatCssDest = paths.webroot + "css/site.min.css"; gulp.task("clean:js", function (cb) { rimraf(paths.concatJsDest, cb); }); gulp.task("clean:css", function (cb) { rimraf(paths.concatCssDest, cb); }); gulp.task("clean", ["clean:js", "clean:css"]); gulp.task("min:js", function () { return gulp.src( [ paths.libs + "requirejs/require.js", paths.js + "hopscotch/**/*.js", paths.js + "blockly/**/*.js", paths.js + "**/*.js", "!" + paths.minJs], { base: "." }) .pipe(concat(paths.concatJsDest)) //.pipe(uglify()) .pipe(gulp.dest(".")); }); gulp.task("min:css", function () { return gulp.src([paths.css, "!" + paths.minCss]) .pipe(concat(paths.concatCssDest)) .pipe(cssmin()) .pipe(gulp.dest(".")); }); gulp.task("series:first", function () { console.log('first task! <-----'); }) gulp.task("series:second", ["series:first"], function () { console.log('second task! <-----'); }); gulp.task("min", ["min:js", "min:css"]);
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2754',"Tlece.Recruitment.Models.SelectionProcess Namespace","topic_000000000000094D.html"],['2793',"SelectionProcessIndexVm Class","topic_0000000000000969.html"]];
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['408',"Tlece.Recruitment.Controllers Namespace","topic_000000000000018A.html"],['537',"QuestionVideoCreateController Class","topic_00000000000001F9.html"]];
window.onload = function() { // Create your Phaser game and inject it into the gameContainer div. // We did it in a window.onload event, but you can do it anywhere (requireJS load, anonymous function, jQuery dom ready, - whatever floats your boat) var game = new Phaser.Game(800, 600, Phaser.AUTO, 'gameContainer'); // Add the States your game has. // You don't have to do this in the html, it could be done in your Boot state too, but for simplicity I'll keep it here. game.state.add('Boot', BasicGame.Boot); game.state.add('Preloader', BasicGame.Preloader); game.state.add('MainMenu', BasicGame.MainMenu); game.state.add('Game', BasicGame.Game); // Now start the Boot state. //game.state.start('Boot'); game.state.start("Game"); };
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('project-list', 'Integration | Component | project list', { integration: true }); test('it renders', function(assert) { assert.expect(1); this.render(hbs`{{project-list}}`); assert.equal(this.$('.project-list').length, 1, 'The component\'s element is rendered'); }); test('it renders an item for each project in the list', function(assert) { assert.expect(1); let mockProjects = []; for (let i = 0; i < 3; i++) { mockProjects.push({ id: i, title: `Project ${i}`, slug: `project_${i}` }); } this.set('projects', mockProjects); this.render(hbs`{{project-list projects=projects}}`); assert.equal(this.$('.project-item').length, 3, 'The correct number of project-items is rendered'); });
search_result['3295']=["topic_00000000000007D9_methods--.html","ApplicationDetailDto Methods",""];
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'blockquote', 'sr-latn', { toolbar: 'Block Quote' // MISSING } );
/*! Tiles.js | http://thinkpixellab.com/tilesjs | 2012-12-03 */ // single namespace export var Tiles = {}; (function($) { var Tile = Tiles.Tile = function(tileId, element) { this.id = tileId; // position and dimensions of tile inside the parent panel this.top = 0; this.left = 0; this.width = 0; this.height = 0; // cache the tile container element this.$el = $(element || document.createElement('div')); }; Tile.prototype.appendTo = function($parent, fadeIn, delay, duration) { this.$el .hide() .appendTo($parent); if (fadeIn) { this.$el.delay(delay).fadeIn(duration); } else { this.$el.show(); } }; Tile.prototype.remove = function(animate, duration) { if (animate) { this.$el.fadeOut({ complete: function() { $(this).remove(); } }); } else { this.$el.remove(); } }; // updates the tile layout with optional animation Tile.prototype.resize = function(cellRect, pixelRect, animate, duration, onComplete) { // store the list of needed changes var cssChanges = {}, changed = false; // update position and dimensions if (this.left !== pixelRect.x) { cssChanges.left = pixelRect.x; this.left = pixelRect.x; changed = true; } if (this.top !== pixelRect.y) { cssChanges.top = pixelRect.y; this.top = pixelRect.y; changed = true; } if (this.width !== pixelRect.width) { cssChanges.width = pixelRect.width; this.width = pixelRect.width; changed = true; } if (this.height !== pixelRect.height) { cssChanges.height = pixelRect.height; this.height = pixelRect.height; changed = true; } // Sometimes animation fails to set the css top and left correctly // in webkit. We'll validate upon completion of the animation and // set the properties again if they don't match the expected values. var tile = this, validateChangesAndComplete = function() { var el = tile.$el[0]; if (tile.left !== el.offsetLeft) { //console.log ('mismatch left:' + tile.left + ' actual:' + el.offsetLeft + ' id:' + tile.id); tile.$el.css('left', tile.left); } if (tile.top !== el.offsetTop) { //console.log ('mismatch top:' + tile.top + ' actual:' + el.offsetTop + ' id:' + tile.id); tile.$el.css('top', tile.top); } if (onComplete) { onComplete(); } }; // make css changes with animation when requested if (animate && changed) { this.$el.animate(cssChanges, { duration: duration, easing: 'swing', complete: validateChangesAndComplete }); } else { if (changed) { this.$el.css(cssChanges); } setTimeout(validateChangesAndComplete, duration); } }; })(jQuery); /* A grid template specifies the layout of variably sized tiles. A single cell tile should use the period character. Larger tiles may be created using any character that is unused by a adjacent tile. Whitespace is ignored when parsing the rows. Examples: var simpleTemplate = [ ' A A . B ', ' A A . B ', ' . C C . ', ] var complexTemplate = [ ' J J . . E E ', ' . A A . E E ', ' B A A F F . ', ' B . D D . H ', ' C C D D G H ', ' C C . . G . ', ]; */ (function($) { // remove whitespace and create 2d array var parseCells = function(rows) { var cells = [], numRows = rows.length, x, y, row, rowLength, cell; // parse each row for(y = 0; y < numRows; y++) { row = rows[y]; cells[y] = []; // parse the cells in a single row for (x = 0, rowLength = row.length; x < rowLength; x++) { cell = row[x]; if (cell !== ' ') { cells[y].push(cell); } } } // TODO: check to make sure the array isn't jagged return cells; }; function Rectangle(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } Rectangle.prototype.copy = function() { return new Rectangle(this.x, this.y, this.width, this.height); }; Tiles.Rectangle = Rectangle; // convert a 2d array of cell ids to a list of tile rects var parseRects = function(cells) { var rects = [], numRows = cells.length, numCols = numRows === 0 ? 0 : cells[0].length, cell, height, width, x, y, rectX, rectY; // make a copy of the cells that we can modify cells = cells.slice(); for (y = 0; y < numRows; y++) { cells[y] = cells[y].slice(); } // iterate through every cell and find rectangles for (y = 0; y < numRows; y++) { for(x = 0; x < numCols; x++) { cell = cells[y][x]; // skip cells that are null if (cell == null) { continue; } width = 1; height = 1; if (cell !== Tiles.Template.SINGLE_CELL) { // find the width by going right until cell id no longer matches while(width + x < numCols && cell === cells[y][x + width]) { width++; } // now find height by going down while (height + y < numRows && cell === cells[y + height][x]) { height++; } } // null out all cells for the rect for(rectY = 0; rectY < height; rectY++) { for(rectX = 0; rectX < width; rectX++) { cells[y + rectY][x + rectX] = null; } } // add the rect rects.push(new Rectangle(x, y, width, height)); } } return rects; }; Tiles.Template = function(rects, numCols, numRows) { this.rects = rects; this.numTiles = this.rects.length; this.numRows = numRows; this.numCols = numCols; }; Tiles.Template.prototype.copy = function() { var copyRects = [], len, i; for (i = 0, len = this.rects.length; i < len; i++) { copyRects.push(this.rects[i].copy()); } return new Tiles.Template(copyRects, this.numCols, this.numRows); }; // appends another template (assumes both are full rectangular grids) Tiles.Template.prototype.append = function(other) { if (this.numCols !== other.numCols) { throw 'Appended templates must have the same number of columns'; } // new rects begin after the last current row var startY = this.numRows, i, len, rect; // copy rects from the other template for (i = 0, len = other.rects.length; i < len; i++) { rect = other.rects[i]; this.rects.push( new Rectangle(rect.x, startY + rect.y, rect.width, rect.height)); } this.numRows += other.numRows; }; Tiles.Template.fromJSON = function(rows) { // convert rows to cells and then to rects var cells = parseCells(rows), rects = parseRects(cells); return new Tiles.Template( rects, cells.length > 0 ? cells[0].length : 0, cells.length); }; Tiles.Template.prototype.toJSON = function() { // for now we'll assume 26 chars is enough (we don't solve graph coloring) var LABELS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', NUM_LABELS = LABELS.length, labelIndex = 0, rows = [], i, len, rect, x, y, label; // fill in single tiles for each cell for (y = 0; y < this.numRows; y++) { rows[y] = []; for (x = 0; x < this.numCols; x++) { rows[y][x] = Tiles.Template.SINGLE_CELL; } } // now fill in bigger tiles for (i = 0, len = this.rects.length; i < len; i++) { rect = this.rects[i]; if (rect.width > 1 || rect.height > 1) { // mark the tile position with a label label = LABELS[labelIndex]; for(y = 0; y < rect.height; y++) { for(x = 0; x < rect.width; x++) { rows[rect.y + y][rect.x + x] = label; } } // advance the label index labelIndex = (labelIndex + 1) % NUM_LABELS; } } // turn the rows into strings for (y = 0; y < this.numRows; y++) { rows[y] = rows[y].join(''); } return rows; }; // period used to designate a single 1x1 cell tile Tiles.Template.SINGLE_CELL = '.'; })(jQuery); // template provider which returns simple templates with 1x1 tiles Tiles.UniformTemplates = { get: function(numCols, targetTiles) { var numRows = Math.ceil(targetTiles / numCols), rects = [], x, y; // create the rects for 1x1 tiles for (y = 0; y < numRows; y++) { for (x = 0; x < numCols; x++) { rects.push(new Tiles.Rectangle(x, y, 1, 1)); } } return new Tiles.Template(rects, numCols, numRows); } }; (function($) { var Grid = Tiles.Grid = function(element) { this.$el = $(element); // animation lasts 500 ms by default this.animationDuration = 500; // min width and height of a cell in the grid this.cellSizeMin = 150; // the default set of factories used when creating templates this.templateFactory = Tiles.UniformTemplates; // defines the page size for prioritization of positions and tiles this.priorityPageSize = Number.MAX_VALUE; // spacing between tiles this.cellPadding = 10; // actual width and height of a cell in the grid this.cellSize = 0; // number of tile cell columns this.numCols = 1; // cache the current template this.template = null; // flag that tracks whether a redraw is necessary this.isDirty = true; this.tiles = []; // keep track of added and removed tiles so we can update tiles // and the render the grid independently. this.tilesAdded = []; this.tilesRemoved = []; }; Grid.prototype.getContentWidth = function() { // by default, the entire container width is used when drawing tiles return this.$el.width(); }; // gets the number of columns during a resize Grid.prototype.resizeColumns = function() { var panelWidth = this.getContentWidth(); // ensure we have at least one column return Math.max(1, Math.floor((panelWidth + this.cellPadding) / (this.cellSizeMin + this.cellPadding))); }; // gets the cell size during a grid resize Grid.prototype.resizeCellSize = function() { var panelWidth = this.getContentWidth(); return Math.ceil((panelWidth + this.cellPadding) / this.numCols) - this.cellPadding; }; Grid.prototype.resize = function() { var newCols = this.resizeColumns(); if (this.numCols !== newCols && newCols > 0) { this.numCols = newCols; this.isDirty = true; } var newCellSize = this.resizeCellSize(); if (this.cellSize !== newCellSize && newCellSize > 0) { this.cellSize = newCellSize; this.isDirty = true; } }; // refresh all tiles based on the current content Grid.prototype.updateTiles = function(newTileIds) { // ensure we dont have duplicate ids newTileIds = uniques(newTileIds); var numTiles = newTileIds.length, newTiles = [], i, tile, tileId, index; // retain existing tiles and queue remaining tiles for removal for (i = this.tiles.length - 1; i >= 0; i--) { tile = this.tiles[i]; index = $.inArray(tile.id, newTileIds); if (index < 0) { this.tilesRemoved.push(tile); //console.log('Removing tile: ' + tile.id) } else { newTiles[index] = tile; } } // clear existing tiles this.tiles = []; // make sure we have tiles for new additions for (i = 0; i < numTiles; i++) { tile = newTiles[i]; if (!tile) { tileId = newTileIds[i]; // see if grid has a custom tile factory if (this.createTile) { tile = this.createTile(tileId); // skip the tile if it couldn't be created if (!tile) { //console.log('Tile element could not be created, id: ' + tileId); continue; } } else { tile = new Tiles.Tile(tileId); } // add tiles to queue (will be appended to DOM during redraw) this.tilesAdded.push(tile); //console.log('Adding tile: ' + tile.id); } this.tiles.push(tile); } }; // helper to return unique items function uniques(items) { var results = [], numItems = items ? items.length : 0, i, item; for (i = 0; i < numItems; i++) { item = items[i]; if ($.inArray(item, results) === -1) { results.push(item); } } return results; } // prepend new tiles Grid.prototype.insertTiles = function(newTileIds) { this.addTiles(newTileIds, true); }; // append new tiles Grid.prototype.addTiles = function(newTileIds, prepend) { if (!newTileIds || newTileIds.length === 0) { return; } var prevTileIds = [], prevTileCount = this.tiles.length, i; // get the existing tile ids for (i = 0; i < prevTileCount; i++) { prevTileIds.push(this.tiles[i].id); } var tileIds = prepend ? newTileIds.concat(prevTileIds) : prevTileIds.concat(newTileIds); this.updateTiles(tileIds); }; Grid.prototype.removeTiles = function(removeTileIds) { if (!removeTileIds || removeTileIds.length === 0) { return; } var updateTileIds = [], i, len, id; // get the set of ids which have not been removed for (i = 0, len = this.tiles.length; i < len; i++) { id = this.tiles[i].id; if ($.inArray(id, removeTileIds) === -1) { updateTileIds.push(id); } } this.updateTiles(updateTileIds); }; Grid.prototype.createTemplate = function(numCols, targetTiles) { // ensure that we have at least one column numCols = Math.max(1, numCols); var template = this.templateFactory.get(numCols, targetTiles); if (!template) { // fallback in case the default factory can't generate a good template template = Tiles.UniformTemplates.get(numCols, targetTiles); } return template; }; // ensures we have a good template for the specified numbef of tiles Grid.prototype.ensureTemplate = function(numTiles) { // verfiy that the current template is still valid if (!this.template || this.template.numCols !== this.numCols) { this.template = this.createTemplate(this.numCols, numTiles); this.isDirty = true; } else { // append another template if we don't have enough rects var missingRects = numTiles - this.template.rects.length; if (missingRects > 0) { this.template.append( this.createTemplate(this.numCols, missingRects)); this.isDirty = true; } } }; // helper that returns true if a tile was in the viewport or will be given // the new pixel rect coordinates and dimensions function wasOrWillBeVisible(viewRect, tile, newRect) { var viewMaxY = viewRect.y + viewRect.height, viewMaxX = viewRect.x + viewRect.width; // note: y axis is the more common exclusion, so check that first // was the tile visible? if (tile) { if (!((tile.top > viewMaxY) || (tile.top + tile.height < viewRect.y) || (tile.left > viewMaxX) || (tile.left + tile.width < viewRect.x))) { return true; } } if (newRect) { // will it be visible? if (!((newRect.y > viewMaxY) || (newRect.y + newRect.height < viewRect.y) || (newRect.x > viewMaxX) || (newRect.x + newRect.width < viewRect.x))) { return true; } } return false; } Grid.prototype.shouldRedraw = function() { // see if we need to calculate the cell size if (this.cellSize <= 0) { this.resize(); } // verify that we have a template this.ensureTemplate(this.tiles.length); // only redraw when necessary return (this.isDirty || this.tilesAdded.length > 0 || this.tilesRemoved.length > 0); }; // redraws the grid after tile collection changes Grid.prototype.redraw = function(animate, onComplete) { // see if we should redraw if (!this.shouldRedraw()) { if (onComplete) { onComplete(false); // tell callback that we did not redraw } return; } var numTiles = this.tiles.length, pageSize = this.priorityPageSize, duration = this.animationDuration, cellPlusPadding = this.cellSize + this.cellPadding, tileIndex = 0, appendDelay = 0, viewRect = new Tiles.Rectangle( this.$el.scrollLeft(), this.$el.scrollTop(), this.$el.width(), this.$el.height()), tile, added, pageRects, pageTiles, i, len, cellRect, pixelRect, animateTile, priorityRects, priorityTiles; // chunk tile layout by pages which are internally prioritized for (tileIndex = 0; tileIndex < numTiles; tileIndex += pageSize) { // get the next page of rects and tiles pageRects = this.template.rects.slice(tileIndex, tileIndex + pageSize); pageTiles = this.tiles.slice(tileIndex, tileIndex + pageSize); // create a copy that can be ordered priorityRects = pageRects.slice(0); priorityTiles = pageTiles.slice(0); // prioritize the page of rects and tiles if (this.prioritizePage) { this.prioritizePage(priorityRects, priorityTiles); } // place all the tiles for the current page for (i = 0, len = priorityTiles.length; i < len; i++) { tile = priorityTiles[i]; added = $.inArray(tile, this.tilesAdded) >= 0; cellRect = priorityRects[i]; pixelRect = new Tiles.Rectangle( cellRect.x * cellPlusPadding, cellRect.y * cellPlusPadding, (cellRect.width * cellPlusPadding) - this.cellPadding, (cellRect.height * cellPlusPadding) - this.cellPadding); tile.resize( cellRect, pixelRect, animate && !added && wasOrWillBeVisible(viewRect, tile, pixelRect), duration); if (added) { // decide whether to animate (fadeIn) and get the duration animateTile = animate && wasOrWillBeVisible(viewRect, null, pixelRect); if (animateTile && this.getAppendDelay) { appendDelay = this.getAppendDelay( cellRect, pageRects, priorityRects, tile, pageTiles, priorityTiles); } else { appendDelay = 0; } tile.appendTo(this.$el, animateTile, appendDelay, duration); } } } // fade out all removed tiles for (i = 0, len = this.tilesRemoved.length; i < len; i++) { tile = this.tilesRemoved[i]; animateTile = animate && wasOrWillBeVisible(viewRect, tile, null); tile.remove(animateTile, duration); } // clear pending queues for add / remove this.tilesRemoved = []; this.tilesAdded = []; this.isDirty = false; if (onComplete) { setTimeout(function() { onComplete(true); }, duration + 10); } }; })(jQuery);
/*global require global describe it expect*/ var q = require("q"); var mapper = require('../../lib/mapper'); var Module = require('../../lib/module'); var Selector = require('../../lib/selector'); var Logger = require('../../lib/logger'); var helpers = require('../_helpers'); var getChildren = helpers.getChildren; var fixtures = require('../_fixtures'); var fixture = fixtures.sampleObjectFixture; var scenarios; var SubmoduleSimple = { content: { firstname: mapper.property.required.get(getChildren, 'firstname', 0) } }; var SubmoduleEarlyBind = function (mapper) { return { content: { firstname: mapper.property.required.get(getChildren, 'firstname', 0) } }; }; var SubmoduleLateBind = function (mapper) { return { evaluate: function (mapper, node) { return mapper.evaluate(this, node).then (function (result) { result.nodeParameter = node; return result; }) }, content: { firstname: mapper.property.required.get(getChildren, 'firstname', 0), nodeParameter: undefined } }; }; var SubmoduleLateBindWithError = function (mapper) { return { evaluate: function (mapper, node) { return mapper.evaluate(this, node).then (function (result) { result.nodeParameter = node; return result; }) }, content: { firstname: mapper.property.required.get(getChildren, 'x', 0), nodeParameter: undefined } }; }; var SubmoduleLateBindPromise = function (mapper) { return q({ transform: function (mapper, node) { return mapper.transform(this, node).then (function (result) { result.nodeParameter = node; return result; }) }, content: { firstname: mapper.property.required.get(getChildren, 'firstname', 0), nodeParameter: undefined } }); }; describe('the test node selector', function () { it('works', function (done) { getChildren(fixture(), ['person'], null, null, function(err, nodes) { expect(nodes.length).to.equal(4); expect(nodes[1].lastname).to.equal('astair'); done(); }); }); }); xdescribe('module submodules', function () { it('evaluates a simple encapsulated submodule', function (done) { var tmpFixture = fixture(); var testModule = { content: { person: mapper.property.required.get(getChildren, 'person', 0).module(SubmoduleSimple) } }; var logger = new Logger(); var module = new Module(testModule); var expectedInstance = { person: { firstname: 'john' } }; module.evaluate(mapper, fixture(), logger).then(function (instance) { expect(instance).not.to.be.null; expect(instance).to.compareTo(expectedInstance); expect(logger.getMessages().length).to.equal(0); }) .catch(function (err) { expect(err).to.be.undefined; }) .finally(function () { done(); }); }); it('evaluates an early bound encapsulated submodule', function (done) { var tmpFixture = fixture(); var testModule = { content: { person: mapper.property.required(true).get(getChildren, 'person', 0).module(new SubmoduleEarlyBind(mapper)) } }; var logger = new Logger(); var module = new Module(testModule); var expectedInstance = { person: { firstname: 'john' } }; module.evaluate(mapper, fixture(), logger).then(function (instance) { expect(instance).not.to.be.null; expect(instance).to.compareTo(expectedInstance); expect(logger.getMessages().length).to.equal(0); }) .catch(function (err) { expect(err).to.be.undefined; }) .finally(function () { done(); }); }); it('evaluates a late bound encapsulated submodule', function (done) { var tmpFixture = fixture(); var testModule = { content: { person: mapper.property.required(true).get(getChildren, 'person', 0).module(SubmoduleLateBind) } }; var logger = new Logger(); var module = new Module(testModule); var expectedInstance = { person: { firstname: 'john', nodeParameter: { firstname: 'john', lastname: 'smith' } } }; module.evaluate(mapper, fixture(), logger).then(function (instance) { expect(instance).not.to.be.null; expect(instance).to.compareTo(expectedInstance); expect(logger.getMessages().length).to.equal(0); }) .catch(function (err) { expect(err).to.be.undefined; }) .finally(function () { done(); }); }); it('evaluates a late bound encapsulated submodule with a selector error', function (done) { var tmpFixture = fixture(); var testModule = { content: { person: mapper.property.required(true).get(getChildren, 'person', 0).module(SubmoduleLateBindWithError) } }; var logger = new Logger(); var module = new Module(testModule); var expectedInstance = {}; var expectedLog = { severity: 'fail', context: {path: ['person', 'firstname', 'get(\'x\')']}, text: 'nothing found', data: { firstname: 'john', lastname: 'smith' } } module.evaluate(mapper, fixture(), logger).then(function (instance) { expect(instance).not.to.be.null; expect(instance).to.compareTo(expectedInstance); expect(logger.getMessages().length).to.equal(1); expect(logger.getMessages()[0]).to.compareTo(expectedLog); }) .catch(function (err) { expect(err).to.be.undefined; }) .finally(function () { done(); }); }); it('evaluates a late bound encapsulated submodule that returns a promise', function (done) { var tmpFixture = fixture(); var testModule = { person: mapper.property.required(true).get(getChildren, 'person', 0).module(SubmoduleLateBindPromise) }; var logger = new Logger(); var module = new Module({content: testModule}); var expectedInstance = { person: { firstname: 'john', nodeParameter: { firstname: 'john', lastname: 'smith' } } }; module.evaluate(mapper, fixture(), logger).then(function (instance) { expect(instance).not.to.be.null; expect(instance).to.compareTo(expectedInstance); expect(logger.getMessages().length).to.equal(0); }) .catch(function (err) { expect(err).to.be.undefined; }) .finally(function () { done(); }); }); });
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ /** * cc.Sprite invalid index on the cc.SpriteBatchNode * @constant * @type Number */ cc.SPRITE_INDEX_NOT_INITIALIZED = -1; /** * generate texture's cache for texture tint * @function * @param {HTMLImageElement} texture * @return {Array} */ cc.generateTextureCacheForColor = function (texture) { if (texture.hasOwnProperty('channelCache')) { return texture.channelCache; } var textureCache = [ document.createElement("canvas"), document.createElement("canvas"), document.createElement("canvas"), document.createElement("canvas") ]; function renderToCache() { var ref = cc.generateTextureCacheForColor; var w = texture.width; var h = texture.height; textureCache[0].width = w; textureCache[0].height = h; textureCache[1].width = w; textureCache[1].height = h; textureCache[2].width = w; textureCache[2].height = h; textureCache[3].width = w; textureCache[3].height = h; ref.canvas.width = w; ref.canvas.height = h; var ctx = ref.canvas.getContext("2d"); ctx.drawImage(texture, 0, 0); ref.tempCanvas.width = w; ref.tempCanvas.height = h; var pixels = ctx.getImageData(0, 0, w, h).data; for (var rgbI = 0; rgbI < 4; rgbI++) { var cacheCtx = textureCache[rgbI].getContext('2d'); cacheCtx.getImageData(0, 0, w, h).data; ref.tempCtx.drawImage(texture, 0, 0); var to = ref.tempCtx.getImageData(0, 0, w, h); var toData = to.data; for (var i = 0; i < pixels.length; i += 4) { toData[i ] = (rgbI === 0) ? pixels[i ] : 0; toData[i + 1] = (rgbI === 1) ? pixels[i + 1] : 0; toData[i + 2] = (rgbI === 2) ? pixels[i + 2] : 0; toData[i + 3] = pixels[i + 3]; } cacheCtx.putImageData(to, 0, 0); } texture.onload = null; } try { renderToCache(); } catch (e) { texture.onload = renderToCache; } texture.channelCache = textureCache; return textureCache; }; cc.generateTextureCacheForColor.canvas = document.createElement('canvas'); cc.generateTextureCacheForColor.tempCanvas = document.createElement('canvas'); cc.generateTextureCacheForColor.tempCtx = cc.generateTextureCacheForColor.tempCanvas.getContext('2d'); /** * generate tinted texture * source-in: Where source and destination overlaps and both are opaque, the source is displayed. * Everywhere else transparency is displayed. * @function * @param {HTMLImageElement} texture * @param {cc.Color3B|cc.Color4F} color * @param {cc.Rect} rect * @return {HTMLCanvasElement} */ cc.generateTintImage2 = function (texture, color, rect) { if (!rect) { rect = cc.rect(0, 0, texture.width, texture.height); rect = cc.RECT_PIXELS_TO_POINTS(rect); } var selColor; if (color instanceof cc.Color4F) { selColor = cc.c4b(color.r * 255, color.g * 255, color.b * 255, color.a * 255); } else { selColor = cc.c4b(color.r, color.g, color.b, 50);//color; } var buff = document.createElement("canvas"); var ctx = buff.getContext("2d"); if (buff.width != rect.width) buff.width = rect.width; if (buff.height != rect.height) buff.height = rect.height; ctx.save(); ctx.drawImage(texture, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height); ctx.globalCompositeOperation = "source-in"; ctx.globalAlpha = selColor.a / 255.0; ctx.fillStyle = "rgb(" + selColor.r + "," + selColor.g + "," + selColor.b + ")"; ctx.fillRect(0, 0, rect.width, rect.height); ctx.restore(); return buff; }; /** * generate tinted texture * lighter: The source and destination colors are added to each other, resulting in brighter colors, * moving towards color values of 1 (maximum brightness for that color). * @function * @param {HTMLImageElement} texture * @param {Array} tintedImgCache * @param {cc.Color3B|cc.Color4F} color * @param {cc.Rect} rect * @param {HTMLCanvasElement} [renderCanvas] * @return {HTMLCanvasElement} */ cc.generateTintImage = function (texture, tintedImgCache, color, rect, renderCanvas) { if (!rect) rect = cc.rect(0, 0, texture.width, texture.height); var selColor; if (color.a == null) { // Optimization for the particle system which mainly uses c4f colors selColor = cc.c4f(color.r / 255.0, color.g / 255.0, color.b / 255, 1); } else { selColor = color; } var w = Math.min(rect.width, tintedImgCache[0].width); var h = Math.min(rect.height, tintedImgCache[0].height); var buff = renderCanvas; var ctx; // Create a new buffer if required if (!buff) { buff = document.createElement("canvas"); buff.width = w; buff.height = h; ctx = buff.getContext("2d"); } else { ctx = buff.getContext("2d"); ctx.clearRect(0, 0, w, h); } ctx.save(); ctx.globalCompositeOperation = 'lighter'; // Make sure to keep the renderCanvas alpha in mind in case of overdraw var a = ctx.globalAlpha; if (selColor.r > 0) { ctx.globalAlpha = selColor.r * a; ctx.drawImage(tintedImgCache[0], rect.x, rect.y, w, h, 0, 0, w, h); } if (selColor.g > 0) { ctx.globalAlpha = selColor.g * a; ctx.drawImage(tintedImgCache[1], rect.x, rect.y, w, h, 0, 0, w, h); } if (selColor.b > 0) { ctx.globalAlpha = selColor.b * a; ctx.drawImage(tintedImgCache[2], rect.x, rect.y, w, h, 0, 0, w, h); } if ((selColor.r === 0) && (selColor.g === 0) && (selColor.b === 0)) { ctx.globalAlpha = a; ctx.drawImage(tintedImgCache[3], rect.x, rect.y, w, h, 0, 0, w, h); } ctx.restore(); return buff; }; cc.cutRotateImageToCanvas = function (texture, rect) { if (!texture) return null; if (!rect) return texture; var nCanvas = document.createElement("canvas"); nCanvas.width = rect.width; nCanvas.height = rect.height; var ctx = nCanvas.getContext("2d"); ctx.translate(nCanvas.width / 2, nCanvas.height / 2); ctx.rotate(-1.5707963267948966); ctx.drawImage(texture, rect.x, rect.y, rect.height, rect.width, -rect.height / 2, -rect.width / 2, rect.height, rect.width); return nCanvas; }; /** * a Values object for transform * @Class * @Construct * @param {cc.Point} pos position x and y * @param {cc.Point} scale scale x and y * @param {Number} rotation * @param {cc.Point} skew skew x and y * @param {cc.Point} ap anchor point in pixels * @param {Boolean} visible */ cc.TransformValues = function (pos, scale, rotation, skew, ap, visible) { this.pos = pos; // position x and y this.scale = scale; // scale x and y this.rotation = rotation; this.skew = skew; // skew x and y this.ap = ap; // anchor point in pixels this.visible = visible; }; cc.RENDER_IN_SUBPIXEL = function (A) { return (0 | A); }; if (cc.SPRITEBATCHNODE_RENDER_SUBPIXEL) { cc.RENDER_IN_SUBPIXEL = function (A) { return A; }; } /** * <p>cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) <br/> * * cc.Sprite can be created with an image, or with a sub-rectangle of an image. <br/> * * If the parent or any of its ancestors is a cc.SpriteBatchNode then the following features/limitations are valid <br/> * - Features when the parent is a cc.BatchNode: <br/> * - MUCH faster rendering, specially if the cc.SpriteBatchNode has many children. All the children will be drawn in a single batch. <br/> * * - Limitations <br/> * - Camera is not supported yet (eg: CCOrbitCamera action doesn't work) <br/> * - GridBase actions are not supported (eg: CCLens, CCRipple, CCTwirl) <br/> * - The Alias/Antialias property belongs to CCSpriteBatchNode, so you can't individually set the aliased property. <br/> * - The Blending function property belongs to CCSpriteBatchNode, so you can't individually set the blending function property. <br/> * - Parallax scroller is not supported, but can be simulated with a "proxy" sprite. <br/> * * If the parent is an standard cc.Node, then cc.Sprite behaves like any other cc.Node: <br/> * - It supports blending functions <br/> * - It supports aliasing / antialiasing <br/> * - But the rendering will be slower: 1 draw per children. <br/> * * The default anchorPoint in cc.Sprite is (0.5, 0.5). </p> * @class * @extends cc.NodeRGBA * * @example * var aSprite = new cc.Sprite(); * aSprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320)); */ cc.Sprite = cc.NodeRGBA.extend(/** @lends cc.Sprite# */{ RGBAProtocol:true, // // Data used when the sprite is rendered using a CCSpriteSheet // _textureAtlas:null, //cc.SpriteBatchNode texture atlas _atlasIndex:0, _batchNode:null, _dirty:false, //Whether the sprite needs to be updated _recursiveDirty:null, //Whether all of the sprite's children needs to be updated _hasChildren:null, //Whether the sprite contains children _shouldBeHidden:false, //should not be drawn because one of the ancestors is not visible _transformToBatch:null, // // Data used when the sprite is self-rendered // _blendFunc:null, //It's required for CCTextureProtocol inheritance _texture:null, //cc.Texture2D object that is used to render the sprite // // Shared data // // texture _rect:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D _rectRotated:false, //Whether the texture is rotated // Offset Position (used by Zwoptex) _offsetPosition:null, // absolute _unflippedOffsetPositionFromCenter:null, _opacityModifyRGB:false, // image is flipped _flippedX:false, //Whether the sprite is flipped horizontally or not. _flippedY:false, //Whether the sprite is flipped vertically or not. _textureLoaded:false, _loadedEventListeners: null, _newTextureWhenChangeColor: null, //hack property for LabelBMFont textureLoaded:function(){ return this._textureLoaded; }, addLoadedEventListener:function(callback, target){ this._loadedEventListeners.push({eventCallback:callback, eventTarget:target}); }, _callLoadedEventCallbacks:function(){ var locListeners = this._loadedEventListeners; for(var i = 0, len = locListeners.length; i < len; i++){ var selCallback = locListeners[i]; selCallback.eventCallback.call(selCallback.eventTarget, this); } locListeners.length = 0; }, /** * Whether or not the Sprite needs to be updated in the Atlas * @return {Boolean} true if the sprite needs to be updated in the Atlas, false otherwise. */ isDirty:function () { return this._dirty; }, /** * Makes the Sprite to be updated in the Atlas. * @param {Boolean} bDirty */ setDirty:function (bDirty) { this._dirty = bDirty; }, /** * Returns whether or not the texture rectangle is rotated. * @return {Boolean} */ isTextureRectRotated:function () { return this._rectRotated; }, /** * Returns the index used on the TextureAtlas. * @return {Number} */ getAtlasIndex:function () { return this._atlasIndex; }, /** * Set the index used on the TextureAtlas. * @warning Don't modify this value unless you know what you are doing * @param {Number} atlasIndex */ setAtlasIndex:function (atlasIndex) { this._atlasIndex = atlasIndex; }, /** * returns the rect of the cc.Sprite in points * @return {cc.Rect} */ getTextureRect:function () { return cc.rect(this._rect.x, this._rect.y, this._rect.width, this._rect.height); }, /** * Gets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode * @return {cc.TextureAtlas} */ getTextureAtlas:function () { return this._textureAtlas; }, /** * Sets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode * @param {cc.TextureAtlas} textureAtlas */ setTextureAtlas:function (textureAtlas) { this._textureAtlas = textureAtlas; }, /** * return the SpriteBatchNode of the cc.Sprite * @return {cc.SpriteBatchNode} */ getSpriteBatchNode:function () { return this._batchNode; }, /** * set the SpriteBatchNode of the cc.Sprite * @param {cc.SpriteBatchNode} spriteBatchNode */ setSpriteBatchNode:function (spriteBatchNode) { this._batchNode = spriteBatchNode; }, /** * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. * @return {cc.Point} */ getOffsetPosition:function () { return cc.p(this._offsetPosition.x, this._offsetPosition.y); }, /** * conforms to cc.TextureProtocol protocol * @return {cc.BlendFunc} */ getBlendFunc:function () { return this._blendFunc; }, /** * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite * @param {cc.SpriteFrame} spriteFrame A CCSpriteFrame object. It should includes a valid texture and a rect * @return {Boolean} true if the sprite is initialized properly, false otherwise. * @example * var spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame("grossini_dance_01.png"); * var sprite = new cc.Sprite(); * sprite.initWithSpriteFrame(spriteFrame); */ initWithSpriteFrame:function (spriteFrame) { cc.Assert(spriteFrame != null, ""); if(!spriteFrame.textureLoaded()){ //add event listener this._textureLoaded = false; spriteFrame.addLoadedEventListener(this._spriteFrameLoadedCallback, this); } var ret = this.initWithTexture(spriteFrame.getTexture(), spriteFrame.getRect()); this.setDisplayFrame(spriteFrame); return ret; }, _spriteFrameLoadedCallback:null, _spriteFrameLoadedCallbackForWebGL:function(spriteFrame){ this.setNodeDirty(); this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); this._callLoadedEventCallbacks(); }, _spriteFrameLoadedCallbackForCanvas:function(spriteFrame){ this.setNodeDirty(); this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); var curColor = this.getColor(); if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255) this._changeTextureColor(); this._callLoadedEventCallbacks(); }, /** * Initializes a sprite with a sprite frame name. <br/> * A cc.SpriteFrame will be fetched from the cc.SpriteFrameCache by name. <br/> * If the cc.SpriteFrame doesn't exist it will raise an exception. <br/> * @param {String} spriteFrameName A key string that can fected a volid cc.SpriteFrame from cc.SpriteFrameCache * @return {Boolean} true if the sprite is initialized properly, false otherwise. * @example * var sprite = new cc.Sprite(); * sprite.initWithSpriteFrameName("grossini_dance_01.png"); */ initWithSpriteFrameName:function (spriteFrameName) { cc.Assert(spriteFrameName != null, ""); var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName); return this.initWithSpriteFrame(frame); }, /** * tell the sprite to use batch node render. * @param {cc.SpriteBatchNode} batchNode */ useBatchNode:function (batchNode) { this._textureAtlas = batchNode.getTextureAtlas(); // weak ref this._batchNode = batchNode; }, /** * <p> * set the vertex rect.<br/> * It will be called internally by setTextureRect. <br/> * Useful if you want to create 2x images from SD images in Retina Display. <br/> * Do not call it manually. Use setTextureRect instead. <br/> * (override this method to generate "double scale" sprites) * </p> * @param rect */ setVertexRect:function (rect) { this._rect = rect; }, sortAllChildren:function () { if (this._reorderChildDirty) { var j, tempItem, locChildren = this._children, tempChild; for (var i = 1; i < locChildren.length; i++) { tempItem = locChildren[i]; j = i - 1; tempChild = locChildren[j]; //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder || ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) { locChildren[j + 1] = tempChild; j = j - 1; tempChild = locChildren[j]; } locChildren[j + 1] = tempItem; } if (this._batchNode) { this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren); } this._reorderChildDirty = false; } }, /** * Reorders a child according to a new z value. (override cc.Node ) * @param {cc.Node} child * @param {Number} zOrder * @override */ reorderChild:function (child, zOrder) { cc.Assert(child != null, "child is null"); cc.Assert(this._children.indexOf(child) > -1, "this child is not in children list"); if (zOrder === child.getZOrder()) return; if (this._batchNode && !this._reorderChildDirty) { this._setReorderChildDirtyRecursively(); this._batchNode.reorderBatch(true); } cc.Node.prototype.reorderChild.call(this, child, zOrder); }, /** * Removes a child from the sprite. (override cc.Node ) * @param child * @param cleanup whether or not cleanup all running actions * @override */ removeChild:function (child, cleanup) { if (this._batchNode) this._batchNode.removeSpriteFromAtlas(child); cc.Node.prototype.removeChild.call(this, child, cleanup); }, /** * Removes all children from the container (override cc.Node ) * @param cleanup whether or not cleanup all running actions * @override */ removeAllChildren:function (cleanup) { var locChildren = this._children, locBatchNode = this._batchNode; if (locBatchNode && locChildren != null) { for (var i = 0, len = locChildren.length; i < len; i++) locBatchNode.removeSpriteFromAtlas(locChildren[i]); } cc.Node.prototype.removeAllChildren.call(this, cleanup); this._hasChildren = false; }, // // cc.Node property overloads // /** * set Recursively is or isn't Dirty * used only when parent is cc.SpriteBatchNode * @param {Boolean} value */ setDirtyRecursively:function (value) { this._recursiveDirty = value; this.setDirty(value); // recursively set dirty var locChildren = this._children; if (locChildren != null) { for (var i = 0; i < locChildren.length; i++) { if (locChildren[i] instanceof cc.Sprite) locChildren[i].setDirtyRecursively(true); } } }, /** * HACK: optimization */ SET_DIRTY_RECURSIVELY:function () { if (this._batchNode && !this._recursiveDirty) { this._recursiveDirty = true; this._dirty = true; if (this._hasChildren) this.setDirtyRecursively(true); } }, /** * position setter (override cc.Node ) * @param {cc.Point} pos * @override */ setPosition:function (pos) { if (arguments.length >= 2) cc.Node.prototype.setPosition.call(this, pos, arguments[1]); else cc.Node.prototype.setPosition.call(this, pos); this.SET_DIRTY_RECURSIVELY(); }, /** * Rotation setter (override cc.Node ) * @param {Number} rotation * @override */ setRotation:function (rotation) { cc.Node.prototype.setRotation.call(this, rotation); this.SET_DIRTY_RECURSIVELY(); }, setRotationX:function (rotationX) { cc.Node.prototype.setRotationX.call(this, rotationX); this.SET_DIRTY_RECURSIVELY(); }, setRotationY:function (rotationY) { cc.Node.prototype.setRotationY.call(this, rotationY); this.SET_DIRTY_RECURSIVELY(); }, /** * SkewX setter (override cc.Node ) * @param {Number} sx SkewX value * @override */ setSkewX:function (sx) { cc.Node.prototype.setSkewX.call(this, sx); this.SET_DIRTY_RECURSIVELY(); }, /** * SkewY setter (override cc.Node ) * @param {Number} sy SkewY value * @override */ setSkewY:function (sy) { cc.Node.prototype.setSkewY.call(this, sy); this.SET_DIRTY_RECURSIVELY(); }, /** * ScaleX setter (override cc.Node ) * @param {Number} scaleX * @override */ setScaleX:function (scaleX) { cc.Node.prototype.setScaleX.call(this, scaleX); this.SET_DIRTY_RECURSIVELY(); }, /** * ScaleY setter (override cc.Node ) * @param {Number} scaleY * @override */ setScaleY:function (scaleY) { cc.Node.prototype.setScaleY.call(this, scaleY); this.SET_DIRTY_RECURSIVELY(); }, /** * <p>The scale factor of the node. 1.0 is the default scale factor. <br/> * It modifies the X and Y scale at the same time. (override cc.Node ) <p/> * @param {Number} scale * @param {Number|null} [scaleY=] * @override */ setScale:function (scale, scaleY) { cc.Node.prototype.setScale.call(this, scale, scaleY); this.SET_DIRTY_RECURSIVELY(); }, /** * VertexZ setter (override cc.Node ) * @param {Number} vertexZ * @override */ setVertexZ:function (vertexZ) { cc.Node.prototype.setVertexZ.call(this, vertexZ); this.SET_DIRTY_RECURSIVELY(); }, /** * AnchorPoint setter (override cc.Node ) * @param {cc.Point} anchor * @override */ setAnchorPoint:function (anchor) { cc.Node.prototype.setAnchorPoint.call(this, anchor); this.SET_DIRTY_RECURSIVELY(); }, /** * visible setter (override cc.Node ) * @param {Boolean} visible * @override */ setVisible:function (visible) { cc.Node.prototype.setVisible.call(this, visible); this.SET_DIRTY_RECURSIVELY(); }, /** * IsRelativeAnchorPoint setter (override cc.Node ) * @param {Boolean} relative * @override */ ignoreAnchorPointForPosition:function (relative) { cc.Assert(!this._batchNode, "ignoreAnchorPointForPosition is invalid in cc.Sprite"); cc.Node.prototype.ignoreAnchorPointForPosition.call(this, relative); }, /** * Sets whether the sprite should be flipped horizontally or not. * @param {Boolean} flippedX true if the sprite should be flipped horizontally, false otherwise. */ setFlippedX:function (flippedX) { if (this._flippedX != flippedX) { this._flippedX = flippedX; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); this.setNodeDirty(); } }, /** * Sets whether the sprite should be flipped vertically or not. * @param {Boolean} flippedY true if the sprite should be flipped vertically, false otherwise. */ setFlippedY:function (flippedY) { if (this._flippedY != flippedY) { this._flippedY = flippedY; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); this.setNodeDirty(); } }, /** * <p> * Returns the flag which indicates whether the sprite is flipped horizontally or not. <br/> * <br/> * It only flips the texture of the sprite, and not the texture of the sprite's children. <br/> * Also, flipping the texture doesn't alter the anchorPoint. <br/> * If you want to flip the anchorPoint too, and/or to flip the children too use: <br/> * sprite->setScaleX(sprite->getScaleX() * -1); <p/> * @return {Boolean} true if the sprite is flipped horizaontally, false otherwise. */ isFlippedX:function () { return this._flippedX; }, /** * <p> * Return the flag which indicates whether the sprite is flipped vertically or not. <br/> * <br/> * It only flips the texture of the sprite, and not the texture of the sprite's children. <br/> * Also, flipping the texture doesn't alter the anchorPoint. <br/> * If you want to flip the anchorPoint too, and/or to flip the children too use: <br/> * sprite->setScaleY(sprite->getScaleY() * -1); <p/> * @return {Boolean} true if the sprite is flipped vertically, flase otherwise. */ isFlippedY:function () { return this._flippedY; }, // // RGBA protocol // /** * opacity: conforms to CCRGBAProtocol protocol * @param {Boolean} modify */ setOpacityModifyRGB:null, _setOpacityModifyRGBForWebGL: function (modify) { if (this._opacityModifyRGB !== modify) { this._opacityModifyRGB = modify; this.updateColor(); } }, _setOpacityModifyRGBForCanvas: function (modify) { if (this._opacityModifyRGB !== modify) { this._opacityModifyRGB = modify; this.setNodeDirty(); } }, /** * return IsOpacityModifyRGB value * @return {Boolean} */ isOpacityModifyRGB:function () { return this._opacityModifyRGB; }, updateDisplayedOpacity: null, _updateDisplayedOpacityForWebGL:function (parentOpacity) { cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity); this.updateColor(); }, _updateDisplayedOpacityForCanvas:function (parentOpacity) { cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity); this._changeTextureColor(); this.setNodeDirty(); }, // Animation /** * changes the display frame with animation name and index.<br/> * The animation name will be get from the CCAnimationCache * @param animationName * @param frameIndex */ setDisplayFrameWithAnimationName:function (animationName, frameIndex) { cc.Assert(animationName, "cc.Sprite#setDisplayFrameWithAnimationName. animationName must not be null"); var cache = cc.AnimationCache.getInstance().getAnimation(animationName); cc.Assert(cache, "cc.Sprite#setDisplayFrameWithAnimationName: Frame not found"); var animFrame = cache.getFrames()[frameIndex]; cc.Assert(animFrame, "cc.Sprite#setDisplayFrame. Invalid frame"); this.setDisplayFrame(animFrame.getSpriteFrame()); }, /** * Returns the batch node object if this sprite is rendered by cc.SpriteBatchNode * @returns {cc.SpriteBatchNode|null} The cc.SpriteBatchNode object if this sprite is rendered by cc.SpriteBatchNode, null if the sprite isn't used batch node. */ getBatchNode:function () { return this._batchNode; }, _setReorderChildDirtyRecursively:function () { //only set parents flag the first time if (!this._reorderChildDirty) { this._reorderChildDirty = true; var pNode = this._parent; while (pNode && pNode != this._batchNode) { pNode._setReorderChildDirtyRecursively(); pNode = pNode.getParent(); } } }, // CCTextureProtocol getTexture:function () { return this._texture; }, _quad:null, // vertex coords, texture coords and color info _quadWebBuffer:null, _quadDirty:false, _colorized:false, _isLighterMode:false, _originalTexture:null, /** * Constructor * @param {String|cc.SpriteFrame|cc.SpriteBatchNode|HTMLImageElement|cc.Texture2D} fileName sprite construct parameter */ ctor: null, _ctorForWebGL: function (fileName) { cc.NodeRGBA.prototype.ctor.call(this); this._shouldBeHidden = false; this._offsetPosition = cc.p(0, 0); this._unflippedOffsetPositionFromCenter = cc.p(0, 0); this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; this._quad = new cc.V3F_C4B_T2F_Quad(); this._quadWebBuffer = cc.renderContext.createBuffer(); this._quadDirty = true; this._textureLoaded = true; this._loadedEventListeners = []; if (fileName) { if (typeof(fileName) === "string") { var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName); this.initWithSpriteFrame(frame); } else if (typeof(fileName) === "object") { if (fileName instanceof cc.SpriteFrame) { this.initWithSpriteFrame(fileName); } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) { var texture2d = new cc.Texture2D(); texture2d.initWithElement(fileName); texture2d.handleLoadedTexture(); this.initWithTexture(texture2d); } else if (fileName instanceof cc.Texture2D) { this.initWithTexture(fileName); } } } }, _ctorForCanvas: function (fileName) { cc.NodeRGBA.prototype.ctor.call(this); this._shouldBeHidden = false; this._offsetPosition = cc.p(0, 0); this._unflippedOffsetPositionFromCenter = cc.p(0, 0); this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; this._newTextureWhenChangeColor = false; this._textureLoaded = true; this._loadedEventListeners = []; if (fileName) { if (typeof(fileName) === "string") { var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName); this.initWithSpriteFrame(frame); } else if (typeof(fileName) === "object") { if (fileName instanceof cc.SpriteFrame) { this.initWithSpriteFrame(fileName); } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) { var texture2d = new cc.Texture2D(); texture2d.initWithElement(fileName); texture2d.handleLoadedTexture(); this.initWithTexture(texture2d); } else if (fileName instanceof cc.Texture2D) { this.initWithTexture(fileName); } } } }, /** * Returns the quad (tex coords, vertex coords and color) information. * @return {cc.V3F_C4B_T2F_Quad} */ getQuad:function () { return this._quad; }, /** * conforms to cc.TextureProtocol protocol * @param {Number|cc.BlendFunc} src * @param {Number} dst */ setBlendFunc: null, _setBlendFuncForWebGL: function (src, dst) { if (arguments.length == 1) this._blendFunc = src; else this._blendFunc = {src: src, dst: dst}; }, _setBlendFuncForCanvas: function (src, dst) { if (arguments.length == 1) this._blendFunc = src; else this._blendFunc = {src: src, dst: dst}; this._isLighterMode = (this._blendFunc && (( this._blendFunc.src == gl.SRC_ALPHA && this._blendFunc.dst == gl.ONE) || (this._blendFunc.src == gl.ONE && this._blendFunc.dst == gl.ONE))); }, /** * Initializes an empty sprite with nothing init. * @return {Boolean} */ init:null, _initForWebGL: function () { if (arguments.length > 0) return this.initWithFile(arguments[0], arguments[1]); cc.NodeRGBA.prototype.init.call(this); this._dirty = this._recursiveDirty = false; this._opacityModifyRGB = true; this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; // update texture (calls _updateBlendFunc) this.setTexture(null); this._textureLoaded = true; this._flippedX = this._flippedY = false; // default transform anchor: center this.setAnchorPoint(cc.p(0.5, 0.5)); // zwoptex default values this._offsetPosition = cc.PointZero(); this._hasChildren = false; // Atlas: Color var tempColor = {r: 255, g: 255, b: 255, a: 255}; this._quad.bl.colors = tempColor; this._quad.br.colors = tempColor; this._quad.tl.colors = tempColor; this._quad.tr.colors = tempColor; this._quadDirty = true; // updated in "useSelfRender" // Atlas: TexCoords this.setTextureRect(cc.RectZero(), false, cc.SizeZero()); return true; }, _initForCanvas: function () { if (arguments.length > 0) return this.initWithFile(arguments[0], arguments[1]); cc.NodeRGBA.prototype.init.call(this); this._dirty = this._recursiveDirty = false; this._opacityModifyRGB = true; this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; // update texture (calls _updateBlendFunc) this.setTexture(null); this._textureLoaded = true; this._flippedX = this._flippedY = false; // default transform anchor: center this.setAnchorPoint(cc.p(0.5, 0.5)); // zwoptex default values this._offsetPosition = cc.PointZero(); this._hasChildren = false; // updated in "useSelfRender" // Atlas: TexCoords this.setTextureRect(cc.RectZero(), false, cc.SizeZero()); return true; }, /** * <p> * Initializes a sprite with an image filename. * * This method will find pszFilename from local file system, load its content to CCTexture2D, * then use CCTexture2D to create a sprite. * After initialization, the rect used will be the size of the image. The offset will be (0,0). * </p> * @param {String} filename The path to an image file in local file system * @param {cc.Rect} rect The rectangle assigned the content area from texture. * @return {Boolean} true if the sprite is initialized properly, false otherwise. * @example * var mySprite = new cc.Sprite(); * mySprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320)); */ initWithFile:function (filename, rect) { cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite"); var texture = cc.TextureCache.getInstance().textureForKey(filename); if (!texture) { texture = cc.TextureCache.getInstance().addImage(filename); return this.initWithTexture(texture, rect); } else { if (!rect) { var size = texture.getContentSize(); rect = cc.rect(0, 0, size.width, size.height); } return this.initWithTexture(texture, rect); } }, /** * Initializes a sprite with a texture and a rect in points, optionally rotated. <br/> * After initialization, the rect used will be the size of the texture, and the offset will be (0,0). * @param {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites. * @param {cc.Rect} rect Only the contents inside rect of this texture will be applied for this sprite. * @param {Boolean} [rotated] Whether or not the texture rectangle is rotated. * @return {Boolean} true if the sprite is initialized properly, false otherwise. * @example * var img =cc.TextureCache.getInstance().addImage("HelloHTML5World.png"); * var mySprite = new cc.Sprite(); * mySprite.initWithTexture(img,cc.rect(0,0,480,320)); */ initWithTexture: null, _initWithTextureForWebGL: function (texture, rect, rotated) { var argnum = arguments.length; if (argnum == 0) throw "Sprite.initWithTexture(): Argument must be non-nil "; rotated = rotated || false; if (!cc.NodeRGBA.prototype.init.call(this)) return false; this._batchNode = null; this._recursiveDirty = false; this._dirty = false; this._opacityModifyRGB = true; this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; this._flippedX = this._flippedY = false; // default transform anchor: center this.setAnchorPoint(cc.p(0.5, 0.5)); // zwoptex default values this._offsetPosition = cc.p(0, 0); this._hasChildren = false; // Atlas: Color var tmpColor = new cc.Color4B(255, 255, 255, 255); var locQuad = this._quad; locQuad.bl.colors = tmpColor; locQuad.br.colors = tmpColor; locQuad.tl.colors = tmpColor; locQuad.tr.colors = tmpColor; var locTextureLoaded = texture.isLoaded(); this._textureLoaded = locTextureLoaded; if (!locTextureLoaded) { this._rectRotated = rotated || false; this._rect = rect; texture.addLoadedEventListener(this._textureLoadedCallback, this); return true; } if (!rect) { rect = cc.rect(0, 0, 0, 0); rect.size = texture.getContentSize(); } this.setTexture(texture); this.setTextureRect(rect, rotated, rect.size); // by default use "Self Render". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" this.setBatchNode(null); this._quadDirty = true; return true; }, _initWithTextureForCanvas: function (texture, rect, rotated) { var argnum = arguments.length; if (argnum == 0) throw "Sprite.initWithTexture(): Argument must be non-nil "; rotated = rotated || false; if (!cc.NodeRGBA.prototype.init.call(this)) return false; this._batchNode = null; this._recursiveDirty = false; this._dirty = false; this._opacityModifyRGB = true; this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; this._flippedX = this._flippedY = false; // default transform anchor: center this.setAnchorPoint(cc.p(0.5, 0.5)); // zwoptex default values this._offsetPosition = cc.p(0, 0); this._hasChildren = false; var locTextureLoaded = texture.isLoaded(); this._textureLoaded = locTextureLoaded; if (!locTextureLoaded) { this._rectRotated = rotated || false; this._rect = rect; texture.addLoadedEventListener(this._textureLoadedCallback, this); return true; } if (!rect) { rect = cc.rect(0, 0, 0, 0); rect.size = texture.getContentSize(); } this._originalTexture = texture; this.setTexture(texture); this.setTextureRect(rect, rotated, rect.size); // by default use "Self Render". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" this.setBatchNode(null); return true; }, _textureLoadedCallback: null, _textureLoadedCallbackForWebGL: function (sender) { this._textureLoaded = true; var locRect = this._rect; if (!locRect) { locRect = cc.rect(0, 0, 0, 0); locRect.size = sender.getContentSize(); } else if (cc._rectEqualToZero(locRect)) { locRect.size = sender.getContentSize(); } this.setTexture(sender); this.setTextureRect(locRect, this._rectRotated, locRect.size); // by default use "Self Render". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" this.setBatchNode(null); this._quadDirty = true; this._callLoadedEventCallbacks(); }, _textureLoadedCallbackForCanvas: function (sender) { this._textureLoaded = true; var locRect = this._rect; if (!locRect) { locRect = cc.rect(0, 0, 0, 0); locRect.size = sender.getContentSize(); } else if (cc._rectEqualToZero(locRect)) { locRect.size = sender.getContentSize(); } this._originalTexture = sender; this.setTexture(sender); this.setTextureRect(locRect, this._rectRotated, locRect.size); // by default use "Self Render". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" this.setBatchNode(null); this._callLoadedEventCallbacks(); }, /** * updates the texture rect of the CCSprite in points. * @param {cc.Rect} rect a rect of texture * @param {Boolean} rotated * @param {cc.Size} untrimmedSize */ setTextureRect:null, _setTextureRectForWebGL:function (rect, rotated, untrimmedSize) { this._rectRotated = rotated || false; untrimmedSize = untrimmedSize || rect.size; this.setContentSize(untrimmedSize); this.setVertexRect(rect); this._setTextureCoords(rect); var relativeOffset = this._unflippedOffsetPositionFromCenter; if (this._flippedX) relativeOffset.x = -relativeOffset.x; if (this._flippedY) relativeOffset.y = -relativeOffset.y; var locRect = this._rect; this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - locRect.width) / 2; this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - locRect.height) / 2; // rendering using batch node if (this._batchNode) { // update dirty_, don't update recursiveDirty_ //this.setDirty(true); this._dirty = true; } else { // self rendering // Atlas: Vertex var x1 = 0 + this._offsetPosition.x; var y1 = 0 + this._offsetPosition.y; var x2 = x1 + locRect.width; var y2 = y1 + locRect.height; // Don't update Z. var locQuad = this._quad; locQuad.bl.vertices = {x:x1, y:y1, z:0}; locQuad.br.vertices = {x:x2, y:y1, z:0}; locQuad.tl.vertices = {x:x1, y:y2, z:0}; locQuad.tr.vertices = {x:x2, y:y2, z:0}; this._quadDirty = true; } }, _setTextureRectForCanvas: function (rect, rotated, untrimmedSize) { this._rectRotated = rotated || false; untrimmedSize = untrimmedSize || rect.size; this.setContentSize(untrimmedSize); this.setVertexRect(rect); var relativeOffset = this._unflippedOffsetPositionFromCenter; if (this._flippedX) relativeOffset.x = -relativeOffset.x; if (this._flippedY) relativeOffset.y = -relativeOffset.y; this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - this._rect.width) / 2; this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - this._rect.height) / 2; // rendering using batch node if (this._batchNode) { // update dirty_, don't update recursiveDirty_ //this.setDirty(true); this._dirty = true; } }, // BatchNode methods /** * updates the quad according the the rotation, position, scale values. */ updateTransform: null, _updateTransformForWebGL: function () { //cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode"); // recaculate matrix only if it is dirty if (this.isDirty()) { var locQuad = this._quad, locParent = this._parent; // If it is not visible, or one of its ancestors is not visible, then do nothing: if (!this._visible || ( locParent && locParent != this._batchNode && locParent._shouldBeHidden)) { locQuad.br.vertices = {x: 0, y: 0, z: 0}; locQuad.tl.vertices = {x: 0, y: 0, z: 0}; locQuad.tr.vertices = {x: 0, y: 0, z: 0}; locQuad.bl.vertices = {x: 0, y: 0, z: 0}; this._shouldBeHidden = true; } else { this._shouldBeHidden = false; if (!locParent || locParent == this._batchNode) { this._transformToBatch = this.nodeToParentTransform(); } else { //cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite"); this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), locParent._transformToBatch); } // // calculate the Quad based on the Affine Matrix // var locTransformToBatch = this._transformToBatch; var size = this._rect.size; var x1 = this._offsetPosition.x; var y1 = this._offsetPosition.y; var x2 = x1 + size.width; var y2 = y1 + size.height; var x = locTransformToBatch.tx; var y = locTransformToBatch.ty; var cr = locTransformToBatch.a; var sr = locTransformToBatch.b; var cr2 = locTransformToBatch.d; var sr2 = -locTransformToBatch.c; var ax = x1 * cr - y1 * sr2 + x; var ay = x1 * sr + y1 * cr2 + y; var bx = x2 * cr - y1 * sr2 + x; var by = x2 * sr + y1 * cr2 + y; var cx = x2 * cr - y2 * sr2 + x; var cy = x2 * sr + y2 * cr2 + y; var dx = x1 * cr - y2 * sr2 + x; var dy = x1 * sr + y2 * cr2 + y; var locVertexZ = this._vertexZ; locQuad.bl.vertices = {x: cc.RENDER_IN_SUBPIXEL(ax), y: cc.RENDER_IN_SUBPIXEL(ay), z: locVertexZ}; locQuad.br.vertices = {x: cc.RENDER_IN_SUBPIXEL(bx), y: cc.RENDER_IN_SUBPIXEL(by), z: locVertexZ}; locQuad.tl.vertices = {x: cc.RENDER_IN_SUBPIXEL(dx), y: cc.RENDER_IN_SUBPIXEL(dy), z: locVertexZ}; locQuad.tr.vertices = {x: cc.RENDER_IN_SUBPIXEL(cx), y: cc.RENDER_IN_SUBPIXEL(cy), z: locVertexZ}; } this._textureAtlas.updateQuad(locQuad, this._atlasIndex); this._recursiveDirty = false; this.setDirty(false); } // recursively iterate over children if (this._hasChildren) this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform); if (cc.SPRITE_DEBUG_DRAW) { // draw bounding box var vertices = [ cc.p(this._quad.bl.vertices.x, this._quad.bl.vertices.y), cc.p(this._quad.br.vertices.x, this._quad.br.vertices.y), cc.p(this._quad.tr.vertices.x, this._quad.tr.vertices.y), cc.p(this._quad.tl.vertices.x, this._quad.tl.vertices.y) ]; cc.drawingUtil.drawPoly(vertices, 4, true); } }, _updateTransformForCanvas: function () { //cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode"); // recaculate matrix only if it is dirty if (this._dirty) { // If it is not visible, or one of its ancestors is not visible, then do nothing: var locParent = this._parent; if (!this._visible || ( locParent && locParent != this._batchNode && locParent._shouldBeHidden)) { this._shouldBeHidden = true; } else { this._shouldBeHidden = false; if (!locParent || locParent == this._batchNode) { this._transformToBatch = this.nodeToParentTransform(); } else { //cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite"); this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), locParent._transformToBatch); } } this._recursiveDirty = false; this._dirty = false; } // recursively iterate over children if (this._hasChildren) this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform); }, /** * Add child to sprite (override cc.Node ) * @param {cc.Sprite} child * @param {Number} zOrder child's zOrder * @param {String} tag child's tag * @override */ addChild: null, _addChildForWebGL:function (child, zOrder, tag) { cc.Assert(child != null, "Argument must be non-NULL"); if (zOrder == null) zOrder = child._zOrder; if (tag == null) tag = child._tag; if (this._batchNode) { cc.Assert((child instanceof cc.Sprite), "cc.Sprite only supports cc.Sprites as children when using cc.SpriteBatchNode"); cc.Assert(child.getTexture()._webTextureObj === this._textureAtlas.getTexture()._webTextureObj, ""); //put it in descendants array of batch node this._batchNode.appendChild(child); if (!this._reorderChildDirty) this._setReorderChildDirtyRecursively(); } //cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check cc.Node.prototype.addChild.call(this, child, zOrder, tag); this._hasChildren = true; }, _addChildForCanvas: function (child, zOrder, tag) { cc.Assert(child != null, "Argument must be non-NULL"); if (zOrder == null) zOrder = child._zOrder; if (tag == null) tag = child._tag; //cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check cc.Node.prototype.addChild.call(this, child, zOrder, tag); this._hasChildren = true; }, /** * Update sprite's color */ updateColor:function () { var locDisplayedColor = this._displayedColor, locDisplayedOpacity = this._displayedOpacity; var color4 = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: locDisplayedOpacity}; // special opacity for premultiplied textures if (this._opacityModifyRGB) { color4.r *= locDisplayedOpacity / 255.0; color4.g *= locDisplayedOpacity / 255.0; color4.b *= locDisplayedOpacity / 255.0; } var locQuad = this._quad; locQuad.bl.colors = color4; locQuad.br.colors = color4; locQuad.tl.colors = color4; locQuad.tr.colors = color4; // renders using Sprite Manager if (this._batchNode) { if (this._atlasIndex != cc.SPRITE_INDEX_NOT_INITIALIZED) { this._textureAtlas.updateQuad(locQuad, this._atlasIndex) } else { // no need to set it recursively // update dirty_, don't update recursiveDirty_ //this.setDirty(true); this._dirty = true; } } // self render // do nothing this._quadDirty = true; }, /** * opacity setter * @param {Number} opacity */ setOpacity:null, _setOpacityForWebGL: function (opacity) { cc.NodeRGBA.prototype.setOpacity.call(this, opacity); this.updateColor(); }, _setOpacityForCanvas: function (opacity) { cc.NodeRGBA.prototype.setOpacity.call(this, opacity); this.setNodeDirty(); }, /** * color setter * @param {cc.Color3B} color3 */ setColor: null, _setColorForWebGL: function (color3) { cc.NodeRGBA.prototype.setColor.call(this, color3); this.updateColor(); }, _setColorForCanvas: function (color3) { var curColor = this.getColor(); if ((curColor.r === color3.r) && (curColor.g === color3.g) && (curColor.b === color3.b)) return; cc.NodeRGBA.prototype.setColor.call(this, color3); this._changeTextureColor(); this.setNodeDirty(); }, updateDisplayedColor: null, _updateDisplayedColorForWebGL: function (parentColor) { cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor); this.updateColor(); }, _updateDisplayedColorForCanvas: function (parentColor) { cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor); this._changeTextureColor(); this.setNodeDirty(); }, // Frames /** * Sets a new display frame to the cc.Sprite. * @param {cc.SpriteFrame} newFrame */ setDisplayFrame: null, _setDisplayFrameForWebGL: function (newFrame) { this.setNodeDirty(); var frameOffset = newFrame.getOffset(); this._unflippedOffsetPositionFromCenter.x = frameOffset.x; this._unflippedOffsetPositionFromCenter.y = frameOffset.y; var pNewTexture = newFrame.getTexture(); var locTextureLoaded = newFrame.textureLoaded(); if (!locTextureLoaded) { this._textureLoaded = false; newFrame.addLoadedEventListener(function (sender) { this._textureLoaded = true; var locNewTexture = sender.getTexture(); if (locNewTexture != this._texture) this.setTexture(locNewTexture); this.setTextureRect(sender.getRect(), sender._rectRotated, sender.getOriginalSize()); this._callLoadedEventCallbacks(); }, this); } // update texture before updating texture rect if (pNewTexture != this._texture) this.setTexture(pNewTexture); // update rect this._rectRotated = newFrame.isRotated(); this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize()); }, _setDisplayFrameForCanvas: function (newFrame) { this.setNodeDirty(); var frameOffset = newFrame.getOffset(); this._unflippedOffsetPositionFromCenter.x = frameOffset.x; this._unflippedOffsetPositionFromCenter.y = frameOffset.y; // update rect this._rectRotated = newFrame.isRotated(); var pNewTexture = newFrame.getTexture(); var locTextureLoaded = newFrame.textureLoaded(); if (!locTextureLoaded) { this._textureLoaded = false; newFrame.addLoadedEventListener(function (sender) { this._textureLoaded = true; var locNewTexture = sender.getTexture(); if (locNewTexture != this._texture) this.setTexture(locNewTexture); this.setTextureRect(sender.getRect(), this._rectRotated, sender.getOriginalSize()); this._callLoadedEventCallbacks(); }, this); } // update texture before updating texture rect if (pNewTexture != this._texture) this.setTexture(pNewTexture); if (this._rectRotated) this._originalTexture = pNewTexture; this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize()); this._colorized = false; if (locTextureLoaded) { var curColor = this.getColor(); if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255) this._changeTextureColor(); } }, /** * Returns whether or not a cc.SpriteFrame is being displayed * @param {cc.SpriteFrame} frame * @return {Boolean} */ isFrameDisplayed: null, _isFrameDisplayedForWebGL: function (frame) { return (cc.rectEqualToRect(frame.getRect(), this._rect) && frame.getTexture().getName() == this._texture.getName() && cc.pointEqualToPoint(frame.getOffset(), this._unflippedOffsetPositionFromCenter)); }, _isFrameDisplayedForCanvas: function (frame) { if (frame.getTexture() != this._texture) return false; return cc.rectEqualToRect(frame.getRect(), this._rect); }, /** * Returns the current displayed frame. * @return {cc.SpriteFrame} */ displayFrame: function () { return cc.SpriteFrame.createWithTexture(this._texture, cc.RECT_POINTS_TO_PIXELS(this._rect), this._rectRotated, cc.POINT_POINTS_TO_PIXELS(this._unflippedOffsetPositionFromCenter), cc.SIZE_POINTS_TO_PIXELS(this._contentSize)); }, /** * Sets the batch node to sprite * @param {cc.SpriteBatchNode|null} spriteBatchNode * @example * var batch = cc.SpriteBatchNode.create("Images/grossini_dance_atlas.png", 15); * var sprite = cc.Sprite.createWithTexture(batch.getTexture(), cc.rect(0, 0, 57, 57)); * batch.addChild(sprite); * layer.addChild(batch); */ setBatchNode:null, _setBatchNodeForWebGL:function (spriteBatchNode) { this._batchNode = spriteBatchNode; // weak reference // self render if (!this._batchNode) { this._atlasIndex = cc.SPRITE_INDEX_NOT_INITIALIZED; this.setTextureAtlas(null); this._recursiveDirty = false; this.setDirty(false); var x1 = this._offsetPosition.x; var y1 = this._offsetPosition.y; var x2 = x1 + this._rect.width; var y2 = y1 + this._rect.height; var locQuad = this._quad; locQuad.bl.vertices = {x:x1, y:y1, z:0}; locQuad.br.vertices = {x:x2, y:y1, z:0}; locQuad.tl.vertices = {x:x1, y:y2, z:0}; locQuad.tr.vertices = {x:x2, y:y2, z:0}; this._quadDirty = true; } else { // using batch this._transformToBatch = cc.AffineTransformIdentity(); this.setTextureAtlas(this._batchNode.getTextureAtlas()); // weak ref } }, _setBatchNodeForCanvas:function (spriteBatchNode) { this._batchNode = spriteBatchNode; // weak reference // self render if (!this._batchNode) { this._atlasIndex = cc.SPRITE_INDEX_NOT_INITIALIZED; this.setTextureAtlas(null); this._recursiveDirty = false; this.setDirty(false); } else { // using batch this._transformToBatch = cc.AffineTransformIdentity(); this.setTextureAtlas(this._batchNode.getTextureAtlas()); // weak ref } }, // CCTextureProtocol /** * Texture of sprite setter * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture */ setTexture: null, _setTextureForWebGL: function (texture) { // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument"); // If batchnode, then texture id should be the same cc.Assert(!this._batchNode, "cc.Sprite: Batched sprites should use the same texture as the batchnode"); if (texture) this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); else this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_COLOR)); if (!this._batchNode && this._texture != texture) { this._texture = texture; this._updateBlendFunc(); } }, _setTextureForCanvas: function (texture) { // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument"); if (this._texture != texture) { if (texture && texture.getHtmlElementObj() instanceof HTMLImageElement) { this._originalTexture = texture; } this._texture = texture; } }, // Texture protocol _updateBlendFunc:function () { cc.Assert(!this._batchNode, "cc.Sprite: _updateBlendFunc doesn't work when the sprite is rendered using a cc.CCSpriteBatchNode"); // it's possible to have an untextured sprite if (!this._texture || !this._texture.hasPremultipliedAlpha()) { this._blendFunc.src = gl.SRC_ALPHA; this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA; this.setOpacityModifyRGB(false); } else { this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; this.setOpacityModifyRGB(true); } }, _changeTextureColor: function () { var locElement, locTexture = this._texture, locRect = this.getTextureRect(); if (locTexture && locRect.width > 0) { locElement = locTexture.getHtmlElementObj(); if (!locElement) return; var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj()); if (cacheTextureForColor) { this._colorized = true; //generate color texture cache if (locElement instanceof HTMLCanvasElement && !this._rectRotated && !this._newTextureWhenChangeColor) cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect, locElement); else { locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect); locTexture = new cc.Texture2D(); locTexture.initWithElement(locElement); locTexture.handleLoadedTexture(); this.setTexture(locTexture); } } } }, _setTextureCoords:function (rect) { rect = cc.RECT_POINTS_TO_PIXELS(rect); var tex = this._batchNode ? this._textureAtlas.getTexture() : this._texture; if (!tex) return; var atlasWidth = tex.getPixelsWide(); var atlasHeight = tex.getPixelsHigh(); var left, right, top, bottom, tempSwap, locQuad = this._quad; if (this._rectRotated) { if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); right = left + (rect.height * 2 - 2) / (2 * atlasWidth); top = (2 * rect.y + 1) / (2 * atlasHeight); bottom = top + (rect.width * 2 - 2) / (2 * atlasHeight); } else { left = rect.x / atlasWidth; right = (rect.x + rect.height) / atlasWidth; top = rect.y / atlasHeight; bottom = (rect.y + rect.width) / atlasHeight; }// CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL if (this._flippedX) { tempSwap = top; top = bottom; bottom = tempSwap; } if (this._flippedY) { tempSwap = left; left = right; right = tempSwap; } locQuad.bl.texCoords.u = left; locQuad.bl.texCoords.v = top; locQuad.br.texCoords.u = left; locQuad.br.texCoords.v = bottom; locQuad.tl.texCoords.u = right; locQuad.tl.texCoords.v = top; locQuad.tr.texCoords.u = right; locQuad.tr.texCoords.v = bottom; } else { if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); right = left + (rect.width * 2 - 2) / (2 * atlasWidth); top = (2 * rect.y + 1) / (2 * atlasHeight); bottom = top + (rect.height * 2 - 2) / (2 * atlasHeight); } else { left = rect.x / atlasWidth; right = (rect.x + rect.width) / atlasWidth; top = rect.y / atlasHeight; bottom = (rect.y + rect.height) / atlasHeight; } // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL if (this._flippedX) { tempSwap = left; left = right; right = tempSwap; } if (this._flippedY) { tempSwap = top; top = bottom; bottom = tempSwap; } locQuad.bl.texCoords.u = left; locQuad.bl.texCoords.v = bottom; locQuad.br.texCoords.u = right; locQuad.br.texCoords.v = bottom; locQuad.tl.texCoords.u = left; locQuad.tl.texCoords.v = top; locQuad.tr.texCoords.u = right; locQuad.tr.texCoords.v = top; } this._quadDirty = true; }, /** * draw sprite to canvas */ draw: null, _drawForWebGL: function () { if (!this._textureLoaded) return; var gl = cc.renderContext, locTexture = this._texture; //cc.Assert(!this._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called"); if (locTexture) { if (locTexture._isLoaded) { this._shaderProgram.use(); this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst); //optimize performance for javascript cc.glBindTexture2DN(0, locTexture); // = cc.glBindTexture2D(locTexture); cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSCOLORTEX); gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); if (this._quadDirty) { gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.DYNAMIC_DRAW); this._quadDirty = false; } gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0); //cc.VERTEX_ATTRIB_POSITION gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 24, 12); //cc.VERTEX_ATTRIB_COLOR gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 24, 16); //cc.VERTEX_ATTRIB_TEX_COORDS gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } } else { this._shaderProgram.use(); this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst); cc.glBindTexture2D(null); cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR); gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); if (this._quadDirty) { cc.renderContext.bufferData(cc.renderContext.ARRAY_BUFFER, this._quad.arrayBuffer, cc.renderContext.STATIC_DRAW); this._quadDirty = false; } gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } cc.g_NumberOfDraws++; if (cc.SPRITE_DEBUG_DRAW === 0) return; if (cc.SPRITE_DEBUG_DRAW === 1) { // draw bounding box var locQuad = this._quad; var verticesG1 = [ cc.p(locQuad.tl.vertices.x, locQuad.tl.vertices.y), cc.p(locQuad.bl.vertices.x, locQuad.bl.vertices.y), cc.p(locQuad.br.vertices.x, locQuad.br.vertices.y), cc.p(locQuad.tr.vertices.x, locQuad.tr.vertices.y) ]; cc.drawingUtil.drawPoly(verticesG1, 4, true); } else if (cc.SPRITE_DEBUG_DRAW === 2) { // draw texture box var drawSizeG2 = this.getTextureRect().size; var offsetPixG2 = this.getOffsetPosition(); var verticesG2 = [cc.p(offsetPixG2.x, offsetPixG2.y), cc.p(offsetPixG2.x + drawSizeG2.width, offsetPixG2.y), cc.p(offsetPixG2.x + drawSizeG2.width, offsetPixG2.y + drawSizeG2.height), cc.p(offsetPixG2.x, offsetPixG2.y + drawSizeG2.height)]; cc.drawingUtil.drawPoly(verticesG2, 4, true); } // CC_SPRITE_DEBUG_DRAW }, _drawForCanvas: function (ctx) { if (!this._textureLoaded) return; var context = ctx || cc.renderContext; if (this._isLighterMode) context.globalCompositeOperation = 'lighter'; context.globalAlpha = this._displayedOpacity / 255; var locRect = this._rect, locContentSize = this._contentSize, locOffsetPosition = this._offsetPosition; var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height; if (this._flippedX || this._flippedY) { context.save(); if (this._flippedX) { flipXOffset = -locOffsetPosition.x - locRect.width; context.scale(-1, 1); } if (this._flippedY) { flipYOffset = locOffsetPosition.y; context.scale(1, -1); } } if (this._texture && locRect.width > 0) { var image = this._texture.getHtmlElementObj(); if (this._colorized) { context.drawImage(image, 0, 0, locRect.width, locRect.height, flipXOffset, flipYOffset, locRect.width, locRect.height); } else { context.drawImage(image, locRect.x, locRect.y, locRect.width, locRect.height, flipXOffset, flipYOffset, locRect.width, locRect.height); } } else if (locContentSize.width !== 0) { var curColor = this.getColor(); context.fillStyle = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)"; context.fillRect(flipXOffset, flipYOffset, locContentSize.width, locContentSize.height); } if (cc.SPRITE_DEBUG_DRAW === 1) { // draw bounding box context.strokeStyle = "rgba(0,255,0,1)"; flipYOffset = -flipYOffset; var vertices1 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset - locRect.height), cc.p(flipXOffset, flipYOffset - locRect.height)]; cc.drawingUtil.drawPoly(vertices1, 4, true); } else if (cc.SPRITE_DEBUG_DRAW === 2) { // draw texture box context.strokeStyle = "rgba(0,255,0,1)"; var drawSize = this._rect.size; flipYOffset = -flipYOffset; var vertices2 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + drawSize.width, flipYOffset), cc.p(flipXOffset + drawSize.width, flipYOffset - drawSize.height), cc.p(flipXOffset, flipYOffset - drawSize.height)]; cc.drawingUtil.drawPoly(vertices2, 4, true); } if (this._flippedX || this._flippedY) context.restore(); cc.g_NumberOfDraws++; } }); if(cc.Browser.supportWebGL){ cc.Sprite.prototype._spriteFrameLoadedCallback = cc.Sprite.prototype._spriteFrameLoadedCallbackForWebGL; cc.Sprite.prototype.setOpacityModifyRGB = cc.Sprite.prototype._setOpacityModifyRGBForWebGL; cc.Sprite.prototype.updateDisplayedOpacity = cc.Sprite.prototype._updateDisplayedOpacityForWebGL; cc.Sprite.prototype.ctor = cc.Sprite.prototype._ctorForWebGL; cc.Sprite.prototype.setBlendFunc = cc.Sprite.prototype._setBlendFuncForWebGL; cc.Sprite.prototype.init = cc.Sprite.prototype._initForWebGL; cc.Sprite.prototype.initWithTexture = cc.Sprite.prototype._initWithTextureForWebGL; cc.Sprite.prototype._textureLoadedCallback = cc.Sprite.prototype._textureLoadedCallbackForWebGL; cc.Sprite.prototype.setTextureRect = cc.Sprite.prototype._setTextureRectForWebGL; cc.Sprite.prototype.updateTransform = cc.Sprite.prototype._updateTransformForWebGL; cc.Sprite.prototype.addChild = cc.Sprite.prototype._addChildForWebGL; cc.Sprite.prototype.setOpacity = cc.Sprite.prototype._setOpacityForWebGL; cc.Sprite.prototype.setColor = cc.Sprite.prototype._setColorForWebGL; cc.Sprite.prototype.updateDisplayedColor = cc.Sprite.prototype._updateDisplayedColorForWebGL; cc.Sprite.prototype.setDisplayFrame = cc.Sprite.prototype._setDisplayFrameForWebGL; cc.Sprite.prototype.isFrameDisplayed = cc.Sprite.prototype._isFrameDisplayedForWebGL; cc.Sprite.prototype.setBatchNode = cc.Sprite.prototype._setBatchNodeForWebGL; cc.Sprite.prototype.setTexture = cc.Sprite.prototype._setTextureForWebGL; cc.Sprite.prototype.draw = cc.Sprite.prototype._drawForWebGL; }else{ cc.Sprite.prototype._spriteFrameLoadedCallback = cc.Sprite.prototype._spriteFrameLoadedCallbackForCanvas; cc.Sprite.prototype.setOpacityModifyRGB = cc.Sprite.prototype._setOpacityModifyRGBForCanvas; cc.Sprite.prototype.updateDisplayedOpacity = cc.Sprite.prototype._updateDisplayedOpacityForCanvas; cc.Sprite.prototype.ctor = cc.Sprite.prototype._ctorForCanvas; cc.Sprite.prototype.setBlendFunc = cc.Sprite.prototype._setBlendFuncForCanvas; cc.Sprite.prototype.init = cc.Sprite.prototype._initForCanvas; cc.Sprite.prototype.initWithTexture = cc.Sprite.prototype._initWithTextureForCanvas; cc.Sprite.prototype._textureLoadedCallback = cc.Sprite.prototype._textureLoadedCallbackForCanvas; cc.Sprite.prototype.setTextureRect = cc.Sprite.prototype._setTextureRectForCanvas; cc.Sprite.prototype.updateTransform = cc.Sprite.prototype._updateTransformForCanvas; cc.Sprite.prototype.addChild = cc.Sprite.prototype._addChildForCanvas; cc.Sprite.prototype.setOpacity = cc.Sprite.prototype._setOpacityForCanvas; cc.Sprite.prototype.setColor = cc.Sprite.prototype._setColorForCanvas; cc.Sprite.prototype.updateDisplayedColor = cc.Sprite.prototype._updateDisplayedColorForCanvas; cc.Sprite.prototype.setDisplayFrame = cc.Sprite.prototype._setDisplayFrameForCanvas; cc.Sprite.prototype.isFrameDisplayed = cc.Sprite.prototype._isFrameDisplayedForCanvas; cc.Sprite.prototype.setBatchNode = cc.Sprite.prototype._setBatchNodeForCanvas; cc.Sprite.prototype.setTexture = cc.Sprite.prototype._setTextureForCanvas; cc.Sprite.prototype.draw = cc.Sprite.prototype._drawForCanvas; } /** * <p> * Creates a sprite with an exsiting texture contained in a CCTexture2D object <br/> * After creation, the rect will be the size of the texture, and the offset will be (0,0). * </p> * @constructs * @param {cc.Texture2D} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites. * @param {cc.Rect} rect Only the contents inside the rect of this texture will be applied for this sprite. * @return {cc.Sprite} A valid sprite object * @example * //get an image * var img = cc.TextureCache.getInstance().addImage("HelloHTML5World.png"); * * //create a sprite with texture * var sprite1 = cc.Sprite.createWithTexture(img); * * //create a sprite with texture and rect * var sprite2 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320)); * */ cc.Sprite.createWithTexture = function (texture, rect) { var argnum = arguments.length; var sprite = new cc.Sprite(); switch (argnum) { case 1: /** Creates an sprite with a texture. The rect used will be the size of the texture. The offset will be (0,0). */ if (sprite && sprite.initWithTexture(texture)) return sprite; return null; break; case 2: /** Creates an sprite with a texture and a rect. The offset will be (0,0). */ if (sprite && sprite.initWithTexture(texture, rect)) return sprite; return null; break; default: throw "Sprite.createWithTexture(): Argument must be non-nil "; break; } }; /** * Create a sprite with filename and rect * @constructs * @param {String} fileName The string which indicates a path to image file, e.g., "scene1/monster.png". * @param {cc.Rect} rect Only the contents inside rect of pszFileName's texture will be applied for this sprite. * @return {cc.Sprite} A valid sprite object * @example * //create a sprite with filename * var sprite1 = cc.Sprite.create("HelloHTML5World.png"); * * //create a sprite with filename and rect * var sprite2 = cc.Sprite.create("HelloHTML5World.png",cc.rect(0,0,480,320)); */ cc.Sprite.create = function (fileName, rect) { var argnum = arguments.length; var sprite = new cc.Sprite(); if (argnum === 0) { if (sprite.init()) return sprite; } else { /** Creates an sprite with an image filename. If the rect equal undefined, the rect used will be the size of the image. The offset will be (0,0). */ if (sprite && sprite.init(fileName, rect)) return sprite; } return null; }; /** * <p> * Creates a sprite with a sprite frame. <br/> * <br/> * A CCSpriteFrame will be fetched from the CCSpriteFrameCache by pszSpriteFrameName param. <br/> * If the CCSpriteFrame doesn't exist it will raise an exception. * </p> * @param {String} spriteFrameName A sprite frame which involves a texture and a rect * @return {cc.Sprite} A valid sprite object * @example * * //create a sprite with a sprite frame * var sprite = cc.Sprite.createWithSpriteFrameName('grossini_dance_01.png'); */ cc.Sprite.createWithSpriteFrameName = function (spriteFrameName) { var spriteFrame = null; if (typeof(spriteFrameName) == 'string') { spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName); if (!spriteFrame) { cc.log("Invalid spriteFrameName: " + spriteFrameName); return null; } } else { cc.log("Invalid argument. Expecting string."); return null; } var sprite = new cc.Sprite(); if (sprite && sprite.initWithSpriteFrame(spriteFrame)) { return sprite; } return null; }; /** * <p> * Creates a sprite with a sprite frame. <br/> * <br/> * A CCSpriteFrame will be fetched from the CCSpriteFrameCache by pszSpriteFrameName param. <br/> * If the CCSpriteFrame doesn't exist it will raise an exception. * </p> * @param {cc.SpriteFrame} spriteFrame A sprite frame which involves a texture and a rect * @return {cc.Sprite} A valid sprite object * @example * //get a sprite frame * var spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame("grossini_dance_01.png"); * * //create a sprite with a sprite frame * var sprite = cc.Sprite.createWithSpriteFrame(spriteFrame); */ cc.Sprite.createWithSpriteFrame = function (spriteFrame) { var sprite = new cc.Sprite(); if (sprite && sprite.initWithSpriteFrame(spriteFrame)) { return sprite; } return null; };
'use strict'; /** * @file Configure the application. */ var restify = require('restify'); var fs = require("fs"); var config = require('./config'); var logError = require('./config/services.js').logError; var cleaner = require('./scripts/cleaner'); var lib = require('./lib/'); var handlers = lib.handlers; var middlewares = lib.middlewares; // Create storage file dir if(!fs.existsSync(config.storageDir)) { // Wrap in try / catch for race condition when clustering the app /* istanbul ignore next */ try { fs.mkdirSync(config.storageDir); } catch(e) {} } var server = restify.createServer(); server.use(middlewares.logger); server.use(restify.queryParser()); server.use(restify.bodyParser({uploadDir: config.storageDir})); server.use(restify.gzipResponse()); require("./config/routes.js")(server, handlers); // Log errors server.on('uncaughtException', function(req, res, route, err) { logError(err, req, { uncaughtRestifyException: true, statusCode: req.statusCode, }); if(!res._headerSent) { res.send(new restify.InternalServerError(err, err.message || 'unexpected error')); return true; } return false; }); module.exports = server; // 3 hours var delayBetweenCleans = (1000 * 60 * 60) * 3; setInterval(function cleanOldFiles() { var olderThan = new Date(new Date().getTime() - config.ttl); console.log("Cleaning olderThan" + olderThan); cleaner(olderThan, logError); }, delayBetweenCleans);
/* Highcharts JS v9.3.0 (2021-10-21) Old IE (v6, v7, v8) array polyfills for Highcharts v7+. (c) 2010-2021 Highsoft AS Author: Torstein Honsi License: www.highcharts.com/license */ 'use strict';(function(e){"object"===typeof module&&module.exports?(e["default"]=e,module.exports=e):"function"===typeof define&&define.amd?define("highcharts/modules/oldie-polyfills",["highcharts"],function(f){e(f);e.Highcharts=f;return e}):e("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(e){function f(c,b,a,d){c.hasOwnProperty(b)||(c[b]=d.apply(null,a))}e=e?e._modules:{};f(e,"Extensions/OldiePolyfills.js",[],function(){String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "")});Array.prototype.forEach||(Array.prototype.forEach=function(c,b){for(var a=0,d=this.length;a<d;a++)if("undefined"!==typeof this[a]&&!1===c.call(b,this[a],a,this))return a});Array.prototype.map||(Array.prototype.map=function(c){for(var b=[],a=0,d=this.length;a<d;a++)b[a]=c.call(this[a],this[a],a,this);return b});Array.prototype.indexOf||(Array.prototype.indexOf=function(c,b){var a=b||0;if(this)for(b=this.length;a<b;a++)if(this[a]===c)return a;return-1});Array.prototype.filter||(Array.prototype.filter= function(c){for(var b=[],a=0,d=this.length;a<d;a++)c(this[a],a)&&b.push(this[a]);return b});Array.prototype.some||(Array.prototype.some=function(c,b){for(var a=0,d=this.length;a<d;a++)if(!0===c.call(b,this[a],a,this))return!0;return!1});Array.prototype.reduce||(Array.prototype.reduce=function(c,b){for(var a=1<arguments.length?0:1,d=1<arguments.length?b:this[0],e=this.length;a<e;++a)d=c.call(this,d,this[a],a,this);return d});Function.prototype.bind||(Function.prototype.bind=function(){var c=this,b= arguments[0],a=Array.prototype.slice.call(arguments,1);if("function"!==typeof c)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");return function(){var d=a.concat(Array.prototype.slice.call(arguments));return c.apply(b,d)}});Object.getPrototypeOf||(Object.getPrototypeOf="object"===typeof"test".__proto__?function(c){return c.__proto__}:function(c){var b=c.constructor.prototype;return b===c?{}.constructor.prototype:b});Object.keys||(Object.keys=function(c){var b= [],a;for(a in c)Object.hasOwnProperty.call(c,a)&&b.push(a);return b});document.getElementsByClassName||(document.getElementsByClassName=function(c){var b=document,a,d=[];if(b.querySelectorAll)return b.querySelectorAll("."+c);if(b.evaluate)for(b=b.evaluate(".//*[contains(concat(' ', @class, ' '), ' "+c+" ')]",b,null,0,null);a=b.iterateNext();)d.push(a);else for(b=b.getElementsByTagName("*"),c=new RegExp("(^|\\s)"+c+"(\\s|$)"),a=0;a<b.length;a++)c.test(b[a].className)&&d.push(b[a]);return d})});f(e, "masters/modules/oldie-polyfills.src.js",[],function(){})}); //# sourceMappingURL=oldie-polyfills.js.map
/*! mailgun.js v1.1.0 */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["mailgun"] = factory(); else root["mailgun"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ((function(modules) { // Check all modules for deduplicated modules for(var i in modules) { if(Object.prototype.hasOwnProperty.call(modules, i)) { switch(typeof modules[i]) { case "function": break; case "object": // Module can be created from a template modules[i] = (function(_m) { var args = _m.slice(1), fn = modules[_m[0]]; return function (a,b,c) { fn.apply(this, [a,b,c].concat(args)); }; }(modules[i])); break; default: // Module is a copy of another module modules[i] = modules[modules[i]]; break; } } } return modules; }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(1).polyfill(); var Client = __webpack_require__(6); var version = __webpack_require__(107).version; module.exports = { VERSION: version, client: function client(options) { return new Client(options); } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var require;var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(process, global, module) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 3.0.2 */ (function() { "use strict"; function lib$es6$promise$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function lib$es6$promise$utils$$isFunction(x) { return typeof x === 'function'; } function lib$es6$promise$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var lib$es6$promise$utils$$_isArray; if (!Array.isArray) { lib$es6$promise$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { lib$es6$promise$utils$$_isArray = Array.isArray; } var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; var lib$es6$promise$asap$$len = 0; var lib$es6$promise$asap$$toString = {}.toString; var lib$es6$promise$asap$$vertxNext; var lib$es6$promise$asap$$customSchedulerFn; var lib$es6$promise$asap$$asap = function asap(callback, arg) { lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; lib$es6$promise$asap$$len += 2; if (lib$es6$promise$asap$$len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (lib$es6$promise$asap$$customSchedulerFn) { lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); } else { lib$es6$promise$asap$$scheduleFlush(); } } } function lib$es6$promise$asap$$setScheduler(scheduleFn) { lib$es6$promise$asap$$customSchedulerFn = scheduleFn; } function lib$es6$promise$asap$$setAsap(asapFn) { lib$es6$promise$asap$$asap = asapFn; } var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function lib$es6$promise$asap$$useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function() { process.nextTick(lib$es6$promise$asap$$flush); }; } // vertx function lib$es6$promise$asap$$useVertxTimer() { return function() { lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); }; } function lib$es6$promise$asap$$useMutationObserver() { var iterations = 0; var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function lib$es6$promise$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = lib$es6$promise$asap$$flush; return function () { channel.port2.postMessage(0); }; } function lib$es6$promise$asap$$useSetTimeout() { return function() { setTimeout(lib$es6$promise$asap$$flush, 1); }; } var lib$es6$promise$asap$$queue = new Array(1000); function lib$es6$promise$asap$$flush() { for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { var callback = lib$es6$promise$asap$$queue[i]; var arg = lib$es6$promise$asap$$queue[i+1]; callback(arg); lib$es6$promise$asap$$queue[i] = undefined; lib$es6$promise$asap$$queue[i+1] = undefined; } lib$es6$promise$asap$$len = 0; } function lib$es6$promise$asap$$attemptVertx() { try { var r = require; var vertx = __webpack_require__(4); lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; return lib$es6$promise$asap$$useVertxTimer(); } catch(e) { return lib$es6$promise$asap$$useSetTimeout(); } } var lib$es6$promise$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (lib$es6$promise$asap$$isNode) { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); } else if (lib$es6$promise$asap$$BrowserMutationObserver) { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); } else if (lib$es6$promise$asap$$isWorker) { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); } else if (lib$es6$promise$asap$$browserWindow === undefined && "function" === 'function') { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); } else { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); } function lib$es6$promise$$internal$$noop() {} var lib$es6$promise$$internal$$PENDING = void 0; var lib$es6$promise$$internal$$FULFILLED = 1; var lib$es6$promise$$internal$$REJECTED = 2; var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); function lib$es6$promise$$internal$$selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function lib$es6$promise$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function lib$es6$promise$$internal$$getThen(promise) { try { return promise.then; } catch(error) { lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; return lib$es6$promise$$internal$$GET_THEN_ERROR; } } function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { lib$es6$promise$asap$$asap(function(promise) { var sealed = false; var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { lib$es6$promise$$internal$$resolve(promise, value); } else { lib$es6$promise$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; lib$es6$promise$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; lib$es6$promise$$internal$$reject(promise, error); } }, promise); } function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { lib$es6$promise$$internal$$fulfill(promise, thenable._result); } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { lib$es6$promise$$internal$$reject(promise, thenable._result); } else { lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { lib$es6$promise$$internal$$resolve(promise, value); }, function(reason) { lib$es6$promise$$internal$$reject(promise, reason); }); } } function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = lib$es6$promise$$internal$$getThen(maybeThenable); if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { lib$es6$promise$$internal$$fulfill(promise, maybeThenable); } else if (lib$es6$promise$utils$$isFunction(then)) { lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { lib$es6$promise$$internal$$fulfill(promise, maybeThenable); } } } function lib$es6$promise$$internal$$resolve(promise, value) { if (promise === value) { lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); } else if (lib$es6$promise$utils$$objectOrFunction(value)) { lib$es6$promise$$internal$$handleMaybeThenable(promise, value); } else { lib$es6$promise$$internal$$fulfill(promise, value); } } function lib$es6$promise$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } lib$es6$promise$$internal$$publish(promise); } function lib$es6$promise$$internal$$fulfill(promise, value) { if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } promise._result = value; promise._state = lib$es6$promise$$internal$$FULFILLED; if (promise._subscribers.length !== 0) { lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); } } function lib$es6$promise$$internal$$reject(promise, reason) { if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } promise._state = lib$es6$promise$$internal$$REJECTED; promise._result = reason; lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); } function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); } } function lib$es6$promise$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function lib$es6$promise$$internal$$ErrorObject() { this.error = null; } var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); function lib$es6$promise$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; return lib$es6$promise$$internal$$TRY_CATCH_ERROR; } } function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = lib$es6$promise$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = lib$es6$promise$$internal$$tryCatch(callback, detail); if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== lib$es6$promise$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { lib$es6$promise$$internal$$resolve(promise, value); } else if (failed) { lib$es6$promise$$internal$$reject(promise, error); } else if (settled === lib$es6$promise$$internal$$FULFILLED) { lib$es6$promise$$internal$$fulfill(promise, value); } else if (settled === lib$es6$promise$$internal$$REJECTED) { lib$es6$promise$$internal$$reject(promise, value); } } function lib$es6$promise$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ lib$es6$promise$$internal$$resolve(promise, value); }, function rejectPromise(reason) { lib$es6$promise$$internal$$reject(promise, reason); }); } catch(e) { lib$es6$promise$$internal$$reject(promise, e); } } function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { var enumerator = this; enumerator._instanceConstructor = Constructor; enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); if (enumerator._validateInput(input)) { enumerator._input = input; enumerator.length = input.length; enumerator._remaining = input.length; enumerator._init(); if (enumerator.length === 0) { lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); } else { enumerator.length = enumerator.length || 0; enumerator._enumerate(); if (enumerator._remaining === 0) { lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); } } } else { lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); } } lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { return lib$es6$promise$utils$$isArray(input); }; lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { var enumerator = this; var length = enumerator.length; var promise = enumerator.promise; var input = enumerator._input; for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { enumerator._eachEntry(input[i], i); } }; lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var enumerator = this; var c = enumerator._instanceConstructor; if (lib$es6$promise$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { entry._onerror = null; enumerator._settledAt(entry._state, i, entry._result); } else { enumerator._willSettleAt(c.resolve(entry), i); } } else { enumerator._remaining--; enumerator._result[i] = entry; } }; lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var enumerator = this; var promise = enumerator.promise; if (promise._state === lib$es6$promise$$internal$$PENDING) { enumerator._remaining--; if (state === lib$es6$promise$$internal$$REJECTED) { lib$es6$promise$$internal$$reject(promise, value); } else { enumerator._result[i] = value; } } if (enumerator._remaining === 0) { lib$es6$promise$$internal$$fulfill(promise, enumerator._result); } }; lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); }); }; function lib$es6$promise$promise$all$$all(entries) { return new lib$es6$promise$enumerator$$default(this, entries).promise; } var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; function lib$es6$promise$promise$race$$race(entries) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(lib$es6$promise$$internal$$noop); if (!lib$es6$promise$utils$$isArray(entries)) { lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { lib$es6$promise$$internal$$resolve(promise, value); } function onRejection(reason) { lib$es6$promise$$internal$$reject(promise, reason); } for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; } var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; function lib$es6$promise$promise$resolve$$resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(lib$es6$promise$$internal$$noop); lib$es6$promise$$internal$$resolve(promise, object); return promise; } var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; function lib$es6$promise$promise$reject$$reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(lib$es6$promise$$internal$$noop); lib$es6$promise$$internal$$reject(promise, reason); return promise; } var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; var lib$es6$promise$promise$$counter = 0; function lib$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function lib$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function lib$es6$promise$promise$$Promise(resolver) { this._id = lib$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if (lib$es6$promise$$internal$$noop !== resolver) { if (!lib$es6$promise$utils$$isFunction(resolver)) { lib$es6$promise$promise$$needsResolver(); } if (!(this instanceof lib$es6$promise$promise$$Promise)) { lib$es6$promise$promise$$needsNew(); } lib$es6$promise$$internal$$initializePromise(this, resolver); } } lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; lib$es6$promise$promise$$Promise.prototype = { constructor: lib$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor(lib$es6$promise$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; lib$es6$promise$asap$$asap(function(){ lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); }); } else { lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; function lib$es6$promise$polyfill$$polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { return; } local.Promise = lib$es6$promise$promise$$default; } var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; var lib$es6$promise$umd$$ES6Promise = { 'Promise': lib$es6$promise$promise$$default, 'polyfill': lib$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if ("function" === 'function' && __webpack_require__(5)['amd']) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return lib$es6$promise$umd$$ES6Promise; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = lib$es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; } lib$es6$promise$polyfill$$default(); }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), (function() { return this; }()), __webpack_require__(3)(module))) /***/ }, /* 2 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } 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]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // 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 = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 3 */ /***/ 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; } /***/ }, /* 4 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var merge = __webpack_require__(7); var defaults = __webpack_require__(24); var Request = __webpack_require__(36); var DomainClient = __webpack_require__(64); var EventClient = __webpack_require__(77); var StatsClient = __webpack_require__(92); var SuppressionClient = __webpack_require__(93); var WebhookClient = __webpack_require__(105); var MessagesClient = __webpack_require__(106); var Client = function Client(options) { _classCallCheck(this, Client); options = options || {}; var config = merge({}, options); config = defaults(config, { url: 'https://api.mailgun.net' }); if (!config.username) { throw new Error('Parameter "username" is required'); } else if (!config.key) { throw new Error('Parameter "key" is required'); } this.request = new Request(config); this.domains = new DomainClient(this.request); this.webhooks = new WebhookClient(this.request); this.events = new EventClient(this.request); this.stats = new StatsClient(this.request); this.suppressions = new SuppressionClient(this.request); this.messages = new MessagesClient(this.request); }; module.exports = Client; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.3.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var arrayCopy = __webpack_require__(8), arrayEach = __webpack_require__(9), createAssigner = __webpack_require__(10), isArguments = __webpack_require__(14), isArray = __webpack_require__(15), isPlainObject = __webpack_require__(16), isTypedArray = __webpack_require__(19), keys = __webpack_require__(20), toPlainObject = __webpack_require__(22); /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? undefined : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it is invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); module.exports = merge; /***/ }, /* 8 */ /***/ function(module, exports) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; /***/ }, /* 9 */ /***/ function(module, exports) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }, /* 10 */ [108, 11, 12, 13], /* 11 */ /***/ function(module, exports) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = bindCallback; /***/ }, /* 12 */ /***/ function(module, exports) { /** * lodash 3.0.9 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isIterateeCall; /***/ }, /* 13 */ /***/ function(module, exports) { /** * lodash 3.6.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; /***/ }, /* 14 */ /***/ function(module, exports) { /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; /***/ }, /* 15 */ /***/ function(module, exports) { /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var arrayTag = '[object Array]', funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } module.exports = isArray; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseFor = __webpack_require__(17), isArguments = __webpack_require__(14), keysIn = __webpack_require__(18); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { var Ctor; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } module.exports = isPlainObject; /***/ }, /* 17 */ /***/ function(module, exports) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = baseFor; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.8 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArguments = __webpack_require__(14), isArray = __webpack_require__(15); /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keysIn; /***/ }, /* 19 */ /***/ function(module, exports) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; /***/ }, /* 20 */ [109, 21, 14, 15], /* 21 */ /***/ function(module, exports) { /** * lodash 3.9.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } module.exports = getNative; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseCopy = __webpack_require__(23), keysIn = __webpack_require__(18); /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } module.exports = toPlainObject; /***/ }, /* 23 */ /***/ function(module, exports) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var assign = __webpack_require__(25), restParam = __webpack_require__(35); /** * Used by `_.defaults` to customize its `_.assign` use. * * @private * @param {*} objectValue The destination object property value. * @param {*} sourceValue The source object property value. * @returns {*} Returns the value to assign to the destination object. */ function assignDefaults(objectValue, sourceValue) { return objectValue === undefined ? sourceValue : objectValue; } /** * Creates a `_.defaults` or `_.defaultsDeep` function. * * @private * @param {Function} assigner The function to assign values. * @param {Function} customizer The function to customize assigned values. * @returns {Function} Returns the new defaults function. */ function createDefaults(assigner, customizer) { return restParam(function(args) { var object = args[0]; if (object == null) { return object; } args.push(customizer); return assigner.apply(undefined, args); }); } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var defaults = createDefaults(assign, assignDefaults); module.exports = defaults; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseAssign = __webpack_require__(26), createAssigner = __webpack_require__(32), keys = __webpack_require__(28); /** * A specialized version of `_.assign` for customizing assigned values without * support for argument juggling, multiple sources, and `this` binding `customizer` * functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. */ function assignWith(object, source, customizer) { var index = -1, props = keys(source), length = props.length; while (++index < length) { var key = props[index], value = object[key], result = customizer(value, source[key], key, object, source); if ((result === result ? (result !== value) : (value === value)) || (value === undefined && !(key in object))) { object[key] = result; } } return object; } /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources overwrite property assignments of previous sources. * If `customizer` is provided it is invoked to produce the assigned values. * The `customizer` is bound to `thisArg` and invoked with five arguments: * (objectValue, sourceValue, key, object, source). * * **Note:** This method mutates `object` and is based on * [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). * * @static * @memberOf _ * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); * // => { 'user': 'fred', 'age': 40 } * * // using a customizer callback * var defaults = _.partialRight(_.assign, function(value, other) { * return _.isUndefined(value) ? other : value; * }); * * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var assign = createAssigner(function(object, source, customizer) { return customizer ? assignWith(object, source, customizer) : baseAssign(object, source); }); module.exports = assign; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseCopy = __webpack_require__(27), keys = __webpack_require__(28); /** * The base implementation of `_.assign` without support for argument juggling, * multiple sources, and `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return source == null ? object : baseCopy(source, keys(source), object); } module.exports = baseAssign; /***/ }, /* 27 */ 23, /* 28 */ [109, 29, 30, 31], /* 29 */ 21, /* 30 */ 14, /* 31 */ 15, /* 32 */ [108, 33, 34, 35], /* 33 */ 11, /* 34 */ 12, /* 35 */ 13, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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'); } } var merge = __webpack_require__(7); var popsicle = __webpack_require__(37); var status = __webpack_require__(60); var btoa = __webpack_require__(61); var urljoin = __webpack_require__(62); var APIError = __webpack_require__(63); function parseResponse() { return function (req) { req.after(function (res) { if (res.type() !== 'text/html') { return Promise.resolve(res); } try { if (res.body !== null) { res.body = JSON.parse(res.body); } return Promise.resolve(res); } catch (err) { return Promise.reject(res); } }); }; } function removeUserAgent() { return function (req) { req.before(function (request) { return new Promise(function (resolve) { if (request.headers['user-agent']) { delete request.headers['user-agent']; } resolve(); }); }); }; } var Request = (function () { function Request(options) { _classCallCheck(this, Request); this.username = options.username; this.key = options.key; this.url = options.url; this.headers = options.headers || {}; } _createClass(Request, [{ key: 'request', value: function request(method, url, options) { var headers = merge({ 'Authorization': 'Basic ' + btoa(this.username + ':' + this.key) }, this.headers); var request = merge({ method: method, url: urljoin(this.url, url), headers: headers }, options); return popsicle(request).use(removeUserAgent()).use(parseResponse()).use(status())['catch'](function (error) { if (error.type === 'EINVALIDSTATUS' && error.popsicle) { throw new APIError(error.popsicle.response); } else if (error instanceof Error) { throw error; } else { throw new APIError(error); } }); } }, { key: 'query', value: function query(method, url, params, options) { return this.request(method, url, merge({ query: params }, options)); } }, { key: 'command', value: function command(method, url, data, options) { return this.request(method, url, merge({ body: data, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }, options)); } }, { key: 'get', value: function get(url, params, options) { return this.query('get', url, params, options); } }, { key: 'head', value: function head(url, params, options) { return this.query('head', url, params, options); } }, { key: 'options', value: function options(url, params, _options) { return this.query('options', url, params, _options); } }, { key: 'post', value: function post(url, data, options) { return this.command('post', url, data, options); } }, { key: 'postMulti', value: function postMulti(url, data) { var formData = popsicle.form(); var options = { headers: { 'Content-Type': null } }; Object.keys(data).forEach(function (key) { if (Array.isArray(data[key])) { data[key].forEach(function (item) { formData.append(key, item); }); } else { formData.append(key, data[key]); } }); return this.command('post', url, formData, options); } }, { key: 'put', value: function put(url, data, options) { return this.command('put', url, data, options); } }, { key: 'patch', value: function patch(url, data, options) { return this.command('patch', url, data, options); } }, { key: 'delete', value: function _delete(url, data, options) { return this.command('delete', url, data, options); } }]); return Request; })(); module.exports = Request; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var common_1 = __webpack_require__(38); var index_1 = __webpack_require__(49); var get_headers_1 = __webpack_require__(59); function open(request) { return new Promise(function (resolve, reject) { var url = request.fullUrl(); var method = request.method; var responseType = request.options.responseType; if (window.location.protocol === 'https:' && /^http\:/.test(url)) { return reject(request.error("The request to \"" + url + "\" was blocked", 'EBLOCKED')); } var xhr = request.raw = new XMLHttpRequest(); xhr.onload = function () { return resolve({ status: xhr.status === 1223 ? 204 : xhr.status, headers: get_headers_1.parse(xhr.getAllResponseHeaders()), body: responseType ? xhr.response : xhr.responseText, url: xhr.responseURL }); }; xhr.onabort = function () { return reject(request.error('Request aborted', 'EABORT')); }; xhr.onerror = function () { return reject(request.error("Unable to connect to \"" + request.fullUrl() + "\"", 'EUNAVAILABLE')); }; xhr.onprogress = function (e) { if (e.lengthComputable) { request.downloadLength = e.total; } request.downloadedBytes = e.loaded; }; if (method === 'GET' || method === 'HEAD' || !xhr.upload) { request.uploadLength = 0; request.uploadedBytes = 0; } else { xhr.upload.onprogress = function (e) { if (e.lengthComputable) { request.uploadLength = e.total; } request.uploadedBytes = e.loaded; }; } try { xhr.open(method, url); } catch (e) { return reject(request.error("Refused to connect to \"" + url + "\"", 'ECSP', e)); } if (request.options.withCredentials) { xhr.withCredentials = true; } if (responseType) { try { xhr.responseType = responseType; } finally { if (xhr.responseType !== responseType) { throw request.error("Unsupported response type: " + responseType, 'ERESPONSETYPE'); } } } Object.keys(request.headers).forEach(function (header) { xhr.setRequestHeader(request.name(header), request.get(header)); }); xhr.send(request.body); }); } function abort(request) { request.raw.abort(); } module.exports = common_1.defaults({ transport: { open: open, abort: abort, use: index_1.defaults } }); //# sourceMappingURL=browser.js.map /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {var extend = __webpack_require__(39); var methods = __webpack_require__(40); var request_1 = __webpack_require__(42); var response_1 = __webpack_require__(48); var plugins = __webpack_require__(49); var form_1 = __webpack_require__(56); var jar_1 = __webpack_require__(57); if (typeof Promise === 'undefined') { var context = typeof window === 'object' ? 'window' : 'global'; var message = (context + ".Promise is undefined and must be polyfilled. ") + "Try using https://github.com/jakearchibald/es6-promise instead."; throw new TypeError(message); } function extendDefaults(defaults, options) { if (typeof options === 'string') { return extend(defaults, { url: options }); } return extend(defaults, options); } function defaults(defaultsOptions) { var popsicle = function popsicle(options) { var opts = extendDefaults(defaultsOptions, options); if (typeof opts.url !== 'string') { throw new TypeError('No URL specified'); } return new request_1.default(opts); }; popsicle.Request = request_1.default; popsicle.Response = response_1.default; popsicle.plugins = plugins; popsicle.form = form_1.default; popsicle.jar = jar_1.default; popsicle.browser = !!process.browser; popsicle.defaults = function (options) { return defaults(extend(defaultsOptions, options)); }; methods.forEach(function (method) { ; popsicle[method] = function (options) { return popsicle(extendDefaults({ method: method }, options)); }; }); return popsicle; } exports.defaults = defaults; //# sourceMappingURL=common.js.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2))) /***/ }, /* 39 */ /***/ function(module, exports) { module.exports = extend function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key] } } } return target } /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var http = __webpack_require__(41); /* istanbul ignore next: implementation differs on version */ if (http.METHODS) { module.exports = http.METHODS.map(function(method){ return method.toLowerCase(); }); } else { module.exports = [ 'get', 'post', 'put', 'head', 'delete', 'options', 'trace', 'copy', 'lock', 'mkcol', 'move', 'purge', 'propfind', 'proppatch', 'unlock', 'report', 'mkactivity', 'checkout', 'merge', 'm-search', 'notify', 'subscribe', 'unsubscribe', 'patch', 'search', 'connect' ]; } /***/ }, /* 41 */ 4, /* 42 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var arrify = __webpack_require__(43); var extend = __webpack_require__(39); var base_1 = __webpack_require__(44); var response_1 = __webpack_require__(48); var Request = (function (_super) { __extends(Request, _super); function Request(options) { var _this = this; _super.call(this, options); this.aborted = false; this.timedout = false; this.opened = false; this.started = false; this.uploadLength = null; this.downloadLength = null; this._uploadedBytes = null; this._downloadedBytes = null; this._before = []; this._after = []; this._always = []; this._progress = []; this.timeout = Number(options.timeout) || 0; this.method = (options.method || 'GET').toUpperCase(); this.body = options.body; this.options = extend(options.options); this._promise = new Promise(function (resolve, reject) { process.nextTick(function () { return start(_this).then(resolve, reject); }); }); this.transport = options.transport; this.use(options.use || this.transport.use); this.always(removeListeners); } Request.prototype.use = function (fn) { var _this = this; arrify(fn).forEach(function (fn) { return fn(_this); }); return this; }; Request.prototype.error = function (message, type, original) { var err = new Error(message); err.popsicle = this; err.type = type; err.original = original; return err; }; Request.prototype.then = function (onFulfilled, onRejected) { return this._promise.then(onFulfilled, onRejected); }; Request.prototype.catch = function (onRejected) { return this.then(null, onRejected); }; Request.prototype.exec = function (cb) { this.then(function (response) { cb(null, response); }).catch(cb); }; Request.prototype.toJSON = function () { return { url: this.fullUrl(), headers: this.get(), body: this.body, options: this.options, timeout: this.timeout, method: this.method }; }; Request.prototype.progress = function (fn) { return pluginFunction(this, '_progress', fn); }; Request.prototype.before = function (fn) { return pluginFunction(this, '_before', fn); }; Request.prototype.after = function (fn) { return pluginFunction(this, '_after', fn); }; Request.prototype.always = function (fn) { return pluginFunction(this, '_always', fn); }; Request.prototype.abort = function () { if (this.completed === 1 || this.aborted) { return this; } this.aborted = true; this.errored = this.errored || this.error('Request aborted', 'EABORT'); if (this.opened) { emitProgress(this); this._progress = null; if (this.transport.abort) { this.transport.abort(this); } } return this; }; Object.defineProperty(Request.prototype, "uploaded", { get: function () { return this.uploadLength ? this.uploadedBytes / this.uploadLength : 0; }, enumerable: true, configurable: true }); Object.defineProperty(Request.prototype, "downloaded", { get: function () { return this.downloadLength ? this.downloadedBytes / this.downloadLength : 0; }, enumerable: true, configurable: true }); Object.defineProperty(Request.prototype, "completed", { get: function () { return (this.uploaded + this.downloaded) / 2; }, enumerable: true, configurable: true }); Object.defineProperty(Request.prototype, "completedBytes", { get: function () { return this.uploadedBytes + this.downloadedBytes; }, enumerable: true, configurable: true }); Object.defineProperty(Request.prototype, "totalBytes", { get: function () { return this.uploadLength + this.downloadLength; }, enumerable: true, configurable: true }); Object.defineProperty(Request.prototype, "uploadedBytes", { get: function () { return this._uploadedBytes; }, set: function (bytes) { if (bytes !== this._uploadedBytes) { this._uploadedBytes = bytes; emitProgress(this); } }, enumerable: true, configurable: true }); Object.defineProperty(Request.prototype, "downloadedBytes", { get: function () { return this._downloadedBytes; }, set: function (bytes) { if (bytes !== this._downloadedBytes) { this._downloadedBytes = bytes; emitProgress(this); } }, enumerable: true, configurable: true }); return Request; })(base_1.default); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Request; function pluginFunction(request, property, fn) { if (request.started) { throw new Error('Plugins can not be used after the request has started'); } if (typeof fn !== 'function') { throw new TypeError("Expected a function, but got " + fn + " instead"); } request[property].push(fn); return request; } function start(request) { var req = request; var timeout = request.timeout; var url = request.fullUrl(); var timer; request.started = true; if (request.errored) { return Promise.reject(request.errored); } if (/^https?\:\/*(?:[~#\\\?;\:]|$)/.test(url)) { return Promise.reject(request.error("Refused to connect to invalid URL \"" + url + "\"", 'EINVALID')); } return chain(req._before, request) .then(function () { if (request.errored) { return Promise.reject(request.errored); } if (timeout) { timer = setTimeout(function () { var error = request.error("Timeout of " + request.timeout + "ms exceeded", 'ETIMEOUT'); request.errored = error; request.timedout = true; request.abort(); }, timeout); } req.opened = true; return req.transport.open(request); }) .then(function (options) { if (request.errored) { return Promise.reject(request.errored); } var response = new response_1.default(options); response.request = request; request.response = response; return response; }) .then(function (response) { return chain(req._after, response); }) .then(function () { return chain(req._always, request).then(function () { return request.response; }); }, function (error) { return chain(req._always, request).then(function () { return Promise.reject(request.errored || error); }); }) .then(function (response) { if (request.errored) { return Promise.reject(request.errored); } return response; }); } function chain(fns, arg) { return fns.reduce(function (p, fn) { return p.then(function () { return fn(arg); }); }, Promise.resolve()); } function removeListeners(request) { ; request._before = null; request._after = null; request._always = null; request._progress = null; } function emitProgress(request) { var fns = request._progress; if (!fns || request.errored) { return; } try { for (var i = 0; i < fns.length; i++) { fns[i](request); } } catch (err) { request.errored = err; request.abort(); } } //# sourceMappingURL=request.js.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2))) /***/ }, /* 43 */ /***/ function(module, exports) { 'use strict'; module.exports = function (val) { if (val == null) { return []; } return Array.isArray(val) ? val : [val]; }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var arrify = __webpack_require__(43); var querystring_1 = __webpack_require__(45); var extend = __webpack_require__(39); function lowerHeader(key) { var lower = key.toLowerCase(); if (lower === 'referrer') { return 'referer'; } return lower; } function type(str) { return str == null ? null : str.split(/ *; */)[0]; } var Base = (function () { function Base(_a) { var url = _a.url, headers = _a.headers, query = _a.query; this.url = null; this.headers = {}; this.headerNames = {}; this.query = {}; if (typeof url === 'string') { var queryIndexOf = url.indexOf('?'); var queryObject = typeof query === 'string' ? querystring_1.parse(query) : query; if (queryIndexOf > -1) { this.url = url.substr(0, queryIndexOf); this.query = extend(queryObject, querystring_1.parse(url.substr(queryIndexOf + 1))); } else { this.url = url; this.query = extend(queryObject); } } this.set(headers); } Base.prototype.set = function (name, value) { var _this = this; if (typeof name !== 'string') { if (name) { Object.keys(name).forEach(function (key) { _this.set(key, name[key]); }); } } else { var lower = lowerHeader(name); if (value == null) { delete this.headers[lower]; delete this.headerNames[lower]; } else { this.headers[lower] = value; this.headerNames[lower] = name; } } return this; }; Base.prototype.append = function (name, value) { var prev = this.get(name); var val = arrify(prev).concat(value); return this.set(name, val); }; Base.prototype.name = function (name) { return this.headerNames[lowerHeader(name)]; }; Base.prototype.get = function (name) { var _this = this; if (arguments.length === 0) { var headers = {}; Object.keys(this.headers).forEach(function (key) { headers[_this.name(key)] = _this.get(key); }); return headers; } else { return this.headers[lowerHeader(name)]; } }; Base.prototype.remove = function (name) { var lower = lowerHeader(name); delete this.headers[lower]; delete this.headerNames[lower]; return this; }; Base.prototype.type = function (value) { if (arguments.length === 0) { return type(this.headers['content-type']); } return this.set('Content-Type', value); }; Base.prototype.fullUrl = function () { var url = this.url; var query = querystring_1.stringify(this.query); if (query) { return url + (url.indexOf('?') === -1 ? '?' : '&') + query; } return url; }; return Base; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Base; //# sourceMappingURL=base.js.map /***/ }, /* 45 */ [110, 46, 47], /* 46 */ /***/ function(module, exports) { // 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. 'use strict'; // 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); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }, /* 47 */ /***/ function(module, exports) { // 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. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var base_1 = __webpack_require__(44); var Response = (function (_super) { __extends(Response, _super); function Response(options) { _super.call(this, options); this.body = options.body; this.status = options.status; } Response.prototype.statusType = function () { return ~~(this.status / 100); }; Response.prototype.error = function (message, type, error) { return this.request.error(message, type, error); }; Response.prototype.toJSON = function () { return { url: this.fullUrl(), headers: this.get(), body: this.body, status: this.status }; }; return Response; })(base_1.default); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Response; //# sourceMappingURL=response.js.map /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } __export(__webpack_require__(50)); var common_2 = __webpack_require__(50); exports.defaults = [common_2.stringify, common_2.headers, common_2.parse]; //# sourceMappingURL=browser.js.map /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, Buffer) {var FormData = __webpack_require__(55); var querystring_1 = __webpack_require__(45); var form_1 = __webpack_require__(56); var JSON_MIME_REGEXP = /^application\/(?:[\w!#\$%&\*`\-\.\^~]*\+)?json$/i; var QUERY_MIME_REGEXP = /^application\/x-www-form-urlencoded$/i; var FORM_MIME_REGEXP = /^multipart\/form-data$/i; var isHostObject; if (process.browser) { isHostObject = function (object) { var str = Object.prototype.toString.call(object); switch (str) { case '[object File]': case '[object Blob]': case '[object FormData]': case '[object ArrayBuffer]': return true; default: return false; } }; } else { isHostObject = function (object) { return typeof object.pipe === 'function' || Buffer.isBuffer(object); }; } function defaultHeaders(request) { if (!request.get('Accept')) { request.set('Accept', '*/*'); } request.remove('Host'); } function stringifyRequest(request) { var body = request.body; if (Object(body) !== body) { request.body = body == null ? null : String(body); return; } if (isHostObject(body)) { return; } var type = request.type(); if (!type) { type = 'application/json'; request.type(type); } try { if (JSON_MIME_REGEXP.test(type)) { request.body = JSON.stringify(body); } else if (FORM_MIME_REGEXP.test(type)) { request.body = form_1.default(body); } else if (QUERY_MIME_REGEXP.test(type)) { request.body = querystring_1.stringify(body); } } catch (err) { return Promise.reject(request.error('Unable to stringify request body: ' + err.message, 'ESTRINGIFY', err)); } if (request.body instanceof FormData) { request.remove('Content-Type'); } } function parseResponse(response) { var body = response.body; if (typeof body !== 'string') { return; } if (body === '') { response.body = null; return; } var type = response.type(); try { if (JSON_MIME_REGEXP.test(type)) { response.body = body === '' ? null : JSON.parse(body); } else if (QUERY_MIME_REGEXP.test(type)) { response.body = querystring_1.parse(body); } } catch (err) { return Promise.reject(response.error('Unable to parse response body: ' + err.message, 'EPARSE', err)); } } function headers(request) { request.before(defaultHeaders); } exports.headers = headers; function stringify(request) { request.before(stringifyRequest); } exports.stringify = stringify; function parse(request) { request.after(parseResponse); } exports.parse = parse; //# sourceMappingURL=common.js.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(51).Buffer)) /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ var base64 = __webpack_require__(52) var ieee754 = __webpack_require__(53) var isArray = __webpack_require__(54) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation 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. * 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 = global.TYPED_ARRAY_SUPPORT !== undefined ? global.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 } })() function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } /** * 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) } this.length = 0 this.parent = undefined // Common case. if (typeof arg === 'number') { return fromNumber(this, arg) } // Slightly less common case. if (typeof arg === 'string') { return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } // Unusual. return fromObject(this, arg) } 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 } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' // Assumption: byteLength() return value is always < kMaxLength. var length = byteLength(string, encoding) | 0 that = allocate(that, length) that.write(string, encoding) return that } function fromObject (that, object) { if (Buffer.isBuffer(object)) return fromBuffer(that, object) if (isArray(object)) return fromArray(that, object) if (object == null) { throw new TypeError('must start with number, buffer, array or string') } if (typeof ArrayBuffer !== 'undefined') { if (object.buffer instanceof ArrayBuffer) { return fromTypedArray(that, object) } if (object instanceof ArrayBuffer) { return fromArrayBuffer(that, object) } } if (object.length) return fromArrayLike(that, object) return fromJsonObject(that, object) } function fromBuffer (that, buffer) { var length = checked(buffer.length) | 0 that = allocate(that, length) buffer.copy(that, 0, 0, length) return that } 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 } // 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 } 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 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 } // 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 if (object.type === 'Buffer' && isArray(object.data)) { array = object.data length = checked(array.length) | 0 } that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array } function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = Buffer._augment(new Uint8Array(length)) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that.length = length that._isBuffer = true } var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 if (fromPool) that.parent = rootParent return that } 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 buf = new Buffer(subject, encoding) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length var i = 0 var len = Math.min(x, y) while (i < len) { if (a[i] !== b[i]) break ++i } if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } 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 } } Buffer.concat = function concat (list, length) { if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { return new Buffer(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; i++) { length += list[i].length } } 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 buf } function byteLength (string, encoding) { if (typeof string !== 'string') string = '' + string var len = string.length if (len === 0) return 0 // 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 // 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 start = start | 0 end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = 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) } 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 } 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 '<Buffer ' + str + '>' } 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) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) 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) } 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 } throw new TypeError('val must be string, number or Buffer') } // `get` is deprecated Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `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 } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } 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 } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } 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) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } 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 { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { var swap = encoding encoding = offset offset = length | 0 length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' 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 } } } 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)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] 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 (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint 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 } } } } 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 } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // 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() } // 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 } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length 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 } 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 } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start 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] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * 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') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) 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) 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) 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 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } 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) } 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 } 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) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } 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 offset + byteLength } 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 } return offset + byteLength } 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 } 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 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (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 this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } 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 } 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 } } 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 } 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 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } 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 } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } 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 } 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 } 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 } 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 } 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') } 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 } 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) } 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 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // 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 // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // 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') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i 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 len } // 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 if (end < start) throw new RangeError('end < start') // 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') 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] } } 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') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * 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 return arr } 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 } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] 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 } // 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') } } return bytes } 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 } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } 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__(51).Buffer, (function() { return this; }()))) /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array 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) 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 } 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') } // 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) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } 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) } 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) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 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 } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }( false ? (this.base64js = {}) : exports)) /***/ }, /* 53 */ /***/ 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 (s ? -1 : 1) * m * Math.pow(2, e - mLen) } 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 { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } 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 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } /***/ }, /* 54 */ /***/ function(module, exports) { /** * isArray */ var isArray = Array.isArray; /** * toString */ var str = Object.prototype.toString; /** * Whether or not the given `val` * is an array. * * example: * * isArray([]); * // > true * isArray(arguments); * // > false * isArray(''); * // > false * * @param {mixed} val * @return {bool} */ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; /***/ }, /* 55 */ /***/ function(module, exports) { module.exports = FormData; //# sourceMappingURL=form-data.js.map /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var FormData = __webpack_require__(55); function form(obj) { var form = new FormData(); if (obj) { Object.keys(obj).forEach(function (name) { form.append(name, obj[name]); }); } return form; } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = form; //# sourceMappingURL=form.js.map /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var tough_cookie_1 = __webpack_require__(58); function cookieJar(store) { return new tough_cookie_1.CookieJar(store); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cookieJar; //# sourceMappingURL=jar.js.map /***/ }, /* 58 */ /***/ function(module, exports) { module.exports = function ToughCookie() { throw new TypeError('Cookie jars are only available on node'); }; //# sourceMappingURL=tough-cookie.js.map /***/ }, /* 59 */ /***/ function(module, exports) { function parse(value) { var arr = []; var lines = value.replace(/\r?\n$/, '').split(/\r?\n/); for (var i = 0; i < lines.length; i++) { var header = lines[i]; var indexOf = header.indexOf(':'); var name_1 = header.substr(0, indexOf).trim(); var value_1 = header.substr(indexOf + 1).trim(); arr.push(name_1, value_1); } return array(arr); } exports.parse = parse; function http(response) { if (response.rawHeaders) { return array(response.rawHeaders); } var headers = {}; Object.keys(response.headers).forEach(function (key) { var value = response.headers[key]; if (value.length === 1) { headers[key] = value[0]; } else { headers[key] = value; } }); return headers; } exports.http = http; function array(values) { var casing = {}; var headers = {}; for (var i = 0; i < values.length; i = i + 2) { var name_2 = values[i]; var lower = name_2.toLowerCase(); var oldName = casing[lower]; var value = values[i + 1]; if (!headers.hasOwnProperty(oldName)) { headers[name_2] = value; } else { if (name_2 !== oldName) { headers[name_2] = headers[oldName]; delete headers[oldName]; } if (typeof headers[name_2] === 'string') { headers[name_2] = [headers[name_2], value]; } else { headers[name_2].push(value); } } casing[lower] = name_2; } return headers; } exports.array = array; //# sourceMappingURL=index.js.map /***/ }, /* 60 */ /***/ function(module, exports) { module.exports = popsicleStatus function popsicleStatus () { var lower = 200 var upper = 399 if (arguments.length === 1) { lower = arguments[0] upper = arguments[0] } if (arguments.length === 2) { lower = arguments[0] upper = arguments[1] } return function (req) { req.after(function (res) { if (res.status >= lower && res.status <= upper) { return Promise.resolve(res) } var message if (lower === upper) { message = 'should equal ' + upper } else { message = 'should be between ' + lower + ' and ' + upper } var err = res.error('Invalid HTTP status, ' + res.status + ', ' + message, 'EINVALIDSTATUS') err.status = res.status return Promise.reject(err) }) } } /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {(function () { "use strict"; function btoa(str) { var buffer ; if (str instanceof Buffer) { buffer = str; } else { buffer = new Buffer(str.toString(), 'binary'); } return buffer.toString('base64'); } module.exports = btoa; }()); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(51).Buffer)) /***/ }, /* 62 */ /***/ function(module, exports) { function normalize (str) { return str .replace(/[\/]+/g, '/') .replace(/\/\?/g, '?') .replace(/\/\#/g, '#') .replace(/\:\//g, '://'); } module.exports = function () { var joined = [].slice.call(arguments, 0).join('/'); return normalize(joined); }; /***/ }, /* 63 */ /***/ function(module, exports) { 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var APIError = function APIError(response) { _classCallCheck(this, APIError); this.status = response.status; this.message = response.message || response.body && (response.body.message || response.body.error); this.id = response.id || response.headers && response.headers['x-mailgun-request-id']; }; module.exports = APIError; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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'); } } var map = __webpack_require__(65); var urljoin = __webpack_require__(62); var Domain = function Domain(data, receiving, sending) { _classCallCheck(this, Domain); this.name = data.name; this.require_tls = data.require_tls; this.skip_verification = data.skip_verification; this.state = data.state; this.wildcard = data.wildcard; this.spam_action = data.spam_action; this.created_at = data.created_at; this.smtp_password = data.smtp_password; this.smtp_login = data.smtp_login; this.type = data.type; this.receiving_dns_records = receiving || null; this.sending_dns_records = sending || null; }; var DomainClient = (function () { function DomainClient(request) { _classCallCheck(this, DomainClient); this.request = request; } _createClass(DomainClient, [{ key: '_parseMessage', value: function _parseMessage(response) { return response.body; } }, { key: '_parseDomainList', value: function _parseDomainList(response) { return map(response.body.items, function (item) { return new Domain(item); }); } }, { key: '_parseDomain', value: function _parseDomain(response) { return new Domain(response.body.domain, response.body.receiving_dns_records, response.body.sending_dns_records); } }, { key: '_parseTrackingSettings', value: function _parseTrackingSettings(response) { return response.body.tracking; } }, { key: '_parseTrackingUpdate', value: function _parseTrackingUpdate(response) { return response.body; } }, { key: 'list', value: function list(query) { return this.request.get('/v2/domains', query).then(this._parseDomainList); } }, { key: 'get', value: function get(domain) { return this.request.get('/v2/domains/' + domain).then(this._parseDomain); } }, { key: 'create', value: function create(data) { return this.request.post('/v2/domains', data).then(this._parseDomain); } }, { key: 'destroy', value: function destroy(domain) { return this.request['delete']('/v2/domains/' + domain).then(this._parseMessage); } // Tracking }, { key: 'getTracking', value: function getTracking(domain) { return this.request.get(urljoin('/v2/domains', domain, 'tracking')).then(this._parseTrackingSettings); } }, { key: 'updateTracking', value: function updateTracking(domain, type, data) { return this.request.put(urljoin('/v2/domains', domain, 'tracking', type), data).then(this._parseTrackingUpdate); } }]); return DomainClient; })(); module.exports = DomainClient; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var arrayMap = __webpack_require__(66), baseCallback = __webpack_require__(67), baseEach = __webpack_require__(76), isArray = __webpack_require__(69); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.map` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Creates an array of values by running each element in `collection` through * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, * `sum`, `uniq`, and `words` * * @static * @memberOf _ * @alias collect * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new mapped array. * @example * * function timesThree(n) { * return n * 3; * } * * _.map([1, 2], timesThree); * // => [3, 6] * * _.map({ 'a': 1, 'b': 2 }, timesThree); * // => [3, 6] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // using the `_.property` callback shorthand * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee, thisArg) { var func = isArray(collection) ? arrayMap : baseMap; iteratee = baseCallback(iteratee, thisArg, 3); return func(collection, iteratee); } module.exports = map; /***/ }, /* 66 */ /***/ function(module, exports) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `_.map` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 67 */ [111, 68, 74, 69, 75], /* 68 */ [112, 69, 70, 71], /* 69 */ 15, /* 70 */ 19, /* 71 */ [109, 72, 73, 69], /* 72 */ 21, /* 73 */ 14, /* 74 */ 11, /* 75 */ [113, 71], /* 76 */ [114, 71], /* 77 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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'); } } var map = __webpack_require__(65); var last = __webpack_require__(78); var indexBy = __webpack_require__(79); var urljoin = __webpack_require__(62); var Event = function Event(data) { _classCallCheck(this, Event); this.type = data.type; this.summary = data.gist; this.content = data.content; this.timestamp = new Date(data.timestamp); }; var EventClient = (function () { function EventClient(request) { _classCallCheck(this, EventClient); this.request = request; } _createClass(EventClient, [{ key: '_parsePageNumber', value: function _parsePageNumber(url) { return last(url.split('/')); } }, { key: '_parsePage', value: function _parsePage(id, url) { return { id: id, number: this._parsePageNumber(url), url: url }; } }, { key: '_parsePageLinks', value: function _parsePageLinks(response) { var _this = this; var pages; pages = {}; pages = map(response.body.paging, function (url, id) { return _this._parsePage(id, url); }); return indexBy(pages, 'id'); } }, { key: '_parseEventList', value: function _parseEventList(response) { var items; items = map(response.body.items, function (data) { return new Event(data); }); items.pages = this._parsePageLinks(response); return items; } }, { key: 'get', value: function get(domain, query) { var _this2 = this; var url; if (query && query.page) { url = urljoin('/v2', domain, 'events', query.page); delete query.page; } else { url = urljoin('/v2', domain, 'events'); } return this.request.get(url, query).then(function (response) { return _this2._parseEventList(response); }); } }]); return EventClient; })(); module.exports = EventClient; /***/ }, /* 78 */ /***/ function(module, exports) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } module.exports = last; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var createAggregator = __webpack_require__(80); /** * Creates an object composed of keys generated from the results of running * each element of `collection` through `iteratee`. The corresponding value * of each key is the last element responsible for generating the key. The * iteratee function is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the composed aggregate object. * @example * * var keyData = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.indexBy(keyData, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keyData, function(object) { * return String.fromCharCode(object.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keyData, function(object) { * return this.fromCharCode(object.code); * }, String); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } */ var indexBy = createAggregator(function(result, value, key) { result[key] = value; }); module.exports = indexBy; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseCallback = __webpack_require__(81), baseEach = __webpack_require__(91), isArray = __webpack_require__(83); /** * Creates a function that aggregates a collection, creating an accumulator * object composed from the results of running each element in the collection * through an iteratee. The `setter` sets the keys and values of the accumulator * object. If `initializer` is provided initializes the accumulator object. * * @private * @param {Function} setter The function to set keys and values of the accumulator object. * @param {Function} [initializer] The function to initialize the accumulator object. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee, thisArg) { var result = initializer ? initializer() : {}; iteratee = baseCallback(iteratee, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; setter(result, value, iteratee(value, index, collection), collection); } } else { baseEach(collection, function(value, key, collection) { setter(result, value, iteratee(value, key, collection), collection); }); } return result; }; } module.exports = createAggregator; /***/ }, /* 81 */ [111, 82, 89, 83, 90], /* 82 */ [112, 83, 84, 85], /* 83 */ 15, /* 84 */ 19, /* 85 */ [109, 86, 87, 88], /* 86 */ 21, /* 87 */ 14, /* 88 */ 15, /* 89 */ 11, /* 90 */ [113, 85], /* 91 */ [114, 85], /* 92 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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'); } } var map = __webpack_require__(65); var urljoin = __webpack_require__(62); var Stats = function Stats(data) { _classCallCheck(this, Stats); this.start = new Date(data.start); this.end = new Date(data.end); this.resolution = data.resolution; this.stats = map(data.stats, function (stat) { stat.time = new Date(stat.time); return stat; }); }; var StatsClient = (function () { function StatsClient(request) { _classCallCheck(this, StatsClient); this.request = request; } _createClass(StatsClient, [{ key: '_parseStats', value: function _parseStats(response) { return new Stats(response.body); } }, { key: 'getDomain', value: function getDomain(domain, query) { return this.request.get(urljoin('/v3', domain, 'stats/total'), query).then(this._parseStats); } }, { key: 'getAccount', value: function getAccount(query) { return this.request.get('/v3/stats/total', query).then(this._parseStats); } }]); return StatsClient; })(); module.exports = StatsClient; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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'); } } var map = __webpack_require__(65); var indexBy = __webpack_require__(79); var partialRight = __webpack_require__(94); var url = __webpack_require__(100); var urljoin = __webpack_require__(62); var createOptions = { headers: { 'Content-Type': 'application/json' } }; var Bounce = function Bounce(data) { _classCallCheck(this, Bounce); this.type = 'bounces'; this.address = data.address; this.code = data.code; this.error = data.error; this.created_at = new Date(data.created_at); }; var Complaint = function Complaint(data) { _classCallCheck(this, Complaint); this.type = 'complaints'; this.address = data.address; this.created_at = new Date(data.created_at); }; var Unsubscribe = function Unsubscribe(data) { _classCallCheck(this, Unsubscribe); this.type = 'unsubscribes'; this.address = data.address; this.tags = data.tags; this.created_at = new Date(data.created_at); }; var SuppressionClient = (function () { function SuppressionClient(request) { _classCallCheck(this, SuppressionClient); this.request = request; this.models = { bounces: Bounce, complaints: Complaint, unsubscribes: Unsubscribe }; } _createClass(SuppressionClient, [{ key: '_parsePage', value: function _parsePage(id, pageUrl) { var parsedUrl = url.parse(pageUrl, true); var query = parsedUrl.query; return { id: id, page: query.page, address: query.address, url: pageUrl }; } }, { key: '_parsePageLinks', value: function _parsePageLinks(response) { var _this = this; var pages; pages = {}; pages = map(response.body.paging, function (url, id) { return _this._parsePage(id, url); }); return indexBy(pages, 'id'); } }, { key: '_parseList', value: function _parseList(response, Model) { var data = {}; data.items = map(response.body.items, function (data) { return new Model(data); }); data.pages = this._parsePageLinks(response); return data; } }, { key: '_parseItem', value: function _parseItem(response, Model) { return new Model(response.body); } }, { key: 'list', value: function list(domain, type, query) { var _this2 = this; var parser; var model = this.models[type]; return this.request.get(urljoin('v3', domain, type), query).then(function (response) { return _this2._parseList(response, model); }); } }, { key: 'get', value: function get(domain, type, address) { var model = this.models[type]; var parser = partialRight(this._parseItem, model); address = encodeURIComponent(address); return this.request.get(urljoin('v3', domain, type, address)).then(function (response) { return parser(response); }); } }, { key: 'create', value: function create(domain, type, data) { // supports adding multiple suppressions by default if (!Array.isArray(data)) { data = [data]; } return this.request.post(urljoin('v3', domain, type), data, createOptions).then(function (response) { return response.body; }); } }, { key: 'destroy', value: function destroy(domain, type, address) { address = encodeURIComponent(address); return this.request['delete'](urljoin('v3', domain, type, address)).then(function (response) { return response.body; }); } }]); return SuppressionClient; })(); module.exports = SuppressionClient; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var createWrapper = __webpack_require__(95), replaceHolders = __webpack_require__(98), restParam = __webpack_require__(99); /** Used to compose bitmasks for wrapper metadata. */ var PARTIAL_RIGHT_FLAG = 64; /** * Creates a `_.partial` or `_.partialRight` function. * * @private * @param {boolean} flag The partial bit flag. * @returns {Function} Returns the new partial function. */ function createPartial(flag) { var partialFunc = restParam(function(func, partials) { var holders = replaceHolders(partials, partialFunc.placeholder); return createWrapper(func, flag, undefined, partials, holders); }); return partialFunc; } /** * This method is like `_.partial` except that partially applied arguments * are appended to those provided to the new function. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method does not set the "length" property of partially * applied functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { * return greeting + ' ' + name; * }; * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // using placeholders * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = createPartial(PARTIAL_RIGHT_FLAG); // Assign default placeholders. partialRight.placeholder = {}; module.exports = partialRight; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * lodash 3.0.7 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var arrayCopy = __webpack_require__(96), baseCreate = __webpack_require__(97), replaceHolders = __webpack_require__(98); /** Used to compose bitmasks for wrapper metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array|Object} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders) { var holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), leftIndex = -1, leftLength = partials.length, result = Array(leftLength + argsLength); while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { result[holders[argsIndex]] = args[argsIndex]; } while (argsLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array|Object} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders) { var holdersIndex = -1, holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), rightIndex = -1, rightLength = partials.length, result = Array(argsLength + rightLength); while (++argsIndex < argsLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } return result; } /** * Creates a function that wraps `func` and invokes it with the `this` * binding of `thisArg`. * * @private * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new bound function. */ function createBindWrapper(func, thisArg) { var Ctor = createCtorWrapper(func); function wrapper() { var fn = (this && this !== global && this instanceof wrapper) ? Ctor : func; return fn.apply(thisArg, arguments); } return wrapper; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtorWrapper(Ctor) { return function() { // Use a `switch` statement to work with class constructors. // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` and invokes it with optional `this` * binding of, partial application, and currying. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurry = bitmask & CURRY_FLAG, isCurryBound = bitmask & CURRY_BOUND_FLAG, isCurryRight = bitmask & CURRY_RIGHT_FLAG, Ctor = isBindKey ? undefined : createCtorWrapper(func); function wrapper() { // Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it to other functions. var length = arguments.length, index = length, args = Array(length); while (index--) { args[index] = arguments[index]; } if (partials) { args = composeArgs(args, partials, holders); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight); } if (isCurry || isCurryRight) { var placeholder = wrapper.placeholder, argsHolders = replaceHolders(args, placeholder); length -= argsHolders.length; if (length < arity) { var newArgPos = argPos ? arrayCopy(argPos) : undefined, newArity = nativeMax(arity - length, 0), newsHolders = isCurry ? argsHolders : undefined, newHoldersRight = isCurry ? undefined : argsHolders, newPartials = isCurry ? args : undefined, newPartialsRight = isCurry ? undefined : args; bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); if (!isCurryBound) { bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); } var result = createHybridWrapper(func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity); result.placeholder = placeholder; return result; } } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; if (argPos) { args = reorder(args, argPos); } if (isAry && ary < args.length) { args.length = ary; } if (this && this !== global && this instanceof wrapper) { fn = Ctor || createCtorWrapper(func); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function that wraps `func` and invokes it with the optional `this` * binding of `thisArg` and the `partials` prepended to those provided to * the wrapper. * * @private * @param {Function} func The function to partially apply arguments to. * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to the new function. * @returns {Function} Returns the new bound function. */ function createPartialWrapper(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtorWrapper(func); function wrapper() { // Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it `func`. var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength); while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } var fn = (this && this !== global && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, args); } return wrapper; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = undefined; } length -= (holders ? holders.length : 0); if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; newData[9] = arity == null ? (isBindKey ? 0 : func.length) : (nativeMax(arity - length, 0) || 0); if (bitmask == BIND_FLAG) { var result = createBindWrapper(newData[0], newData[2]); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { result = createPartialWrapper.apply(undefined, newData); } else { result = createHybridWrapper.apply(undefined, newData); } return result; } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = arrayCopy(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = createWrapper; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 96 */ 8, /* 97 */ /***/ function(module, exports) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(prototype) { if (isObject(prototype)) { object.prototype = prototype; var result = new object; object.prototype = undefined; } return result || {}; }; }()); /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = baseCreate; /***/ }, /* 98 */ /***/ function(module, exports) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { if (array[index] === placeholder) { array[index] = PLACEHOLDER; result[++resIndex] = index; } } return result; } module.exports = replaceHolders; /***/ }, /* 99 */ 13, /* 100 */ /***/ 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. var punycode = __webpack_require__(101); 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__(102); 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. // // 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; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // 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); } } // 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; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // 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(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; 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.query && isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // 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 = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } 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); // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // 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]; }); //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } 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; } 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; } 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; } 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 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 === ''); // 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 the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // 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(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //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; }; 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; }; function isString(arg) { return typeof arg === "string"; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; } /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/punycode v1.3.2 by @mathias */ ;(function(root) { /** 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; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** 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' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * 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]); } /** * 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; } /** * 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; } /** * 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 <https://mathiasbynens.be/notes/javascript-encoding> * @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; } /** * 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(''); } /** * 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; } /** * 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); } /** * 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)); } /** * 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)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `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) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `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'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * 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)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // 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; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } 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; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.3.2', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** 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; } }(this)); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)(module), (function() { return this; }()))) /***/ }, /* 102 */ [110, 103, 104], /* 103 */ /***/ function(module, exports) { // 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. 'use strict'; // 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); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; /***/ }, /* 104 */ /***/ function(module, exports) { // 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. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return Object.keys(obj).map(function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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'); } } var map = __webpack_require__(65); var urljoin = __webpack_require__(62); var Webhook = function Webhook(id, data) { _classCallCheck(this, Webhook); this.id = id; this.url = data.url; }; var WebhookClient = (function () { function WebhookClient(request) { _classCallCheck(this, WebhookClient); this.request = request; } _createClass(WebhookClient, [{ key: '_parseWebhookList', value: function _parseWebhookList(response) { return response.body.webhooks; } }, { key: '_parseWebhookWithID', value: function _parseWebhookWithID(id) { return function (response) { return new Webhook(id, response.body.webhook); }; } }, { key: '_parseWebhookTest', value: function _parseWebhookTest(response) { return { code: response.body.code, message: response.body.message }; } }, { key: 'list', value: function list(domain, query) { return this.request.get(urljoin('/v2/domains', domain, 'webhooks'), query).then(this._parseWebhookList); } }, { key: 'get', value: function get(domain, id) { return this.request.get(urljoin('/v2/domains', domain, 'webhooks', id)).then(this._parseWebhookWithID(id)); } }, { key: 'create', value: function create(domain, id, url, test) { if (test) { return this.request.put(urljoin('/v2/domains', domain, 'webhooks', id, 'test'), { url: url }).then(this._parseWebhookTest); } else { return this.request.post(urljoin('/v2/domains', domain, 'webhooks'), { id: id, url: url }).then(this._parseWebhookWithID(id)); } } }, { key: 'update', value: function update(domain, id, url) { return this.request.put(urljoin('/v2/domains', domain, 'webhooks', id), { url: url }).then(this._parseWebhookWithID(id)); } }, { key: 'destroy', value: function destroy(domain, id) { return this.request['delete'](urljoin('/v2/domains', domain, 'webhooks', id)).then(this._parseWebhookWithID(id)); } }]); return WebhookClient; })(); module.exports = WebhookClient; /***/ }, /* 106 */ /***/ function(module, exports) { 'use strict'; 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'); } } var MessagesClient = (function () { function MessagesClient(request) { _classCallCheck(this, MessagesClient); this.request = request; } _createClass(MessagesClient, [{ key: '_parseResponse', value: function _parseResponse(response) { if (response.body) { return response.body; } else { return response; } } }, { key: 'create', value: function create(domain, data) { if (data.mime) { return this.request.postMulti('/v3/' + domain + '/messages.mime', data).then(this._parseResponse); } else { return this.request.postMulti('/v3/' + domain + '/messages', data).then(this._parseResponse); } } }]); return MessagesClient; })(); module.exports = MessagesClient; /***/ }, /* 107 */ /***/ function(module, exports) { module.exports = { "name": "mailgun.js", "version": "1.1.0", "main": "index.js", "author": "Mailgun", "license": "MIT", "keywords": [ "mailgun", "email" ], "repository": { "type": "git", "url": "git://github.com/mailgun/mailgun-js.git" }, "bugs": { "url": "https://github.com/mailgun/mailgun-js/issues" }, "homepage": "https://github.com/mailgun/mailgun-js#readme", "scripts": { "build": "webpack --config ./webpack.config.js --progress --colors", "start": "webpack --config ./webpack.config.js --progress --colors --watch", "release": "webpack --config ./webpack.release.config.js --progress --colors", "test": "multi='dot=- xunit=./results.xml' mocha --compilers js:babel/register -t 10000 -R mocha-multi", "test-watch": "mocha --compilers js:babel/register -w -R dot", "preversion": "npm test", "version": "npm run release && git add -A dist", "postversion": "git push && git push --tags && rm -rf build" }, "dependencies": { "btoa": "^1.1.2", "es6-promise": "^3.0.2", "lodash.defaults": "^3.1.2", "lodash.indexby": "^3.1.1", "lodash.last": "^3.0.0", "lodash.map": "^3.1.4", "lodash.merge": "^3.3.2", "lodash.partialright": "^3.1.1", "popsicle": "^1.1.1", "popsicle-status": "^0.2.0", "url-join": "0.0.1" }, "devDependencies": { "babel": "^5.8.23", "babel-loader": "^5.3.2", "exports-loader": "^0.6.2", "expose-loader": "^0.7.0", "imports-loader": "^0.6.4", "jscs-loader": "^0.2.0", "json-loader": "^0.5.2", "mocha": "^2.2.3", "mocha-multi": "^0.7.1", "nock": "^0.48.1", "raw-loader": "^0.5.1", "should": "^4.1.0", "webpack": "^1.12.1", "webpack-dev-server": "^1.11.0", "xmlbuilder": "^2.6.2" }, "contributors": [ { "name": "Brad Gignac", "url": "https://github.com/bradgignac" }, { "name": "Eddy Hernandez", "url": "https://github.com/eddywashere" } ] }; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__, __webpack_module_template_argument_0__, __webpack_module_template_argument_1__, __webpack_module_template_argument_2__) { /** * lodash 3.1.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var bindCallback = __webpack_require__(__webpack_module_template_argument_0__), isIterateeCall = __webpack_require__(__webpack_module_template_argument_1__), restParam = __webpack_require__(__webpack_module_template_argument_2__); /** * Creates a function that assigns properties of source object(s) to a given * destination object. * * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__, __webpack_module_template_argument_0__, __webpack_module_template_argument_1__, __webpack_module_template_argument_2__) { /** * lodash 3.1.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = __webpack_require__(__webpack_module_template_argument_0__), isArguments = __webpack_require__(__webpack_module_template_argument_1__), isArray = __webpack_require__(__webpack_module_template_argument_2__); /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keys; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__, __webpack_module_template_argument_0__, __webpack_module_template_argument_1__) { 'use strict'; exports.decode = exports.parse = __webpack_require__(__webpack_module_template_argument_0__); exports.encode = exports.stringify = __webpack_require__(__webpack_module_template_argument_1__); /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__, __webpack_module_template_argument_0__, __webpack_module_template_argument_1__, __webpack_module_template_argument_2__, __webpack_module_template_argument_3__) { /** * lodash 3.3.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseIsEqual = __webpack_require__(__webpack_module_template_argument_0__), bindCallback = __webpack_require__(__webpack_module_template_argument_1__), isArray = __webpack_require__(__webpack_module_template_argument_2__), pairs = __webpack_require__(__webpack_module_template_argument_3__); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { return value == null ? '' : (value + ''); } /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = object[path[index++]]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} matchData The propery names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = toObject(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var result = customizer ? customizer(objValue, srcValue, key) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { return false; } } } return true; } /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in toObject(object))); }; } return function(object) { return baseIsMatch(object, matchData); }; } /** * The base implementation of `_.matchesProperty` which does not clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === srcValue ? (srcValue !== undefined || (key in object)) : baseIsEqual(srcValue, object[key], undefined, true); }; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * Gets the propery names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = pairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Creates a function that returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = baseCallback; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__, __webpack_module_template_argument_0__, __webpack_module_template_argument_1__, __webpack_module_template_argument_2__) { /** * lodash 3.0.7 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArray = __webpack_require__(__webpack_module_template_argument_0__), isTypedArray = __webpack_require__(__webpack_module_template_argument_1__), keys = __webpack_require__(__webpack_module_template_argument_2__); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { return false; } } return true; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} value The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // Coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; // Recursively compare objects (susceptible to call stack limits). if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = baseIsEqual; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__, __webpack_module_template_argument_0__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(__webpack_module_template_argument_0__); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { object = toObject(object); var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } module.exports = pairs; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__, __webpack_module_template_argument_0__) { /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(__webpack_module_template_argument_0__); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = baseEach; /***/ } /******/ ]))) }); ; //# sourceMappingURL=mailgun.js.map