text
stringlengths
3
1.05M
// paste in your published Google Sheets URL from the browser address bar var googleDocURL = 'https://docs.google.com/spreadsheets/d/1KtlbBI0y5HgZhPvvrumbzclKaWOnzmVVo7rDB6hdO2U/edit#gid=0'; // insert your own Google Sheets API key from https://console.developers.google.com var googleApiKey = 'AIzaSyBKp65u3JgHbc2gPK2qvSOU17grYEN2k7M';
var models = {} var noa var meshbody=null var scene=null var modelname='firework' export function defineModelCompFirework(noa2) { meshbody= projectiles['fireworks']//mainplayer; } export function wath(){ return meshbody; } export function applyModelFirework(eid, model, texture, offset, nametag, name, hitbox,randomizer,rando,entityList,uuid,socket,PF,noa,pos) { var builded=meshbody.clone(name) var cid = noa.entities.addent( [pos[0],pos[1]+0.5,pos[2]], 0.5, 0.5, builded, [0.2,0.5/2,0.2], true, false,false,null ) //noa.ents.getState(eid, 'model').nametag=addNametag(builded, 'horse', 1.5) noa.entities.addComponent(cid, noa.entities.names.propulsion,{ mesh:builded }) } function addNametag(mainMesh, name, height) { var scene = noa.rendering.getScene() var font_size = 96 var font = "bold " + font_size + "px 'lato'" //Set height for plane var planeHeight = 0.5//0.3 //Set height for dynamic texture var DTHeight = 1.5 * font_size //or set as wished //Calcultae ratio var ratio = planeHeight/DTHeight //Use a temporay dynamic texture to calculate the length of the text on the dynamic texture canvas var temp = new BABYLON.DynamicTexture("DynamicTexture", 64, scene) var tmpctx = temp.getContext() tmpctx.font = font var DTWidth = tmpctx.measureText(name).width + 8 //Calculate width the plane has to be var planeWidth = DTWidth * ratio //Create dynamic texture and write the text var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", {width:DTWidth, height:DTHeight}, scene, false) var mat = noa.rendering.makeStandardMaterial('nametag') mat.diffuseTexture = dynamicTexture mat.emissiveTexture = mat.diffuseTexture mat.diffuseTexture.hasAlpha = true mat.opacityTexture = mat.diffuseTexture dynamicTexture.drawText(name, null, null, font, "#eeeeee", "#00000066", true) //Create plane and set dynamic texture as material var plane = BABYLON.MeshBuilder.CreatePlane("plane", {width:planeWidth, height:planeHeight}, scene) plane.material = mat //plane.setPositionWithLocalVector(new BABYLON.Vector3(height + 0.2, 0, 0)) plane.position.x=mainMesh.position.x plane.position.y=mainMesh.position.y+3 plane.position.z=mainMesh.position.z plane.opaque = false plane.setParent(mainMesh) noa.rendering.addMeshToScene(plane) plane.billboardMode = BABYLON.Mesh.BILLBOARDMODE_ALL return plane }
'use strict' // Template version: 1.2.4 // see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: true, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader? // If true, your code will be linted during bundling and // linting errors and warnings will be shown in the console. useEslint: true, // If true, eslint errors and warnings will also be shown in the error overlay // in the browser. showEslintErrorsInOverlay: false, // 代理配置 proxyTable: { '/api/': { target: 'http://localhost:3000', changeOrigin:true, pathRewrite: { '^/api': '' } }, }, /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false, }, build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: './', proxyTable: { '/api/': { target: 'localhost:3000', changeOrigin:true, pathRewrite: { '^/api': '' } }, }, /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report } }
'use strict'; let searching = 0; let zoomclick = null; // 以下是公共方法 function find_child(parent, name, attr) { let children = parent.childNodes; for (let i = 0; i < children.length; i++) { if (children[i].tagName == name) return (attr != undefined) ? children[i].attributes[attr].value : children[i]; } return; } function orig_load(e, attr) { if (e.attributes["_orig_" + attr] == undefined) return; e.attributes[attr].value = e.attributes["_orig_" + attr].value; e.removeAttribute("_orig_" + attr); } function orig_save(e, attr, val) { if (e.attributes["_orig_" + attr] != undefined) return; if (e.attributes[attr] == undefined) return; if (val == undefined) val = e.attributes[attr].value; e.setAttribute("_orig_" + attr, val); } function g_to_text(e) { var text = find_child(e, "title").firstChild.nodeValue; return (text) } function g_to_func(e) { var func = g_to_text(e); if (func != null) func = func.replace(/ .*/, ""); return (func); } function zoom_child(e, x, ratio) { if (e.attributes != undefined) { if (e.attributes["x"] != undefined) { orig_save(e, "x"); e.attributes["x"].value = (parseFloat(e.attributes["x"].value) - x - 10) * ratio + 10; if (e.tagName == "text") e.attributes["x"].value = find_child(e.parentNode, "rect", "x") + 3; } if (e.attributes["width"] != undefined) { orig_save(e, "width"); const index = e.attributes['node-index'].value; const width_origin = e.attributes["width"].value; e.attributes["width"].value = parseFloat(width_origin) * ratio; e.attributes["width"].value = e.attributes["width"].value; } } if (e.childNodes == undefined) return; for (let i = 0, c = e.childNodes; i < c.length; i++) { zoom_child(c[i], x - 10, ratio); } } function zoom_parent(e, svg) { if (e.attributes) { if (e.attributes["x"] != undefined) { orig_save(e, "x"); e.attributes["x"].value = 10; } if (e.attributes["width"] != undefined) { orig_save(e, "width"); e.attributes["width"].value = parseFloat(svg.width.baseVal.value) - (10 * 2); } } if (e.childNodes == undefined) return; for (let i = 0, c = e.childNodes; i < c.length; i++) { zoom_parent(c[i], svg); } } function update_text(e) { let r = find_child(e, "rect"); let t = find_child(e, "text"); let w = parseFloat(r.attributes["width"].value) - 3; // let txt = find_child(e, "title").textContent.replace(/\([^(]*\)/, ""); let txt = find_child(e, "title").textContent.split(' (')[0]; t.attributes["x"].value = parseFloat(r.attributes["x"].value) + 3; // Smaller than this size won't fit anything if (w < 2 * 12 * 0.59) { t.textContent = ""; return; } t.textContent = txt; // Fit in full text width if (/^ *$/.test(txt) || t.getSubStringLength(0, txt.length) < w) return; for (let x = txt.length - 2; x > 0; x--) { if (t.getSubStringLength(0, x + 2) <= w) { t.textContent = txt.substring(0, x) + ".."; return; } } t.textContent = ""; } function zoom_reset(e) { if (e.attributes != undefined) { orig_load(e, "x"); orig_load(e, "width"); } if (e.childNodes == undefined) return; for (let i = 0, c = e.childNodes; i < c.length; i++) { zoom_reset(c[i]); } } function search(term, matchedtxt, searchbtn) { let re = new RegExp(term); let el = document.getElementsByTagName("g"); let matches = new Object(); let maxwidth = 0; for (let i = 0; i < el.length; i++) { let e = el[i]; if (e.attributes["class"].value != "func_g") continue; let func = g_to_func(e); let rect = find_child(e, "rect"); if (rect == null) { // the rect might be wrapped in an anchor // if nameattr href is being used if (rect = find_child(e, "a")) { rect = find_child(r, "rect"); } } if (func == null || rect == null) continue; // Save max width. Only works as we have a root frame let w = parseFloat(rect.attributes["width"].value); if (w > maxwidth) maxwidth = w; if (func.match(re)) { // highlight let x = parseFloat(rect.attributes["x"].value); orig_save(rect, "fill"); rect.attributes["fill"].value = "rgb(230,0,230)"; // remember matches if (matches[x] == undefined) { matches[x] = w; } else { if (w > matches[x]) { // overwrite with parent matches[x] = w; } } searching = 1; } } if (!searching) { matchedtxt.style["opacity"] = "1.0"; matchedtxt.firstChild.nodeValue = "Matched: none"; return; } searchbtn.style["opacity"] = "1.0"; searchbtn.firstChild.nodeValue = "Reset Search" // calculate percent matched, excluding vertical overlap let count = 0; let lastx = -1; let lastw = 0; let keys = Array(); for (let k in matches) { if (matches.hasOwnProperty(k)) keys.push(k); } // sort the matched frames by their x location // ascending, then width descending keys.sort(function (a, b) { return a - b; if (a < b || a > b) return a - b; return matches[b] - matches[a]; }); // Step through frames saving only the biggest bottom-up frames // thanks to the sort order. This relies on the tree property // where children are always smaller than their parents. for (let k in keys) { let x = parseFloat(keys[k]); let w = matches[keys[k]]; if (x >= lastx + lastw) { count += w; lastx = x; lastw = w; } } // display matched percent matchedtxt.style["opacity"] = "1.0"; let pct = 100 * count / maxwidth; if (pct == 100) pct = "100" else pct = pct.toFixed(1) matchedtxt.firstChild.nodeValue = "Matched: " + pct + "%"; } function reset_search() { var el = document.getElementsByTagName("rect"); for (var i = 0; i < el.length; i++) { orig_load(el[i], "fill") } } // flamegraph 颜色 const colorMap = (function () { function scalarReverse(s) { return s.split('').reverse().join('') } function nameHash(name) { let vector = 0 let weight = 1 let max = 1 let mod = 10 let ord name = name.replace(/.(.*?)`/, '') let splits = name.split('') for (let i = 0; i < splits.length; i++) { ord = splits[i].charCodeAt(0) % mod vector += (ord / (mod++ - 1)) * weight max += weight weight *= 0.70 if (mod > 12) break } return (1 - vector / max) } function color(type, hash, name) { let v1, v2, v3, r, g, b if (!type) return 'rgb(0, 0, 0)' if (hash) { v1 = nameHash(name) v2 = v3 = nameHash(scalarReverse(name)) } else { v1 = Math.random() + 1 v2 = Math.random() + 1 v3 = Math.random() + 1 } switch (type) { case 'hot': r = 205 + Math.round(50 * v3); g = 0 + Math.round(230 * v1); b = 0 + Math.round(55 * v2); return `rgb(${r}, ${g}, ${b})`; case 'mem': r = 0 g = 190 + Math.round(50 * v2) b = 0 + Math.round(210 * v1) return `rgb(${r}, ${g}, ${b})` case 'io': r = 80 + Math.round(60 * v1) g = r b = 190 + Math.round(55 * v2) return `rgb(${r}, ${g}, ${b})` default: throw new Error('Unknown type ' + type) } } function colorMap(paletteMap, colorTheme, hash, func) { if (paletteMap[func]) return paletteMap[func] paletteMap[func] = color(colorTheme, hash, func) return paletteMap[func] } return colorMap; })(); // 获取渲染的 context 信息 const contextify = (function () { function oneDecimal(x) { return (Math.round(x * 10) / 10) } function htmlEscape(s) { return s .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') } function contextify(parsed, opts) { let each = parsed.each; let time = parsed.time let timeMax = opts.timemax let ypadTop = opts.fontsize * 4 // pad top, include title let ypadBottom = opts.fontsize * 2 + 10 // pad bottom, include labels let xpad = 10 let xpad2 = opts.imagewidth * 0.82 let xpad3 = opts.imagewidth * 0.92 let depthMax = 0 let frameHeight = opts.frameheight let paletteMap = {} if (timeMax < time && timeMax / time > 0.02) { console.error('Specified timemax %d is less than actual total %d, so it will be ignored', timeMax, time) timeMax = Infinity } timeMax = Math.min(time, timeMax) let widthPerTime = (opts.imagewidth - 2 * xpad) / timeMax let minWidthTime = opts.minwidth / widthPerTime function markNarrowBlocks(nodes) { function mark(k) { let val = parsed.nodes[k] if (typeof val.stime !== 'number') throw new Error('Missing start for ' + k) if ((val.etime - val.stime) < minWidthTime) { val.narrow = true return } val.narrow = false depthMax = Math.max(val.depth, depthMax) } Object.keys(nodes).forEach(mark) } // NodeProcessor proto function processNode(node, index) { let func = node.func let depth = node.depth let etime = node.etime let stime = node.stime let factor = opts.factor let countName = opts.countname let isRoot = !func.length && depth === 0 if (isRoot) etime = timeMax let samples = Math.round((etime - stime * factor) * 10) / 10 let costTime = samples * each let samplesTxt = samples.toLocaleString() let pct let pctTxt let escapedFunc let name let sampleInfo if (isRoot) { name = 'all' sampleInfo = `(${samplesTxt} ${countName} ${utils.formatTime(costTime)}, 100%)` } else { pct = Math.round((100 * samples) / (timeMax * factor) * 10) / 10 pctTxt = pct.toLocaleString() escapedFunc = htmlEscape(func) name = escapedFunc sampleInfo = `(${samplesTxt} ${countName} ${utils.formatTime(costTime)}), ${pctTxt}%)` } let x1 = oneDecimal(xpad + stime * widthPerTime) let x2 = oneDecimal(xpad + etime * widthPerTime) let y1 = oneDecimal(imageHeight - ypadBottom - (depth + 1) * frameHeight + 1) let y2 = oneDecimal(imageHeight - ypadBottom - depth * frameHeight) let chars = (x2 - x1) / (opts.fontsize * opts.fontwidth) let showText = false let text if (chars >= 3) { // enough room to display function name? showText = true text = func.slice(0, chars) if (chars < func.length) text = text.slice(0, chars - 2) + '..' text = htmlEscape(text) } let rect_w = x2 - x1; let rect_h = y2 - y1; return { name: name , index: index , search: name.toLowerCase() , samples: sampleInfo , rect_x: x1 , rect_y: y1 , rect_w: rect_w , rect_h: rect_h , rect_fill: colorMap(paletteMap, opts.colors, opts.hash, func) , text: text , text_x: x1 + (showText ? 3 : 0) , text_y: 3 + (y1 + y2) / 2 , narrow: node.narrow , func: htmlEscape(func) } } function processNodes(nodes) { let keys = Object.keys(nodes) let acc = new Array(keys.length) for (let i = 0; i < keys.length; i++) { acc[i] = processNode(nodes[keys[i]], i) } return acc } markNarrowBlocks(parsed.nodes) let imageHeight = (depthMax * frameHeight) + ypadTop + ypadBottom let ctx = Object.assign({}, opts, { imageheight: imageHeight , xpad: xpad , xpad2: xpad2 , xpad3: xpad3 , titleX: opts.imagewidth / 2 , detailsY: imageHeight - (frameHeight / 2) , viewbox: `0 0 ${opts.imagewidth} ${imageHeight}` }) ctx.nodes = processNodes(parsed.nodes) return ctx } return contextify; })(); const utils = (function () { function formatTime(ts) { ts = !isNaN(ts) && ts || 0; let str = ''; if (ts < 1e3) { str = `${ts.toFixed(2)} ms`; } else if (ts < 1e3 * 60) { str = `${(ts / 1e3).toFixed(2)} s`; } else if (ts < 1e3 * 60 * 60) { str = `${(ts / (1e3 * 60)).toFixed(2)} min`; } else if (ts < 1e3 * 60 * 60 * 60) { str = `${(ts / (1e3 * 60 * 60)).toFixed(2)} h`; } else { str = `${ts.toFixed(2)} ms`; } return str; } return { formatTime }; })(); function narrowify(context, opts) { function processNode(n) { n.class = n.narrow ? 'hidden' : '' } function filterNode(n) { return !n.narrow } if (opts.removenarrows) context.nodes = context.nodes.filter(filterNode) else context.nodes.forEach(processNode) } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: mounted * @descript: 计算 svg 渲染数据 */ function mounted() { // 计算 svg 真实宽度 const imagewidth = this.$refs.svg.clientWidth; this.flamegraphData.fconfig.imagewidth = imagewidth; // 传输过程中 timemax 会丢失 this.flamegraphData.fconfig.timemax = Infinity; // 计算 svg 其余渲染数据 const context = contextify(this.flamegraphData.parsed, this.flamegraphData.fconfig); narrowify(context, this.flamegraphData.fconfig); this.data = context; } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: methods * @descript: 展示函数详情 */ function s(info) { this.show = 'Function: ' + info; } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: methods * @descript: 展示默认值 */ function c() { this.show = 'Easy-Monitor'; } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: methods * @descript: 放大点击处 */ function zoom(event) { let node = event.currentTarget; let index = node.attributes['node-index'].value; zoomclick = index; if (this.need_unzoom[index]) { unzoom.call(this); } let svg = document.getElementsByTagName("svg")[0]; let attr = find_child(node, "rect").attributes; let width = parseFloat(attr["width"].value); let xmin = parseFloat(attr["x"].value); let xmax = parseFloat(xmin + width); let ymin = parseFloat(attr["y"].value); // 计算倍率使用原来的 width let ratio = (svg.width.baseVal.value - 2 * 10) / parseFloat(attr["width"].value); let fudge = 0.0001; let unzoombtn = this.$refs.unzoom; unzoombtn.style["opacity"] = "1.0"; let el = document.getElementsByTagName("g"); let upstack; for (let i = 0; i < el.length; i++) { let e = el[i]; let ei = e.attributes['node-index'].value; let a = find_child(e, "rect").attributes; let ex = parseFloat(a["x"].value); let ew = parseFloat(a["width"].value); if (0 == 0) { upstack = parseFloat(a["y"].value) > ymin; } else { upstack = parseFloat(a["y"].value) < ymin; } if (upstack) { if (ex <= xmin && (ex + ew + fudge) >= xmax) { e.style["opacity"] = "0.5"; zoom_parent(e, svg); this.need_unzoom[e.attributes['node-index'].value] = true; update_text(e); } else e.style["display"] = "none"; } else { if (ex < xmin || ex + fudge >= xmax) { e.style["display"] = "none"; } else { zoom_child(e, xmin, ratio); this.need_unzoom[e.attributes['node-index'].value] = false; update_text(e); } } } } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: methods * @descript: 缩小点击 */ function unzoom() { let unzoombtn = this.$refs.unzoom; unzoombtn.style["opacity"] = "0.0"; let el = document.getElementsByTagName("g"); for (let i = 0; i < el.length; i++) { el[i].style["display"] = "block"; el[i].style["opacity"] = "1"; zoom_reset(el[i]); update_text(el[i]); } } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: methods * @descript: 鼠标置于搜索框上 */ function searchover(e) { this.$refs.search.style["opacity"] = "1.0"; } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: methods * @descript: 鼠标移开搜索框 */ function searchout(e) { let searchbtn = this.$refs.search; if (searching) { searchbtn.style["opacity"] = "1.0"; } else { searchbtn.style["opacity"] = "0.1"; } } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: search_prompt * @descript: 开始搜索 */ function search_prompt() { let searchbtn = this.$refs.search; let matchedtxt = this.$refs.matched; if (!searching) { let term = prompt("请输入需要查询的函数名: (允许输入正则表达式,例如: ^ext4_)", ""); if (term != null) { search(term, matchedtxt, searchbtn); } } else { reset_search(); searching = 0; searchbtn.style["opacity"] = "0.1"; searchbtn.firstChild.nodeValue = "Search" matchedtxt.style["opacity"] = "0.0"; matchedtxt.firstChild.nodeValue = ""; } } function set_parent_inf() { this.showBigPic ? this.$emit('hidePic') : this.$emit('changPic'); } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: computed * @descript: 函数节点展示 */ function nodes() { return this.data.nodes || []; } /** * @component: views/common/profiler/flamegraph.vue * @vue-data: watch * @descript: 缩放时进行处理 */ function showBigPic() { // 计算 svg 真实宽度 const imagewidth = this.$refs.svg.clientWidth; this.flamegraphData.fconfig.imagewidth = imagewidth; // 传输过程中 timemax 会丢失 this.flamegraphData.fconfig.timemax = Infinity; // 计算 svg 其余渲染数据 const context = contextify(this.flamegraphData.parsed, this.flamegraphData.fconfig); narrowify(context, this.flamegraphData.fconfig); this.data = context; unzoom.call(this); } //导出 flamegraph.vue 所需 export default { mounted, methods: { s, c, zoom, unzoom, searchover, searchout, search_prompt, set_parent_inf }, computed: { nodes }, watch: { showBigPic } }
// // Vivado(TM) // ISEWrap.js: Vivado Runs Script for WSH 5.1/5.6 // Copyright 1986-1999, 2001-2013,2015 Xilinx, Inc. All Rights Reserved. // // GLOBAL VARIABLES var ISEShell = new ActiveXObject( "WScript.Shell" ); var ISEFileSys = new ActiveXObject( "Scripting.FileSystemObject" ); var ISERunDir = ""; var ISELogFile = "runme.log"; var ISELogFileStr = null; var ISELogEcho = true; var ISEOldVersionWSH = false; // BOOTSTRAP ISEInit(); // // ISE FUNCTIONS // function ISEInit() { // 1. RUN DIR setup var ISEScrFP = WScript.ScriptFullName; var ISEScrN = WScript.ScriptName; ISERunDir = ISEScrFP.substr( 0, ISEScrFP.length - ISEScrN.length - 1 ); // 2. LOG file setup ISELogFileStr = ISEOpenFile( ISELogFile ); // 3. LOG echo? var ISEScriptArgs = WScript.Arguments; for ( var loopi=0; loopi<ISEScriptArgs.length; loopi++ ) { if ( ISEScriptArgs(loopi) == "-quiet" ) { ISELogEcho = false; break; } } // 4. WSH version check var ISEOptimalVersionWSH = 5.6; var ISECurrentVersionWSH = WScript.Version; if ( ISECurrentVersionWSH < ISEOptimalVersionWSH ) { ISEStdErr( "" ); ISEStdErr( "Warning: ExploreAhead works best with Microsoft WSH " + ISEOptimalVersionWSH + " or higher. Downloads" ); ISEStdErr( " for upgrading your Windows Scripting Host can be found here: " ); ISEStdErr( " http://msdn.microsoft.com/downloads/list/webdev.asp" ); ISEStdErr( "" ); ISEOldVersionWSH = true; } } function ISEStep( ISEProg, ISEArgs ) { // CHECK for a STOP FILE if ( ISEFileSys.FileExists(ISERunDir + "/.stop.rst") ) { ISEStdErr( "" ); ISEStdErr( "*** Halting run - EA reset detected ***" ); ISEStdErr( "" ); WScript.Quit( 1 ); } // WRITE STEP HEADER to LOG ISEStdOut( "" ); ISEStdOut( "*** Running " + ISEProg ); ISEStdOut( " with args " + ISEArgs ); ISEStdOut( "" ); // LAUNCH! var ISEExitCode = ISEExec( ISEProg, ISEArgs ); if ( ISEExitCode != 0 ) { WScript.Quit( ISEExitCode ); } } function ISEExec( ISEProg, ISEArgs ) { var ISEStep = ISEProg; if (ISEProg == "realTimeFpga" || ISEProg == "planAhead" || ISEProg == "vivado") { ISEProg += ".bat"; } var ISECmdLine = ISEProg + " " + ISEArgs; var ISEExitCode = 1; if ( ISEOldVersionWSH ) { // WSH 5.1 // BEGIN file creation ISETouchFile( ISEStep, "begin" ); // LAUNCH! ISELogFileStr.Close(); ISECmdLine = "%comspec% /c " + ISECmdLine + " >> " + ISELogFile + " 2>&1"; ISEExitCode = ISEShell.Run( ISECmdLine, 0, true ); ISELogFileStr = ISEOpenFile( ISELogFile ); } else { // WSH 5.6 // LAUNCH! ISEShell.CurrentDirectory = ISERunDir; // Redirect STDERR to STDOUT ISECmdLine = "%comspec% /c " + ISECmdLine + " 2>&1"; var ISEProcess = ISEShell.Exec( ISECmdLine ); // BEGIN file creation var wbemFlagReturnImmediately = 0x10; var wbemFlagForwardOnly = 0x20; var objWMIService = GetObject ("winmgmts:{impersonationLevel=impersonate, (Systemtime)}!//./root/cimv2"); var processor = objWMIService.ExecQuery("SELECT * FROM Win32_Processor", "WQL",wbemFlagReturnImmediately | wbemFlagForwardOnly); var computerSystem = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem", "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly); var NOC = 0; var NOLP = 0; var TPM = 0; var cpuInfos = new Enumerator(processor); for(;!cpuInfos.atEnd(); cpuInfos.moveNext()) { var cpuInfo = cpuInfos.item(); NOC += cpuInfo.NumberOfCores; NOLP += cpuInfo.NumberOfLogicalProcessors; } var csInfos = new Enumerator(computerSystem); for(;!csInfos.atEnd(); csInfos.moveNext()) { var csInfo = csInfos.item(); TPM += csInfo.TotalPhysicalMemory; } var ISEHOSTCORE = NOLP var ISEMEMTOTAL = TPM var ISENetwork = WScript.CreateObject( "WScript.Network" ); var ISEHost = ISENetwork.ComputerName; var ISEUser = ISENetwork.UserName; var ISEPid = ISEProcess.ProcessID; var ISEBeginFile = ISEOpenFile( "." + ISEStep + ".begin.rst" ); ISEBeginFile.WriteLine( "<?xml version=\"1.0\"?>" ); ISEBeginFile.WriteLine( "<ProcessHandle Version=\"1\" Minor=\"0\">" ); ISEBeginFile.WriteLine( " <Process Command=\"" + ISEProg + "\" Owner=\"" + ISEUser + "\" Host=\"" + ISEHost + "\" Pid=\"" + ISEPid + "\" HostCore=\"" + ISEHOSTCORE + "\" HostMemory=\"" + ISEMEMTOTAL + "\">" ); ISEBeginFile.WriteLine( " </Process>" ); ISEBeginFile.WriteLine( "</ProcessHandle>" ); ISEBeginFile.Close(); var ISEOutStr = ISEProcess.StdOut; var ISEErrStr = ISEProcess.StdErr; // WAIT for ISEStep to finish while ( ISEProcess.Status == 0 ) { // dump stdout then stderr - feels a little arbitrary while ( !ISEOutStr.AtEndOfStream ) { ISEStdOut( ISEOutStr.ReadLine() ); } WScript.Sleep( 100 ); } ISEExitCode = ISEProcess.ExitCode; } ISELogFileStr.Close(); // END/ERROR file creation if ( ISEExitCode != 0 ) { ISETouchFile( ISEStep, "error" ); } else { ISETouchFile( ISEStep, "end" ); } return ISEExitCode; } // // UTILITIES // function ISEStdOut( ISELine ) { ISELogFileStr.WriteLine( ISELine ); if ( ISELogEcho ) { WScript.StdOut.WriteLine( ISELine ); } } function ISEStdErr( ISELine ) { ISELogFileStr.WriteLine( ISELine ); if ( ISELogEcho ) { WScript.StdErr.WriteLine( ISELine ); } } function ISETouchFile( ISERoot, ISEStatus ) { var ISETFile = ISEOpenFile( "." + ISERoot + "." + ISEStatus + ".rst" ); ISETFile.Close(); } function ISEOpenFile( ISEFilename ) { // This function has been updated to deal with a problem seen in CR #870871. // In that case the user runs a script that runs impl_1, and then turns around // and runs impl_1 -to_step write_bitstream. That second run takes place in // the same directory, which means we may hit some of the same files, and in // particular, we will open the runme.log file. Even though this script closes // the file (now), we see cases where a subsequent attempt to open the file // fails. Perhaps the OS is slow to release the lock, or the disk comes into // play? In any case, we try to work around this by first waiting if the file // is already there for an arbitrary 5 seconds. Then we use a try-catch block // and try to open the file 10 times with a one second delay after each attempt. // Again, 10 is arbitrary. But these seem to stop the hang in CR #870871. // If there is an unrecognized exception when trying to open the file, we output // an error message and write details to an exception.log file. var ISEFullPath = ISERunDir + "/" + ISEFilename; if (ISEFileSys.FileExists(ISEFullPath)) { // File is already there. This could be a problem. Wait in case it is still in use. WScript.Sleep(5000); } var i; for (i = 0; i < 10; ++i) { try { return ISEFileSys.OpenTextFile(ISEFullPath, 8, true); } catch (exception) { var error_code = exception.number & 0xFFFF; // The other bits are a facility code. if (error_code == 52) { // 52 is bad file name or number. // Wait a second and try again. WScript.Sleep(1000); continue; } else { WScript.StdErr.WriteLine("ERROR: Exception caught trying to open file " + ISEFullPath); var exceptionFilePath = ISERunDir + "/exception.log"; if (!ISEFileSys.FileExists(exceptionFilePath)) { WScript.StdErr.WriteLine("See file " + exceptionFilePath + " for details."); var exceptionFile = ISEFileSys.OpenTextFile(exceptionFilePath, 8, true); exceptionFile.WriteLine("ERROR: Exception caught trying to open file " + ISEFullPath); exceptionFile.WriteLine("\tException name: " + exception.name); exceptionFile.WriteLine("\tException error code: " + error_code); exceptionFile.WriteLine("\tException message: " + exception.message); exceptionFile.Close(); } throw exception; } } } // If we reached this point, we failed to open the file after 10 attempts. // We need to error out. WScript.StdErr.WriteLine("ERROR: Failed to open file " + ISEFullPath); WScript.Quit(1); }
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_data_labels09.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'scatter'}) chart.axis_ids = [45740416, 45705856] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$B$1:$B$5', 'data_labels': {'value': 1, 'position': 'above'}, }) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$C$1:$C$5', 'data_labels': {'value': 1, 'position': 'below'}, }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
removeFeedbackButton(); var selectInput; function removeFeedbackButton() { if(document != null && document.body != null){ var linkElements = document.getElementsByTagName("a"); for(var i = 0; i < linkElements.length; i++) { var link = linkElements[i]; if (link.innerHTML.indexOf("馈") >= 0) { var parentDiv = link.parentNode; parentDiv.parentNode.removeChild(parentDiv); } } } }
export const content = ` export interface Item { id: String; name: String; value: String; } export interface Result { id: String; name: String; value: String; } `
import React from "react"; import Layout from "../../components/NewLayout"; import useCanonicalLinkMetaTag from "../../components/useCanonicalLinkMetaTag"; import ContactPageContent from "../../components/ContactPageContent"; const Index = () => { const canonicalLinkMetaTag = useCanonicalLinkMetaTag("/contact/"); return ( <Layout title="Contact"> {canonicalLinkMetaTag} <ContactPageContent /> </Layout> ); }; export default Index;
# !/usr/bin/evn python3 # -*- config: utf-8 -*- from functools import lru_cache import timeit @lru_cache(maxsize=24) def factorial(n): if n == 0: return 1 elif n == 1: return 1 else: return n * factorial(n - 1) @lru_cache(maxsize=24) def fib(n): if n == 0 or n == 1: return n else: return fib(n - 2) + fib(n - 1) if __name__ == '__main__': comm = int(input("Enter number> ")) r_fib = fib(comm) r_factorial = factorial(comm) print(timeit.timeit("r_factorial", setup="from __main__ import r_factorial")) print(timeit.timeit("r_fib", setup="from __main__ import r_fib"))
Java.perform(function() { var hook; var targetClass = 'java.lang.Enum'; //change your class here!! try{ console.log('[*] Getting Methods and Implementations of Class: ' + targetClass) console.log(" ") hook = Java.use(targetClass); } catch (err){ console.log('[Android] Hooking ' + targetClass + ' [\"Error\"] => ' + err); return; } var methods = hook.class.getDeclaredMethods(); hook.$dispose; methods.forEach(function(method) { console.log('[Android] ' + method) }); console.log('[*] Done!! Ctrl-C to Exit'); });
import React from 'react'; import { DataBox, FlexRow } from '../../Common'; import { Link } from 'react-router-dom'; const DoubleBakingEvidence = ({ op }) => { return ( <FlexRow> <Link to={`/${op.block}`}> <DataBox mr={40} title="Block" valueSize="14px" value={op.height} /> </Link> <Link to={`/cycle/${op.cycle}`}> <DataBox mr={40} title="Cycle" valueSize="14px" value={op.cycle} /> </Link> <DataBox mr={40} title="Date & Time" valueSize="14px" valueType="datetime" value={op.time} /> <DataBox mr={40} title="Burned" value={op.burned} valueSize="14px" valueType="currency-short" /> <DataBox mr={40} title="Reward" value={op.reward} valueSize="14px" valueType="currency-short" /> </FlexRow> ); }; export default DoubleBakingEvidence;
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for Custom Translate Dataset.""" import os from unittest import mock from tensorflow_datasets.core.folder_dataset import translate_folder import tensorflow_datasets.public_api as tfds _EXAMPLE_DIR = os.path.join( tfds.testing.test_utils.fake_examples_dir(), 'translate_folder') original_init = tfds.TranslateFolder.__init__ original_download_and_prepare = tfds.TranslateFolder.download_and_prepare def new_init(self, root_dir=None, **kwargs): assert root_dir is None del kwargs original_init(self, root_dir=_EXAMPLE_DIR) class TranslateFolderTests(tfds.testing.DatasetBuilderTestCase): """Translate dataset tests.""" DATASET_CLASS = tfds.TranslateFolder SPLITS = { 'train': 4, 'test': 4, 'val': 4, } @classmethod def setUpClass(cls): # pylint:disable = invalid-name super().setUpClass() super(TranslateFolderTests, cls).setUpClass() cls.DATASET_CLASS.__init__ = new_init cls.DATASET_CLASS.download_and_prepare = mock.Mock(return_value=None) @classmethod def tearDownClass(cls): # pylint:disable = invalid-name super().tearDownClass() cls.DATASET_CLASS.__init__ = original_init cls.DATASET_CLASS.download_and_prepare = original_download_and_prepare def test_registered(self): # Custom datasets shouldn't be registered self.assertNotIn(tfds.TranslateFolder.name, tfds.list_builders()) class TranslateFolderFunctionTest(tfds.testing.TestCase): """Tests for TranslateFolder functions.""" def test_properties(self): file_contents = { 'root_dir/lang1.train.txt': 'line1\nlang1', 'root_dir/lang2.train.txt': 'line1\nlang2', 'root_dir/lang3.train.txt': 'line1\nlang3', 'root_dir/lang1.val.txt': 'line1\nline2\n\nline4', 'root_dir/lang2.val.txt': 'line1\nline2\n\nline4', 'root_dir/lang3.val.txt': 'line1\nline2\n\nline4', 'root_dir/lang1.test.txt': 'line1', 'root_dir/lang2.test.txt': 'line1', } with tfds.testing.MockFs() as fs: for file in file_contents: fs.add_file(file, file_contents[file]) split_examples, langs = translate_folder._get_split_language_examples( 'root_dir') builder = tfds.TranslateFolder(root_dir='root_dir') self.assertEqual(split_examples, { 'train': { 'lang1': ['line1', 'lang1'], 'lang2': ['line1', 'lang2'], 'lang3': ['line1', 'lang3'], }, 'val': { 'lang1': ['line1', 'line2', '', 'line4'], 'lang2': ['line1', 'line2', '', 'line4'], 'lang3': ['line1', 'line2', '', 'line4'], }, 'test': { 'lang1': ['line1'], 'lang2': ['line1'], }, }) self.assertEqual(builder.info.splits['train'].num_examples, 2) self.assertEqual(builder.info.splits['val'].num_examples, 4) self.assertEqual(builder.info.splits['test'].num_examples, 1) expected_languages = [ 'lang1', 'lang2', 'lang3', ] self.assertEqual(expected_languages, langs) self.assertEqual(list(builder.info.features.keys()), expected_languages) if __name__ == '__main__': tfds.testing.test_main()
import sys import os sys.path.insert(1,os.getcwd()) #from perceiver_pytorch.multi_modality_perceiver import MultiModalityPerceiver, InputModality from private_test_scripts.perceivers.crossattnperceiver import MultiModalityPerceiver, InputModality import torch torch.multiprocessing.set_sharing_strategy('file_system') from datasets.mimic.get_data import get_dataloader trains1,valid1,test1=get_dataloader(7,imputed_path='/home/pliang/yiwei/im.pk',no_robust=True,batch_size=20,fracs=1) from datasets.avmnist.get_data import get_dataloader trains2,valid2,test2=get_dataloader('/home/pliang/yiwei/avmnist/_MFAS/avmnist',no_robust=True,unsqueeze_channel=False,to4by4=True,fracs=1) #from datasets.affect.get_data import get_simple_processed_data #trains3,valid3,test3=get_simple_processed_data('/home/pliang/yiwei/MultiBench/mosei_senti_data.pkl',fracs=1,repeats=1) #from private_test_scripts.perceivers.humorloader import get_dataloader #trains4,valid4,test4=get_dataloader(1,32,1) #trains4,valid4,test4=get_dataloader('/home/paul/MultiBench/mosi_raw.pkl',raw_path='/home/paul/MultiBench/mosi.hdf5',batch_size=3,no_robust=True) device='cuda:3' static_modality=InputModality( name='static', input_channels=1, input_axis=1, num_freq_bands=6, max_freq=1 ) timeseries_modality=InputModality( name='timeseries', input_channels=1, input_axis=2, num_freq_bands=6, max_freq=1 ) colorless_image_modality=InputModality( name='colorlessimage', input_channels=16, input_axis=2, num_freq_bands=6, max_freq=1 ) audio_spec_modality=InputModality( name='audiospec', input_channels=256, input_axis=2, num_freq_bands=6, max_freq=1 ) feature1_modality=InputModality( name='feature1', input_channels=35, input_axis=1, num_freq_bands=3, max_freq=1 ) feature2_modality=InputModality( name='feature2', input_channels=74, input_axis=1, num_freq_bands=3, max_freq=1 ) feature3_modality=InputModality( name='feature3', input_channels=300, input_axis=1, num_freq_bands=3, max_freq=1 ) feature4_modality=InputModality( name='feature4', input_channels=371, input_axis=1, num_freq_bands=3, max_freq=1 ) feature5_modality=InputModality( name='feature5', input_channels=81, input_axis=1, num_freq_bands=3, max_freq=1 ) for i in range(1): #""" model = MultiModalityPerceiver( modalities=(static_modality,timeseries_modality,colorless_image_modality,audio_spec_modality,feature1_modality,feature2_modality,feature3_modality,feature4_modality,feature5_modality), depth=1, # depth of net, combined with num_latent_blocks_per_layer to produce full Perceiver num_latents=20, # number of latents, or induced set points, or centroids. different papers giving it different names latent_dim=64, # latent dimension cross_heads=1, # number of heads for cross attention. paper said 1 latent_heads=6, # number of heads for latent self attention, 8 cross_dim_head=64, latent_dim_head=64, num_classes=1, # output number of classes attn_dropout=0., ff_dropout=0., #embed=True, weight_tie_layers=True, num_latent_blocks_per_layer=1, # Note that this parameter is 1 in the original Lucidrain implementation, cross_depth=1 ).to(device) model.to_logitslist=torch.nn.ModuleList([torch.nn.Sequential(torch.nn.LayerNorm(128),torch.nn.Linear(128,2)),torch.nn.Sequential(torch.nn.LayerNorm(128),torch.nn.Linear(128,10))]).to(device) from private_test_scripts.perceivers.train_structure_multitask import train records=train(model,55,[trains1,trains2],[valid1,valid2],[test1,test2],[['static','timeseries'],['colorlessimage','audiospec']],'private_test_scripts/perceivers/twotransfernew.pt',lr=0.0008,device=device,train_weights=[1.2,0.9],is_affect=[False,False],unsqueezing=[True,False],transpose=[False,False],evalweights=[1,1,1],start_from=0,weight_decay=0.001)
from sentiment import classifier from flask import session import pickle import requests import collections import json import pandas as pd import numpy as np def norm(v, r=[0,1]): m = max(v) diff = r[1] - r[0] return [r[0] + (diff*(item/float(m))) for item in v] # sentiment def _process_tweet(tweet): tweet = tweet.replace('/', '').split() return [w.lower() for w in tweet] def _tw_get_text(tweets): texts = [tweet['text'] for tweet in tweets] return map(_process_tweet, texts) def get_sent(tweets): tweets = _tw_get_text(tweets) sents = map(classifier.pos_neg_classify_sentence, tweets) return {'pos': norm([t['pos'] for t in sents]), 'neg': norm([t['neg'] for t in sents])} # # IDOL # IDOL_KEY = open('static/keys.txt', 'rb').readlines()[0].strip() # def idol_sentiment(text): # sent_endpoint = 'https://api.idolondemand.com/1/api/sync/analyzesentiment/v1' # payload = {'text': text, 'apikey': IDOL_KEY} # res = requests.get(sent_endpoint, params=payload) # return json.loads(res.content)['aggregate']['score'] # def get_sent(tweets): # tweets = _tw_get_text(tweets) # sents = map(idol_sentiment, tweets) # return " ".join(sents) # def sentiment_idol_action(text): # return {'name': 'analyzesentiment', # 'version': 'v1', # 'params': {'text': text, # 'apikey': IDOL_KEY} # } # def build_idol_actions(tweets): # texts = tw_get_text(tweets) # return map(sentiment_idol_action, texts) # def send_jobs(actions): # jobs_endpoint = 'https://api.idolondemand.com/1/job' # return requests.post(jobs_endpoint, data={'actions': actions}, params=IDOL_KEY).content # attention def get_attention(tweets): """Normalized measure of retweets/favorites for each tweet """ get_atten = lambda (t): t['retweet_count'] + t['favorite_count'] return norm(map(get_atten, tweets)) # tweet rate -> bpm def _avg_tweet_rate(tweets): dates = [t['created_at'] for t in tweets] dates =[pd.to_datetime(s).date() for s in dates] return dict(collections.Counter(dates)) def tweets_to_bpm(tweets): """ Returns a float in the range [80, 240] """ dates = _avg_tweet_rate(tweets) freq = dict(collections.Counter(dates)) print "converting tweet frequency to bpm..." bpm = np.mean(norm(freq.values(), r=[80,240])) return bpm def tw_get_timeline(twitter, token=None): resp = twitter.get("statuses/user_timeline.json?count=3400") if resp.status == 200: tweets = resp.data user = session['twitter_user'] # pickle.dump( tweets, open( user + "_timeline.p", "wb" ) ) else: return str(resp.status) return resp.data # jawbone def get_ticks(token, xid): "normalized ticks for a move!" headers = {'Authorization': 'Bearer ' + str(token)} res = requests.get('https://jawbone.com/nudge/api/v.1.1/moves/' + xid + '/ticks', headers=headers) return [t['distance'] for t in json.loads(res.content)['data']['items']] def jb_get_moves(jawbone, token=None): headers = {'Authorization': 'Bearer ' + str(token)} payload = {'start_time': 1380974114} res = requests.get('https://jawbone.com/nudge/api/v.1.1/users/@me/moves', headers=headers, params=payload) return json.loads(res.content)['data']['items'] def get_steps(jawbone, token=None): moves = jb_get_moves(jawbone, token) distances = [] for move in moves: distances.extend(get_ticks(token, move['xid'])) print "length of distances: ", len(distances) return norm(distances)
var cont="contact-us"; function infor(){ var name= document.getElementById("names").value; var text=document.getElementById("message").value; var email=document.getElementById("emails").value; if(name===""||email===""||text===""){ alert("Enter details"); } else{ alert("Thank you " + name + "we have recieved your message"); } } $(document).ready(function(){ $(".dev-con").click(function(){ $(".dev-img").toggle(function(){ $(".paragraph-dev").toggle(); }); }); }); $(document).ready(function(){ $(".design-con").click(function(){ $(".paragraph-des").toggle(function(){ $(".design-img").toggle(); }); }); }); $(document).ready(function(){ $(".product-con").click(function(){ $(".paragraph-prod").toggle(function(){ $(".prod-img").toggle(); }); }); });
import React from 'react' import { graphql } from 'gatsby' import Layout from '../components/Layout' import Helmet from 'react-helmet' import Container from '../components/Container' import CardList from '../components/CardList' import GhostPost from '../components/ghost-post' import PageTitle from '../components/PageTitle' import SEO from '../components/SEO' import config from '../utils/siteConfig' const Insights = ({ data }) => { const posts = data.allGhostPost.edges const postNode = { title: `Insights - ${config.siteTitle}`, } return ( <Layout> <Helmet> <title>{`Insights - ${config.siteTitle}`}</title> </Helmet> <SEO postNode={postNode} pagePath="insights" customTitle /> <Container> <CardList> {posts.map(({ node }) => { return ( <GhostPost key={node.id} post={node} /> ) })} </CardList> </Container> </Layout> ) } export const query = graphql` query { allGhostPost( sort: { fields: [published_at], order: DESC } ) { edges { node { id slug title plaintext feature_image custom_excerpt html published_at authors { id slug name } } } } } ` export default Insights
'use strict'; const {methodCallSelector} = require('./selectors/index.js'); const toLocation = require('./utils/to-location.js'); const MESSAGE_ID = 'no-console-spaces'; const messages = { [MESSAGE_ID]: 'Do not use {{position}} space between `console.{{method}}` parameters.', }; const methods = [ 'log', 'debug', 'info', 'warn', 'error', ]; const selector = methodCallSelector({ methods, minimumArguments: 1, object: 'console', }); // Find exactly one leading space, allow exactly one space const hasLeadingSpace = value => value.length > 1 && value.charAt(0) === ' ' && value.charAt(1) !== ' '; // Find exactly one trailing space, allow exactly one space const hasTrailingSpace = value => value.length > 1 && value.charAt(value.length - 1) === ' ' && value.charAt(value.length - 2) !== ' '; const create = context => { const sourceCode = context.getSourceCode(); const getProblem = (node, method, position) => { const index = position === 'leading' ? node.range[0] + 1 : node.range[1] - 2; const range = [index, index + 1]; return { loc: toLocation(range, sourceCode), messageId: MESSAGE_ID, data: {method, position}, fix: fixer => fixer.removeRange(range), }; }; return { * [selector](node) { const method = node.callee.property.name; const {arguments: messages} = node; const {length} = messages; for (const [index, node] of messages.entries()) { const {type, value} = node; if ( !(type === 'Literal' && typeof value === 'string') && type !== 'TemplateLiteral' ) { continue; } const raw = sourceCode.getText(node).slice(1, -1); if (index !== 0 && hasLeadingSpace(raw)) { yield getProblem(node, method, 'leading'); } if (index !== length - 1 && hasTrailingSpace(raw)) { yield getProblem(node, method, 'trailing'); } } }, }; }; module.exports = { create, meta: { type: 'suggestion', docs: { description: 'Do not use leading/trailing space between `console.log` parameters.', }, fixable: 'code', messages, }, };
'use strict' var test = require('tape') var u = require('unist-builder') var h = require('hastscript') var ok = require('.') test('hast-util-is-body-ok-link', function(t) { t.equal( ok(h('link', {itemProp: 'foo'})), true, 'yes - for `link`s with `itemProp`' ) t.equal( ok(h('link', {rel: ['prefetch'], href: '//example.com'})), true, 'yes - for `link`s with `rel[prefetch]`' ) t.equal( ok(h('link', {rel: ['stylesheet'], href: 'index.css'})), true, 'yes - for `link`s with `rel[stylesheet]`' ) t.equal( ok(h('link', {rel: ['pingback'], href: '//example.com'})), true, 'yes - for `link`s with `rel[pingback]`' ) t.equal( ok(h('link', {rel: ['author'], href: 'index.css'})), false, 'no - for `link`s with other rel’s' ) t.equal( ok(h('link', {rel: ['stylesheet', 'author'], href: 'index.css'})), false, 'no - for `link`s with combined rel’s' ) t.equal(ok(h('link')), false, 'no - for `link`s without `rel` or `itemProp`') t.equal( ok(u('element', {tagName: 'link'})), false, 'no - for `link`s without `rel` or `itemProp` (2)' ) t.equal(ok(h('p')), false, 'no - for non-links') t.equal(ok(u('text', 'foo')), false, 'no - for non-elements') t.end() })
module.exports = "Type ${type} does not exist for ${path}"
/* eslint-disable no-unused-vars */ // node fetch import const fetch = require('node-fetch'); // node redis import const redis = require('redis'); // client creation from redis const client = redis.createClient(); // Utility for Promises working with redis const { promisify } = require('util'); // const getAsync = promisify(client.get).bind(client); const setAsync = promisify(client.set).bind(client); // base Url that we will work with const baseURL = `https://jobs.github.com/positions.json`; let resultCount = 1; let onPage = 0; const allJobs = []; // fetch function to get jobs async function fetchGitHub() { while (resultCount > 0) { const res = await fetch(`${baseURL}?page=${onPage}`); const jobs = await res.json(); allJobs.push(...jobs); resultCount = jobs.length; console.log('got', resultCount, 'jobs'); onPage += 1; } // filter algo const // set in redis console.log('***************************************'); console.log('got a total of', allJobs.length, 'jobs'); console.log('***************************************'); const success = await setAsync('github', JSON.stringify(allJobs)); console.log(success); } module.exports = fetchGitHub;
module.exports = { prefix: '', important: false, separator: ':', theme: { screens: { sm: '640px', md: '768px', lg: '1024px', xl: '1280px', }, colors: { transparent: 'transparent', black: '#000', white: '#fff', gray: { 100: '#f7fafc', 200: '#edf2f7', 300: '#e2e8f0', 400: '#cbd5e0', 500: '#a0aec0', 600: '#718096', 700: '#4a5568', 800: '#2d3748', 900: '#1a202c', }, red: { 100: '#fff5f5', 200: '#fed7d7', 300: '#feb2b2', 400: '#fc8181', 500: '#f56565', 600: '#e53e3e', 700: '#c53030', 800: '#9b2c2c', 900: '#742a2a', }, orange: { 100: '#fffaf0', 200: '#feebc8', 300: '#fbd38d', 400: '#f6ad55', 500: '#ed8936', 600: '#dd6b20', 700: '#c05621', 800: '#9c4221', 900: '#7b341e', }, yellow: { 100: '#fffff0', 200: '#fefcbf', 300: '#faf089', 400: '#f6e05e', 500: '#ecc94b', 600: '#d69e2e', 700: '#b7791f', 800: '#975a16', 900: '#744210', }, green: { 100: '#f0fff4', 200: '#c6f6d5', 300: '#9ae6b4', 400: '#68d391', 500: '#48bb78', 600: '#38a169', 700: '#2f855a', 800: '#276749', 900: '#22543d', }, teal: { 100: '#e6fffa', 200: '#b2f5ea', 300: '#81e6d9', 400: '#4fd1c5', 500: '#38b2ac', 600: '#319795', 700: '#2c7a7b', 800: '#285e61', 900: '#234e52', }, blue: { 100: '#ebf8ff', 200: '#bee3f8', 300: '#90cdf4', 400: '#63b3ed', 500: '#4299e1', 600: '#3182ce', 700: '#2b6cb0', 800: '#2c5282', 900: '#2a4365', }, indigo: { 100: '#ebf4ff', 200: '#c3dafe', 300: '#a3bffa', 400: '#7f9cf5', 500: '#667eea', 600: '#5a67d8', 700: '#4c51bf', 800: '#434190', 900: '#3c366b', }, purple: { 100: '#faf5ff', 200: '#e9d8fd', 300: '#d6bcfa', 400: '#b794f4', 500: '#9f7aea', 600: '#805ad5', 700: '#6b46c1', 800: '#553c9a', 900: '#44337a', }, pink: { 100: '#fff5f7', 200: '#fed7e2', 300: '#fbb6ce', 400: '#f687b3', 500: '#ed64a6', 600: '#d53f8c', 700: '#b83280', 800: '#97266d', 900: '#702459', }, }, spacing: { px: '1px', '0': '0', '1': '0.25rem', '2': '0.5rem', '3': '0.75rem', '4': '1rem', '5': '1.25rem', '6': '1.5rem', '8': '2rem', '10': '2.5rem', '12': '3rem', '16': '4rem', '20': '5rem', '24': '6rem', '32': '8rem', '40': '10rem', '48': '12rem', '56': '14rem', '64': '16rem', }, backgroundColor: theme => theme('colors'), backgroundPosition: { bottom: 'bottom', center: 'center', left: 'left', 'left-bottom': 'left bottom', 'left-top': 'left top', right: 'right', 'right-bottom': 'right bottom', 'right-top': 'right top', top: 'top', }, backgroundSize: { auto: 'auto', cover: 'cover', contain: 'contain', }, borderColor: theme => ({ ...theme('colors'), default: theme('colors.gray.300', 'currentColor'), }), borderRadius: { none: '0', sm: '0.125rem', default: '0.25rem', md: '0.375rem', lg: '0.5rem', full: '9999px', }, borderWidth: { default: '1px', '0': '0', '2': '2px', '4': '4px', '8': '8px', }, boxShadow: { sm: '0 1px 2px 0 rgba(0, 0, 0, 0.04)', default: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)', md: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)', lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)', xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)', '2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)', inner: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)', outline: '0 0 0 3px rgba(66, 153, 225, 0.5)', none: 'none', }, container: {}, cursor: { auto: 'auto', default: 'default', pointer: 'pointer', wait: 'wait', text: 'text', move: 'move', 'not-allowed': 'not-allowed', }, fill: { current: 'currentColor', }, flex: { '1': '1 1 0%', auto: '1 1 auto', initial: '0 1 auto', none: 'none', }, flexGrow: { '0': '0', default: '1', }, flexShrink: { '0': '0', default: '1', }, fontFamily: { sans: [ 'Inter', '-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', 'Roboto', '"Helvetica Neue"', 'Arial', '"Noto Sans"', 'sans-serif', '"Apple Color Emoji"', '"Segoe UI Emoji"', '"Segoe UI Symbol"', '"Noto Color Emoji"', ], serif: ['Georgia', 'Cambria', '"Times New Roman"', 'Times', 'serif'], mono: ['Menlo', 'Monaco', 'Consolas', '"Liberation Mono"', '"Courier New"', 'monospace'], }, fontSize: { xs: '0.75rem', sm: '0.875rem', base: '1rem', lg: '1.125rem', xl: '1.25rem', '2xl': '1.5rem', '3xl': '1.875rem', '4xl': '2.25rem', '5xl': '3rem', '6xl': '4rem', }, fontWeight: { hairline: '100', thin: '200', light: '300', normal: '400', medium: '500', semibold: '600', bold: '700', extrabold: '800', black: '900', }, height: theme => ({ auto: 'auto', ...theme('spacing'), full: '100%', screen: '100vh', }), inset: { '0': '0', auto: 'auto', }, letterSpacing: { tighter: '-0.05em', tight: '-0.025em', normal: '0', wide: '0.025em', wider: '0.05em', widest: '0.1em', }, lineHeight: { none: '1', tight: '1.25', snug: '1.375', normal: '1.5', relaxed: '1.625', loose: '2', }, listStyleType: { none: 'none', disc: 'disc', decimal: 'decimal', }, margin: (theme, { negative }) => ({ auto: 'auto', ...theme('spacing'), ...negative(theme('spacing')), }), maxHeight: { full: '100%', screen: '100vh', }, maxWidth: (theme, { breakpoints }) => ({ none: 'none', xs: '20rem', sm: '24rem', md: '28rem', lg: '32rem', xl: '36rem', '2xl': '42rem', '3xl': '48rem', '4xl': '56rem', '5xl': '64rem', '6xl': '72rem', full: '100%', ...breakpoints(theme('screens')), }), minHeight: { '0': '0', full: '100%', screen: '100vh', }, minWidth: { '0': '0', full: '100%', }, objectPosition: { bottom: 'bottom', center: 'center', left: 'left', 'left-bottom': 'left bottom', 'left-top': 'left top', right: 'right', 'right-bottom': 'right bottom', 'right-top': 'right top', top: 'top', }, opacity: { '0': '0', '25': '0.25', '50': '0.5', '75': '0.75', '100': '1', }, order: { first: '-9999', last: '9999', none: '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '10': '10', '11': '11', '12': '12', }, padding: theme => theme('spacing'), placeholderColor: theme => theme('colors'), stroke: { current: 'currentColor', }, strokeWidth: { '0': '0', '1': '1', '2': '2', }, textColor: theme => theme('colors'), width: theme => ({ auto: 'auto', ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.666667%', '2/6': '33.333333%', '3/6': '50%', '4/6': '66.666667%', '5/6': '83.333333%', '1/12': '8.333333%', '2/12': '16.666667%', '3/12': '25%', '4/12': '33.333333%', '5/12': '41.666667%', '6/12': '50%', '7/12': '58.333333%', '8/12': '66.666667%', '9/12': '75%', '10/12': '83.333333%', '11/12': '91.666667%', full: '100%', screen: '100vw', }), zIndex: { auto: 'auto', '0': '0', '10': '10', '20': '20', '30': '30', '40': '40', '50': '50', }, gap: theme => theme('spacing'), rowGap: {}, columnGap: {}, gridTemplateColumns: { none: 'none', '1': 'repeat(1, minmax(0, 1fr))', '2': 'repeat(2, minmax(0, 1fr))', '3': 'repeat(3, minmax(0, 1fr))', '4': 'repeat(4, minmax(0, 1fr))', '5': 'repeat(5, minmax(0, 1fr))', '6': 'repeat(6, minmax(0, 1fr))', '7': 'repeat(7, minmax(0, 1fr))', '8': 'repeat(8, minmax(0, 1fr))', '9': 'repeat(9, minmax(0, 1fr))', '10': 'repeat(10, minmax(0, 1fr))', '11': 'repeat(11, minmax(0, 1fr))', '12': 'repeat(12, minmax(0, 1fr))', }, gridColumn: { auto: 'auto', 'span-1': 'span 1 / span 1', 'span-2': 'span 2 / span 2', 'span-3': 'span 3 / span 3', 'span-4': 'span 4 / span 4', 'span-5': 'span 5 / span 5', 'span-6': 'span 6 / span 6', 'span-7': 'span 7 / span 7', 'span-8': 'span 8 / span 8', 'span-9': 'span 9 / span 9', 'span-10': 'span 10 / span 10', 'span-11': 'span 11 / span 11', 'span-12': 'span 12 / span 12', }, gridColumnStart: { auto: 'auto', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '10': '10', '11': '11', '12': '12', '13': '13', }, gridColumnEnd: { auto: 'auto', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '10': '10', '11': '11', '12': '12', '13': '13', }, gridTemplateRows: {}, gridRow: {}, gridRowStart: {}, gridRowEnd: {}, transformOrigin: { center: 'center', top: 'top', 'top-right': 'top right', right: 'right', 'bottom-right': 'bottom right', bottom: 'bottom', 'bottom-left': 'bottom left', left: 'left', 'top-left': 'top left', }, scale: { '0': '0', '50': '.5', '75': '.75', '90': '.9', '95': '.95', '100': '1', '105': '1.05', '110': '1.1', '125': '1.25', '150': '1.5', }, rotate: { '-180': '-180deg', '-90': '-90deg', '-45': '-45deg', '0': '0', '45': '45deg', '90': '90deg', '180': '180deg', }, translate: (theme, { negative }) => ({ ...theme('spacing'), ...negative(theme('spacing')), '-full': '-100%', '-1/2': '-50%', '1/2': '50%', full: '100%', }), skew: {}, transitionProperty: { none: 'none', all: 'all', default: 'background-color, border-color, color, opacity, transform', colors: 'background-color, border-color, color', opacity: 'opacity', transform: 'transform', }, transitionTimingFunction: { linear: 'linear', in: 'cubic-bezier(0.4, 0, 1, 1)', out: 'cubic-bezier(0, 0, 0.2, 1)', 'in-out': 'cubic-bezier(0.4, 0, 0.2, 1)', }, transitionDuration: { '75': '75ms', '100': '100ms', '150': '150ms', '200': '200ms', '300': '300ms', '500': '500ms', '700': '700ms', '1000': '1000ms', }, }, variants: { accessibility: ['responsive', 'focus'], alignContent: ['responsive'], alignItems: ['responsive'], alignSelf: ['responsive'], appearance: ['responsive'], backgroundAttachment: ['responsive'], backgroundColor: ['responsive', 'hover', 'focus'], backgroundPosition: ['responsive'], backgroundRepeat: ['responsive'], backgroundSize: ['responsive'], borderCollapse: ['responsive'], borderColor: ['responsive', 'hover', 'focus'], borderRadius: ['responsive'], borderStyle: ['responsive'], borderWidth: ['responsive'], boxShadow: ['responsive', 'hover', 'focus'], boxSizing: ['responsive'], cursor: ['responsive'], display: ['responsive'], fill: ['responsive'], flex: ['responsive'], flexDirection: ['responsive'], flexGrow: ['responsive'], flexShrink: ['responsive'], flexWrap: ['responsive'], float: ['responsive'], clear: ['responsive'], fontFamily: ['responsive'], fontSize: ['responsive'], fontSmoothing: ['responsive'], fontStyle: ['responsive'], fontWeight: ['responsive', 'hover', 'focus'], height: ['responsive'], inset: ['responsive'], justifyContent: ['responsive'], letterSpacing: ['responsive'], lineHeight: ['responsive'], listStylePosition: ['responsive'], listStyleType: ['responsive'], margin: ['responsive'], maxHeight: ['responsive'], maxWidth: ['responsive'], minHeight: ['responsive'], minWidth: ['responsive'], objectFit: ['responsive'], objectPosition: ['responsive'], opacity: ['responsive', 'hover', 'focus'], order: ['responsive'], outline: ['responsive', 'focus'], overflow: ['responsive'], padding: ['responsive'], placeholderColor: ['responsive', 'focus'], pointerEvents: ['responsive'], position: ['responsive'], resize: ['responsive'], stroke: ['responsive'], strokeWidth: ['responsive'], tableLayout: ['responsive'], textAlign: ['responsive'], textColor: ['responsive', 'hover', 'focus'], textDecoration: ['responsive', 'hover', 'focus'], textTransform: ['responsive'], userSelect: ['responsive'], verticalAlign: ['responsive'], visibility: ['responsive'], whitespace: ['responsive'], width: ['responsive'], wordBreak: ['responsive'], zIndex: ['responsive'], gap: ['responsive'], columnGap: ['responsive'], rowGap: ['responsive'], gridAutoFlow: ['responsive'], gridTemplateColumns: ['responsive'], gridColumn: ['responsive'], gridColumnStart: ['responsive'], gridColumnEnd: ['responsive'], gridTemplateRows: ['responsive'], gridRow: ['responsive'], gridRowStart: ['responsive'], gridRowEnd: ['responsive'], transform: ['responsive'], transformOrigin: ['responsive'], scale: ['responsive', 'hover', 'focus'], rotate: ['responsive', 'hover', 'focus'], translate: ['responsive', 'hover', 'focus'], skew: ['responsive', 'hover', 'focus'], transitionProperty: ['responsive'], transitionTimingFunction: ['responsive'], transitionDuration: ['responsive'], }, corePlugins: {}, plugins: [], }
import request from './request'; const extractData = res => res.data.data; function fetch(params) { return request.get('/users', { params }).then(extractData); } function upsert(data) { return request.post('/users', data).then(extractData); } function remove({ id }) { return request.delete(`/users/${id}`); } function reinvite({ id }) { return request.post(`/users/${id}/reinvite`); } export default { fetch, upsert, remove, reinvite };
import React from "react"; import "./host_info.scss"; import data from "./host_info.json"; import QqImg from './img/qq.jpg'; import WechatImg from './img/wechat.jpg'; class HostInfo extends React.Component { quickCodeMap = { 'qq': QqImg, 'wechat': WechatImg } render() { return( <div id="host_info"> <div class="back"> <div class="head_img"></div> </div> <div class="info"> <div class="intro"> <h1>世幻水</h1> 生而为人 <br/> 我很抱歉 <br/> </div> <div class="contacts"> {data.contacts.map( item => <a className ={item.name + " contact"} href={item.url?item.url:"javascript:void(0);"} target={item.url?"blank":"_self"} rel="nofollow"> {item.qcode && <div style={{backgroundImage:`url(${this.quickCodeMap[item.name]})`}}></div>} </a>)} </div> </div> </div> ) } } export default HostInfo;
import numpy as np from .skeleton import Environment class Gridworld(Environment): """ The Gridworld as described in the lecture notes of the 687 course material. Actions: up (0), right (1), down (2), left (3), Environment Dynamics: With probability 0.8 the robot moves in the specified direction. With probability 0.05 it gets confused and veers to the right -- it moves +90 degrees from where it attempted to move, e.g., with probability 0.05, moving up will result in the robot moving right. With probability 0.05 it gets confused and veers to the left -- moves -90 degrees from where it attempted to move, e.g., with probability 0.05, moving right will result in the robot moving down. With probability 0.1 the robot temporarily breaks and does not move at all. If the movement defined by these dynamics would cause the agent to exit the grid (e.g., move up when next to the top wall), then the agent does not move. The robot starts in the top left corner, and the process ends in the bottom right corner. Rewards: -10 for entering the state with water +10 for entering the goal state 0 everywhere else """ def __init__(self, startState=0, endState=24, shape=(5,5), obstacles=[12, 17], waterStates=[6, 18, 22]): self._name = "Gridworld" self.startState = startState self.endState = endState self.shape = shape self.obstacles = obstacles self.waterStates = waterStates self._state = startState self._action = -1 # no action taken yet self._reward = 0 # no reward yet self._gamma = 0.9 self.gamma_coeff = 1 self.t = 0 self.maxT = 100000 @property def name(self) -> str: return self._name @property def reward(self) -> float: return self._reward @property def action(self) -> int: return self._action @property def isEnd(self) -> bool: return self.t == self.maxT or self._state == self.endState @property def state(self) -> np.ndarray: return self._state @property def gamma(self) -> float: return self._gamma def step(self, action): p = np.random.random_sample() # veer right with prob 0.05 actual_action = action if p < 0.05: actual_action = (action+1)%4 # veer left with prob 0.05 elif p < 0.1: actual_action = (action-1)%4 # stay there with prob 0.1 elif p < 0.2: actual_action = -1 # move up if possible if (actual_action == 0): new_state = self._state - self.shape[1] if (new_state >= 0 and new_state not in self.obstacles): self._state = new_state # move right if possible elif (actual_action == 1): new_state = self._state + 1 if (self._state%5 != 4 and new_state not in self.obstacles): self._state = new_state # move down if possible elif (actual_action == 2): new_state = self._state + self.shape[1] if (new_state < 25 and new_state not in self.obstacles): self._state = new_state # move left if possible elif (actual_action == 3): new_state = self._state - 1 if (self._state%5 != 0 and new_state not in self.obstacles): self._state = new_state self._action = action # Update A_t self._reward = self.gamma_coeff * self.R(self._state) # Update R_t self.gamma_coeff *= self._gamma self.t += 1 return (actual_action, self._state, self._reward) def reset(self): self._state = self.startState self._action = -1 # no action taken yet self._reward = 0 # no reward yet self._gamma = 0.9 self.gamma_coeff = 1 self.t = 0 def R(self, _state): """ reward function output: reward -- the reward resulting in the agent being in a particular state """ if _state == self.endState: self._reward = 10 elif _state in self.waterStates: self._reward = -10 else: self._reward = 0 return self._reward
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GLES2 import _types as _cs # End users want this... from OpenGL.raw.GLES2._types import * from OpenGL.raw.GLES2 import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GLES2_INTEL_framebuffer_CMAA' def _f( function ): return _p.createFunction( function,_p.PLATFORM.GLES2,'GLES2_INTEL_framebuffer_CMAA',error_checker=_errors._error_checker) @_f @_p.types(None,) def glApplyFramebufferAttachmentCMAAINTEL():pass
// Copyright (c) 2022 Uber Technologies, Inc. // // 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. import React from 'react'; import PropTypes from 'prop-types'; import {useIntl} from 'react-intl'; import {FormattedMessage} from 'localization'; import {Tooltip} from './styled-components'; import {Docs} from 'components/common/icons'; import styled from 'styled-components'; import {camelize} from 'utils/utils'; const StyledInfoHelper = styled.div` align-items: center; margin-left: 10px; color: ${props => props.theme.labelColor}; display: inline-flex; .info-helper__content { width: ${props => (props.width ? `${props.width}px` : 'auto')}; max-width: ${props => (props.width ? 'auto' : '100px')}; } :hover { cursor: pointer; color: ${props => props.theme.textColorHl}; } `; function InfoHelperFactory() { const propTypes = { description: PropTypes.string.isRequired, containerClass: PropTypes.string }; const InfoHelper = ({description, property, containerClass, width, id}) => { // TODO: move intl out const intl = useIntl(); return ( <StyledInfoHelper className={`info-helper ${containerClass || ''}`} width={width} data-tip data-for={id} > <Docs height="16px" /> <Tooltip id={id} effect="solid"> <div className="info-helper__content"> {description && ( <FormattedMessage id={description} defaultValue={description} values={{ property: intl.formatMessage({ id: property ? `property.${camelize(property)}` : 'misc.empty' }) }} /> )} </div> </Tooltip> </StyledInfoHelper> ); }; InfoHelper.propTypes = propTypes; return InfoHelper; } export default InfoHelperFactory;
import sqlite3 import copy from xml.etree import ElementTree import xml.dom.minidom import traceback import globals class WuComponent: def __init__(self, component_index, location, group_size, reaction_time, type, application_hashed_name, properties=None): self.index = component_index self.location = location self.group_size = group_size # int self.reaction_time = reaction_time # float self.type = type # wuclass name self.application_hashed_name = application_hashed_name self.properties = properties #properties without default values if self.properties == None: self.properties = [] self.deployid = -1 #temporary id, only used for generating wkpfdeploy.xml self.instances = [] # WuObjects allocated on various Nodes after mapping self.message = "" self.heartbeatgroups = [] class WuLink: def __init__(self, from_component, from_property_name, to_component, to_property_name): self.from_component = from_component self.from_property_name = from_property_name self.from_property = WuObjectFactory.wuclassdefsbyname[from_component.type].properties[from_property_name] self.to_component = to_component self.to_property_name = to_property_name self.to_property = WuObjectFactory.wuclassdefsbyname[to_component.type].properties[to_property_name] ########### in db ##################### class WuObjectFactory: wutypedefs = {} wuclassdefsbyid = {} wuclassdefsbyname = {} #property_values, a dictionary of property_name: value pairs, may not contain all properties, default will be used in that case @classmethod def createWuObject(cls, wuclassdef, wunode, port_number, virtual, property_values=None): wuobj = WuObject( wuclassdef, wunode, port_number, virtual, property_values) wunode.wuobjects[port_number] = wuobj return wuobj @classmethod def removeWuObject(cls,wunode, port_number): del wunode.wuobjects[port_number] return True @classmethod def createWuPropertyDef(cls, id, name, wutype_name, default_value, access, wuclassdef): wutype = None if wutype_name in cls.wutypedefs.keys(): wutype = cls.wutypedefs[wutype_name] if wutype == None: print ("wutype", wutype_name, "does not exist") wuprop = WuPropertyDef(id, name, wutype, default_value, access, wuclassdef) wuclassdef.properties[name]=wuprop return wuprop @classmethod def createWuTypeDef(cls, name, type,values=None): cls.wutypedefs[name] = WuTypeDef(name,type,values) return cls.wutypedefs[name] @classmethod def createWuClassDef(cls, id, name, virtual, type, properties = None): cls.wuclassdefsbyid[id] = WuClassDef( id, name, virtual, type, properties) cls.wuclassdefsbyname[name] = cls.wuclassdefsbyid[id] return cls.wuclassdefsbyname[name] class WuClassDef: # Maintaining an ordered list for save function #properties, a dictionary of name:wupropertydef def __init__(self, id, name, virtual, type, properties = None): self.id = id self.name = name self.virtual = virtual self.type = type self.properties = properties #dictionary of wuproperties if self.properties == None: self.properties = {} def createWuProperty(self, name, default_value, wutype, access, wuclassdef): self.properties[name] = WuPropertyDef(id, name, default_value, wutype, access, self) return self.wuproperties[name] class WuPropertyDef: def __init__(self, id, name,wutype, default_value, access, wuclassdef): self.id = id self.name = name self.value = default_value self.wutype = wutype self.access = access self.wuclassdef = wuclassdef class WuTypeDef: #values is a list of values def __init__(self, name, type,values=None): self.name = name self.wutype = type self.values = values if self.values == None: self.values = [] # Network info class WuNode: node_dict = {} locations = {} def __init__(self, id, location, wuclassdefs=None, wuobj=None,energy=100.0,type='wudevice'): self.id = id if location == None: try: self.location = WuNode.locations[id] except: self.location = 'WuKong' else: self.location = location self.wuclasses = wuclassdefs #wuclasses[id] self.wuobjects = wuobj #wuobjects[port] if self.wuclasses == None: self.wuclasses = {} if self.wuobjects == None: self.wuobjects = {} self.energy = energy self.type = type WuNode.node_dict[id] = self def dump(self): stri = '' stri += "id:"+str(self.id)+'\n' stri += "location:"+ self.location+'\n' stri += "wuclasses:" +str(self.wuclasses)+'\n' stri += "wuobjects"+str(self.wuobjects)+'\n' stri += "type:"+self.type+'\n' return stri @staticmethod def addVirtualNodes(nodes): WuNode.node_dict = dict(WuNode.node_dict.items() + nodes.items()) return @staticmethod def getAllWuNodes(): return WuNode.node_dict.values() @classmethod def dumpXML(cls): root = ElementTree.Element('Nodes') for id, node in cls.node_dict.items(): node_element = ElementTree.SubElement(root, 'Node') node_element.attrib['id'] = str(id) node_element.attrib['type'] = str(node.type) location_element = ElementTree.SubElement(node_element, "Location") location_element.attrib['length'] = str(len(node.location)) location_element.attrib['content'] = str(node.location) wuclasslist_element = ElementTree.SubElement(node_element,"WuClassList") wuclasslist_element.attrib['length'] = str(len(node.wuclasses)) for wuclassid, wuclass in node.wuclasses.items(): wuclass_element = ElementTree.SubElement(wuclasslist_element,"WuCLass") wuclass_element.attrib['id'] = str(wuclassid) wuclass_element.attrib['virtual'] = str(wuclass.virtual) wuobjectlist_element = ElementTree.SubElement(node_element,"WuObjectList") for port, wuobject in node.wuobjects.items(): wuobject_element = ElementTree.SubElement(wuobjectlist_element,"WuObject") wuobject_element.attrib['id'] = str(wuobject.wuclassdef.id) wuobject_element.attrib['virtual'] = str(wuobject.virtual) wuobject_element.attrib['port'] = str(port) # for prop_name, prop_value in wuobject.properties.items(): # wuproperty_element = ElementTree.SubElement(wuobject_element,"WuProperty") # wuproperty_element.attrib['name'] = str(prop_name) # wuproperty_element.attrib['value'] = str(prop_value) #for more human readable xml rough_stri = ElementTree.tostring(root, 'utf-8') xml_content = xml.dom.minidom.parseString(rough_stri) pretty_stri = xml_content.toprettyxml() return pretty_stri @classmethod def findById(cls, id): if id in cls.node_dict.keys(): return cls.node_dict[id] return None @classmethod def saveNodes(cls, filename="../LocalData/nodes.xml"):#for debug now, will expand to support reconstructing nodes from the dump ---- Sen fin = open(filename,"w") fin.write( WuNode.dumpXML()) fin.close() WuNode.locations={} for id in WuNode.node_dict: WuNode.locations[id] = WuNode.node_dict[id].location return @classmethod def clearNodes(cls, filename="../LocalData/nodes.xml"): cls.node_dict = {} fin = open(filename,"w") fin.write("") fin.close() return @classmethod def loadNodes(cls, filename="../LocalData/nodes.xml"):#for debug now, will expand to support reconstructing nodes from the dump ---- Sen print ('[loadNodes in models] Loading node from file', filename) try: fin = open(filename,"r") nodedom = xml.dom.minidom.parse(filename) except Exception: print (filename,'does not exist, initial list is empty!') return cls.node_dict.values() nodes = nodedom.getElementsByTagName("Node") for node_ele in nodes: nodeid = int(node_ele.getAttribute("id")) nodetype = node_ele.getAttribute("type") wuclasses = {} wuobjects = {} location = '' node = WuNode(nodeid, location, wuclasses, wuobjects,type=nodetype) #note: wuclasses, pass by reference, change in original list is also change in node if node_ele.hasChildNodes(): for prop_ele in node_ele.childNodes: if prop_ele.nodeType != prop_ele.ELEMENT_NODE: continue if prop_ele.tagName == "Location": node.location = prop_ele.getAttribute("content") WuNode.locations[nodeid] = node.location if prop_ele.tagName == "WuClassList": for wuclass_ele in prop_ele.childNodes: if wuclass_ele.nodeType != wuclass_ele.ELEMENT_NODE: continue wuclass_id = int(wuclass_ele.getAttribute("id"), 0) virtual = True if wuclass_ele.getAttribute("virtual").lower()=="true" else False try: wuclassdef = WuObjectFactory.wuclassdefsbyid[wuclass_id] except KeyError: print '[loadNodes in models] Unknown wuclass id', wuclass_id print ('[loadNodes in models] Invalid saved discover input file', filename) return wuclasses[wuclass_id] = wuclassdef if prop_ele.tagName == "WuObjectList": for wuobj in prop_ele.childNodes: if wuobj.nodeType != wuobj.ELEMENT_NODE: continue port_number = int(wuobj.getAttribute("port"), 0) wuclass_id = int(wuobj.getAttribute("id"), 0) virtual = True if wuobj.getAttribute("virtual").lower()=="true" else False try: wuclassdef = WuObjectFactory.wuclassdefsbyid[wuclass_id] except KeyError: print '[loadNodes in models] Unknown wuclass id', wuclass_id print ('[loadNodes in models] Invalid saved discover input file', filename) return wuobject = WuObjectFactory.createWuObject(wuclassdef, node, port_number, virtual) # for wuprop in wuobj.childNodes: # if wuobj.nodeType != wuobj.ELEMENT_NODE: # continue # prop_name = wuprop.getAttribute("name") # prop_value = int(wuprop.getAttribute("value"),0) # wuobject.properties[prop_name] = prop_value #add the virtual nodes cls.node_dict = dict(cls.node_dict.items() + globals.virtual_nodes.items()) return cls.node_dict.values() def isResponding(self): return len(self.wuclasses) > 0 or len(self.wuobjects) > 0 class WuObject: ZWAVE_SWITCH_PORT = 64 def __init__(self, wuclassdef, wunode, port_number, virtual, property_values = None): self.port_number = port_number self.wuclassdef = wuclassdef self.wunode = wunode self.virtual = virtual self.created = False self.mapped = False #self-identify if a wuobject is mapped, set to True in mapper self.properties = wuclassdef.properties if property_values == None: property_values = {} for prop_name, prop_value in property_values: wuprop = self.wuclassdef.wuproperties[prop_name] new_wuprop = copy.deepcopy(wuprop) new_wuprop.value = prop_value self.properties[prop_name] = new_wuprop def getPropertyByName(self, name): return property_values[name]
'use strict'; let { T_VARIABLE, T_ATOM } = require('./const'); let { checkAST, runTimeCheck, getVariable, validateParamsInRunTime } = require('./stub'); let parser = require('./parser'); let executeAST = (mid, variableMap = {}, { variableStub = {}, skipCheck } = {}) => { if (!skipCheck) { runTimeCheck(variableStub, variableMap); } let root = { mid }; let stack = [root], traceTable = []; while (stack.length) { let top = stack[stack.length - 1]; let topMid = top.mid; let midType = topMid.type; if (midType === T_ATOM) { top.value = topMid.value; traceTable.push(stack.pop()); } else if (midType === T_VARIABLE) { top.value = getVariable(topMid.name, variableMap, variableStub); traceTable.push(stack.pop()); } else { // function if (!top.visited) { top.visited = true; // push params let params = topMid.params; let paramLen = params.length; for (let i = 0; i < paramLen; i++) { stack.push({ mid: params[i] }); } } else { let name = topMid.name; let fun = getVariable(name, variableMap, variableStub); // fetch params let paramValues = []; let paramLen = topMid.params.length; let traceTableLen = traceTable.length; let stopPos = traceTableLen - paramLen; for (let i = traceTableLen - 1; i >= stopPos; i--) { paramValues.push(traceTable.pop().value); } // validate params before run function validateParamsInRunTime(name, paramValues, variableStub); // run function top.value = fun(...paramValues); traceTable.push(stack.pop()); } } } return root.value; }; let parseStrToAst = (str) => { let handleChunk = parser(); if (str) { handleChunk(str); } return handleChunk(null); }; module.exports = { parser, parseStrToAst, executeAST, checkAST };
module.exports = { extends: '@parcel/eslint-config', parser: '@babel/eslint-parser', parserOptions: { ecmaVersion: 5, }, env: { browser: true, }, rules: { 'no-console': 'off', 'no-global-assign': 'warn', 'no-unused-vars': 'off', }, };
from selenium.webdriver.support.ui import Select from model.project import Project class ProjectHelper: def __init__(self, app): self.app = app def open_manage_projects_page(self): wd = self.app.wd wd.get("http://localhost/mantisbt-1.2.20/manage_proj_page.php") def open_add_project_page(self): wd = self.app.wd self.open_manage_projects_page() if not wd.current_url.endswith("/manage_proj_create_page.php"): wd.find_element_by_xpath("//input[@value='Create New Project']").click() self.implicitly_wait(3) def create_project(self, project): wd = self.app.wd self.open_add_project_page() self.fill_project_form(project) # submit project creation wd.find_element_by_xpath("//input[@value='Add Project']").click() self.implicitly_wait(5) def fill_project_form(self, project): wd = self.app.wd self.change_field_value("name", project.name) self.select_dropdown_value("status", project.status) self.select_dropdown_value("view_state", project.view_state) self.change_field_value("description", project.description) self.implicitly_wait(1) def change_field_value(self, field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(field_name).clear() wd.find_element_by_name(field_name).send_keys(text) def select_dropdown_value(self, field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() Select(wd.find_element_by_name(field_name)).select_by_visible_text(text) # wd.find_element_by_link_text(text).click() def delete_project_by_id(self, id): wd = self.app.wd self.open_manage_projects_page() self.select_project_by_id(id) self.implicitly_wait(1) # confirm Delete action # self.accept_next_alert = True wd.find_element_by_xpath("//input[@value='Delete Project']").click() wd.find_element_by_xpath("//input[@value='Delete Project']").click() self.project_cache = None self.implicitly_wait(2) def select_project_by_id(self, id): wd = self.app.wd wd.find_element_by_xpath("//a[@href='manage_proj_edit_page.php?project_id=%s']" % id).click() project_cache = None def get_project_list(self): wd = self.app.wd self.open_manage_projects_page() self.project_cache = [] all_tables = wd.find_elements_by_xpath("//table[@class='width100']") table = all_tables[1] rows = table.find_elements_by_xpath(".//tr[contains(@class, 'row')]") del rows[0] for element in rows: cells = element.find_elements_by_tag_name("td") name = cells[0].text description_text = cells[4].text id_link = wd.find_element_by_link_text(name).get_attribute("href") id_index = id_link.index('=') + 1 id = id_link[id_index:] self.project_cache.append(Project(id=id, name=name, description=description_text)) return list(self.project_cache) def implicitly_wait(self, param): pass
/** * @class Ext.util.AbstractMixedCollection * @private */ Ext.define('Ext.util.AbstractMixedCollection', { requires: ['Ext.util.Filter'], mixins: { observable: 'Ext.util.Observable' }, /** * @property {Boolean} isMixedCollection * `true` in this class to identify an object as an instantiated MixedCollection, or subclass thereof. */ isMixedCollection: true, /** * @private Mutation counter which is incremented upon add and remove. */ generation: 0, constructor: function(allowFunctions, keyFn) { var me = this; me.items = []; me.map = {}; me.keys = []; me.length = 0; /** * @event clear * Fires when the collection is cleared. * @since Ext 1 */ /** * @event add * Fires when an item is added to the collection. * @param {Number} index The index at which the item was added. * @param {Object} o The item added. * @param {String} key The key associated with the added item. * @since Ext 1 */ /** * @event replace * Fires when an item is replaced in the collection. * @param {String} key he key associated with the new added. * @param {Object} old The item being replaced. * @param {Object} new The new item. * @since Ext 1 */ /** * @event remove * Fires when an item is removed from the collection. * @param {Object} o The item being removed. * @param {String} key (optional) The key associated with the removed item. * @since Ext 1 */ me.allowFunctions = allowFunctions === true; if (keyFn) { me.getKey = keyFn; } me.mixins.observable.constructor.call(me); }, /** * @cfg {Boolean} allowFunctions Specify <code>true</code> if the {@link #addAll} * function should add function references to the collection. Defaults to * <code>false</code>. * @since Ext 3 */ allowFunctions : false, /** * Adds an item to the collection. Fires the {@link #event-add} event when complete. * * @param {String/Object} key The key to associate with the item, or the new item. * * If a {@link #getKey} implementation was specified for this MixedCollection, * or if the key of the stored items is in a property called `id`, * the MixedCollection will be able to *derive* the key for the new item. * In this case just pass the new item in this parameter. * * @param {Object} [o] The item to add. * * @return {Object} The item added. * @since Ext 1 */ add : function(key, obj){ var me = this, myObj = obj, myKey = key, old; if (arguments.length == 1) { myObj = myKey; myKey = me.getKey(myObj); } if (typeof myKey != 'undefined' && myKey !== null) { old = me.map[myKey]; if (typeof old != 'undefined') { return me.replace(myKey, myObj); } me.map[myKey] = myObj; } me.generation++; me.length++; me.items.push(myObj); me.keys.push(myKey); if (me.hasListeners.add) { me.fireEvent('add', me.length - 1, myObj, myKey); } return myObj; }, /** * MixedCollection has a generic way to fetch keys if you implement getKey. The default implementation * simply returns <b><code>item.id</code></b> but you can provide your own implementation * to return a different value as in the following examples:<pre><code> // normal way var mc = new Ext.util.MixedCollection(); mc.add(someEl.dom.id, someEl); mc.add(otherEl.dom.id, otherEl); //and so on // using getKey var mc = new Ext.util.MixedCollection(); mc.getKey = function(el){ return el.dom.id; }; mc.add(someEl); mc.add(otherEl); // or via the constructor var mc = new Ext.util.MixedCollection(false, function(el){ return el.dom.id; }); mc.add(someEl); mc.add(otherEl); * </code></pre> * @param {Object} item The item for which to find the key. * @return {Object} The key for the passed item. * @since Ext 1 */ getKey : function(o){ return o.id; }, /** * Replaces an item in the collection. Fires the {@link #event-replace} event when complete. * @param {String} key <p>The key associated with the item to replace, or the replacement item.</p> * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key * of your stored items is in a property called <code><b>id</b></code>, then the MixedCollection * will be able to <i>derive</i> the key of the replacement item. If you want to replace an item * with one having the same key value, then just pass the replacement item in this parameter.</p> * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate * with that key. * @return {Object} The new item. * @since Ext 1 */ replace : function(key, o){ var me = this, old, index; if (arguments.length == 1) { o = arguments[0]; key = me.getKey(o); } old = me.map[key]; if (typeof key == 'undefined' || key === null || typeof old == 'undefined') { return me.add(key, o); } me.generation++; index = me.indexOfKey(key); me.items[index] = o; me.map[key] = o; if (me.hasListeners.replace) { me.fireEvent('replace', key, old, o); } return o; }, /** * Adds all elements of an Array or an Object to the collection. * @param {Object/Array} objs An Object containing properties which will be added * to the collection, or an Array of values, each of which are added to the collection. * Functions references will be added to the collection if <code>{@link #allowFunctions}</code> * has been set to <code>true</code>. * @since Ext 1 */ addAll : function(objs){ var me = this, i = 0, args, len, key; if (arguments.length > 1 || Ext.isArray(objs)) { args = arguments.length > 1 ? arguments : objs; for (len = args.length; i < len; i++) { me.add(args[i]); } } else { for (key in objs) { if (objs.hasOwnProperty(key)) { if (me.allowFunctions || typeof objs[key] != 'function') { me.add(key, objs[key]); } } } } }, /** * Executes the specified function once for every item in the collection. * The function should return a boolean value. * Returning false from the function will stop the iteration. * * @param {Function} fn The function to execute for each item. * @param {Mixed} fn.item The collection item. * @param {Number} fn.index The index of item. * @param {Number} fn.len Total length of collection. * @param {Object} scope (optional) The scope (<code>this</code> reference) * in which the function is executed. Defaults to the current item in the iteration. * * @since Ext 1 */ each : function(fn, scope){ var items = [].concat(this.items), // each safe for removal i = 0, len = items.length, item; for (; i < len; i++) { item = items[i]; if (fn.call(scope || item, item, i, len) === false) { break; } } }, /** * Executes the specified function once for every key in the collection, passing each * key, and its associated item as the first two parameters. * @param {Function} fn The function to execute for each item. * @param {String} fn.key The key of collection item. * @param {Mixed} fn.item The collection item. * @param {Number} fn.index The index of item. * @param {Number} fn.len Total length of collection. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the * function is executed. Defaults to the browser window. * * @since Ext 1 */ eachKey : function(fn, scope){ var keys = this.keys, items = this.items, i = 0, len = keys.length; for (; i < len; i++) { fn.call(scope || window, keys[i], items[i], i, len); } }, /** * Returns the first item in the collection which elicits a true return value from the * passed selection function. * @param {Function} fn The selection function to execute for each item. * @param {Mixed} fn.item The collection item. * @param {String} fn.key The key of collection item. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the * function is executed. Defaults to the browser window. * @return {Object} The first item in the collection which returned true from the selection * function, or null if none was found. */ findBy : function(fn, scope) { var keys = this.keys, items = this.items, i = 0, len = items.length; for (; i < len; i++) { if (fn.call(scope || window, items[i], keys[i])) { return items[i]; } } return null; }, //<deprecated since="0.99"> /** * Returns the first item in the collection which elicits a true return value from the passed selection function. * @deprecated 4.0 Use {@link #findBy} instead. * @since Ext 1 */ find : function() { if (Ext.isDefined(Ext.global.console)) { Ext.global.console.warn('Ext.util.MixedCollection: find has been deprecated. Use findBy instead.'); } return this.findBy.apply(this, arguments); }, //</deprecated> /** * Inserts an item at the specified index in the collection. Fires the {@link #event-add} event when complete. * @param {Number} index The index to insert the item at. * @param {String} key The key to associate with the new item, or the item itself. * @param {Object} o (optional) If the second parameter was a key, the new item. * @return {Object} The item inserted. * @since Ext 1 */ insert : function(index, key, obj){ var me = this, myKey = key, myObj = obj; if (arguments.length == 2) { myObj = myKey; myKey = me.getKey(myObj); } if (me.containsKey(myKey)) { me.suspendEvents(); me.removeAtKey(myKey); me.resumeEvents(); } if (index >= me.length) { return me.add(myKey, myObj); } me.generation++; me.length++; Ext.Array.splice(me.items, index, 0, myObj); if (typeof myKey != 'undefined' && myKey !== null) { me.map[myKey] = myObj; } Ext.Array.splice(me.keys, index, 0, myKey); if (me.hasListeners.add) { me.fireEvent('add', index, myObj, myKey); } return myObj; }, /** * Remove an item from the collection. * @param {Object} o The item to remove. * @return {Object} The item removed or false if no item was removed. * @since Ext 1 */ remove : function(o) { this.generation++; return this.removeAt(this.indexOf(o)); }, /** * Remove all items in the passed array from the collection. * @param {Array} items An array of items to be removed. * @return {Ext.util.MixedCollection} this object */ removeAll : function(items) { items = [].concat(items); var i, iLen = items.length; for (i = 0; i < iLen; i++) { this.remove(items[i]); } return this; }, /** * Remove an item from a specified index in the collection. Fires the {@link #event-remove} event when complete. * @param {Number} index The index within the collection of the item to remove. * @return {Object} The item removed or false if no item was removed. * @since Ext 1 */ removeAt : function(index) { var me = this, o, key; if (index < me.length && index >= 0) { me.length--; o = me.items[index]; Ext.Array.erase(me.items, index, 1); key = me.keys[index]; if (typeof key != 'undefined') { delete me.map[key]; } Ext.Array.erase(me.keys, index, 1); if (me.hasListeners.remove) { me.fireEvent('remove', o, key); } me.generation++; return o; } return false; }, /** * Removed an item associated with the passed key fom the collection. * @param {String} key The key of the item to remove. * @return {Object} The item removed or false if no item was removed. */ removeAtKey : function(key){ return this.removeAt(this.indexOfKey(key)); }, /** * Returns the number of items in the collection. * @return {Number} the number of items in the collection. * @since Ext 1 */ getCount : function(){ return this.length; }, /** * Returns index within the collection of the passed Object. * @param {Object} o The item to find the index of. * @return {Number} index of the item. Returns -1 if not found. * @since Ext 1 */ indexOf : function(o){ return Ext.Array.indexOf(this.items, o); }, /** * Returns index within the collection of the passed key. * @param {String} key The key to find the index of. * @return {Number} index of the key. * @since Ext 1 */ indexOfKey : function(key){ return Ext.Array.indexOf(this.keys, key); }, /** * Returns the item associated with the passed key OR index. * Key has priority over index. This is the equivalent * of calling {@link #getByKey} first, then if nothing matched calling {@link #getAt}. * @param {String/Number} key The key or index of the item. * @return {Object} If the item is found, returns the item. If the item was not found, returns <code>undefined</code>. * If an item was found, but is a Class, returns <code>null</code>. * @since Ext 1 */ get : function(key) { var me = this, mk = me.map[key], item = mk !== undefined ? mk : (typeof key == 'number') ? me.items[key] : undefined; return typeof item != 'function' || me.allowFunctions ? item : null; // for prototype! }, /** * Returns the item at the specified index. * @param {Number} index The index of the item. * @return {Object} The item at the specified index. */ getAt : function(index) { return this.items[index]; }, /** * Returns the item associated with the passed key. * @param {String/Number} key The key of the item. * @return {Object} The item associated with the passed key. */ getByKey : function(key) { return this.map[key]; }, /** * Returns true if the collection contains the passed Object as an item. * @param {Object} o The Object to look for in the collection. * @return {Boolean} True if the collection contains the Object as an item. * @since Ext 1 */ contains : function(o){ return typeof this.map[this.getKey(o)] != 'undefined'; }, /** * Returns true if the collection contains the passed Object as a key. * @param {String} key The key to look for in the collection. * @return {Boolean} True if the collection contains the Object as a key. * @since Ext 1 */ containsKey : function(key){ return typeof this.map[key] != 'undefined'; }, /** * Removes all items from the collection. Fires the {@link #event-clear} event when complete. * @since Ext 1 */ clear : function(){ var me = this; me.length = 0; me.items = []; me.keys = []; me.map = {}; me.generation++; if (me.hasListeners.clear) { me.fireEvent('clear'); } }, /** * Returns the first item in the collection. * @return {Object} the first item in the collection.. * @since Ext 1 */ first : function() { return this.items[0]; }, /** * Returns the last item in the collection. * @return {Object} the last item in the collection.. * @since Ext 1 */ last : function() { return this.items[this.length - 1]; }, /** * Collects all of the values of the given property and returns their sum * @param {String} property The property to sum by * @param {String} [root] 'root' property to extract the first argument from. This is used mainly when * summing fields in records, where the fields are all stored inside the 'data' object * @param {Number} [start=0] The record index to start at * @param {Number} [end=-1] The record index to end at * @return {Number} The total */ sum: function(property, root, start, end) { var values = this.extractValues(property, root), length = values.length, sum = 0, i; start = start || 0; end = (end || end === 0) ? end : length - 1; for (i = start; i <= end; i++) { sum += values[i]; } return sum; }, /** * Collects unique values of a particular property in this MixedCollection * @param {String} property The property to collect on * @param {String} root (optional) 'root' property to extract the first argument from. This is used mainly when * summing fields in records, where the fields are all stored inside the 'data' object * @param {Boolean} allowBlank (optional) Pass true to allow null, undefined or empty string values * @return {Array} The unique values */ collect: function(property, root, allowNull) { var values = this.extractValues(property, root), length = values.length, hits = {}, unique = [], value, strValue, i; for (i = 0; i < length; i++) { value = values[i]; strValue = String(value); if ((allowNull || !Ext.isEmpty(value)) && !hits[strValue]) { hits[strValue] = true; unique.push(value); } } return unique; }, /** * @private * Extracts all of the given property values from the items in the MC. Mainly used as a supporting method for * functions like sum and collect. * @param {String} property The property to extract * @param {String} root (optional) 'root' property to extract the first argument from. This is used mainly when * extracting field data from Model instances, where the fields are stored inside the 'data' object * @return {Array} The extracted values */ extractValues: function(property, root) { var values = this.items; if (root) { values = Ext.Array.pluck(values, root); } return Ext.Array.pluck(values, property); }, /** * Returns a range of items in this collection * @param {Number} startIndex (optional) The starting index. Defaults to 0. * @param {Number} endIndex (optional) The ending index. Defaults to the last item. * @return {Array} An array of items * @since Ext 1 */ getRange : function(start, end){ var me = this, items = me.items, range = [], i; if (items.length < 1) { return range; } start = start || 0; end = Math.min(typeof end == 'undefined' ? me.length - 1 : end, me.length - 1); if (start <= end) { for (i = start; i <= end; i++) { range[range.length] = items[i]; } } else { for (i = start; i >= end; i--) { range[range.length] = items[i]; } } return range; }, /** * <p>Filters the objects in this collection by a set of {@link Ext.util.Filter Filter}s, or by a single * property/value pair with optional parameters for substring matching and case sensitivity. See * {@link Ext.util.Filter Filter} for an example of using Filter objects (preferred). Alternatively, * MixedCollection can be easily filtered by property like this:</p> <pre><code> //create a simple store with a few people defined var people = new Ext.util.MixedCollection(); people.addAll([ {id: 1, age: 25, name: 'Ed'}, {id: 2, age: 24, name: 'Tommy'}, {id: 3, age: 24, name: 'Arne'}, {id: 4, age: 26, name: 'Aaron'} ]); //a new MixedCollection containing only the items where age == 24 var middleAged = people.filter('age', 24); </code></pre> * * * @param {Ext.util.Filter[]/String} property A property on your objects, or an array of {@link Ext.util.Filter Filter} objects * @param {String/RegExp} value Either string that the property values * should start with or a RegExp to test against the property * @param {Boolean} [anyMatch=false] True to match any part of the string, not just the beginning * @param {Boolean} [caseSensitive=false] True for case sensitive comparison. * @return {Ext.util.MixedCollection} The new filtered collection * @since Ext 1 */ filter : function(property, value, anyMatch, caseSensitive) { var filters = []; //support for the simple case of filtering by property/value if (Ext.isString(property)) { filters.push(new Ext.util.Filter({ property : property, value : value, anyMatch : anyMatch, caseSensitive: caseSensitive })); } else if (Ext.isArray(property) || property instanceof Ext.util.Filter) { filters = filters.concat(property); } // At this point we have an array of zero or more Ext.util.Filter objects to filter with, // so here we construct a function that combines these filters by ANDing them together // and filter by that. return this.filterBy(Ext.util.Filter.createFilterFn(filters)); }, /** * Filter by a function. Returns a <i>new</i> collection that has been filtered. * The passed function will be called with each object in the collection. * If the function returns true, the value is included otherwise it is filtered. * @param {Function} fn The function to be called. * @param {Mixed} fn.item The collection item. * @param {String} fn.key The key of collection item. * @param {Object} scope (optional) The scope (<code>this</code> reference) in * which the function is executed. Defaults to this MixedCollection. * @return {Ext.util.MixedCollection} The new filtered collection * @since Ext 1 */ filterBy : function(fn, scope) { var me = this, newMC = new this.self(), keys = me.keys, items = me.items, length = items.length, i; newMC.getKey = me.getKey; for (i = 0; i < length; i++) { if (fn.call(scope || me, items[i], keys[i])) { newMC.add(keys[i], items[i]); } } return newMC; }, /** * Finds the index of the first matching object in this collection by a specific property/value. * @param {String} property The name of a property on your objects. * @param {String/RegExp} value A string that the property values * should start with or a RegExp to test against the property. * @param {Number} [start=0] The index to start searching at. * @param {Boolean} [anyMatch=false] True to match any part of the string, not just the beginning. * @param {Boolean} [caseSensitive=false] True for case sensitive comparison. * @return {Number} The matched index or -1 * @since Ext 2 */ findIndex : function(property, value, start, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return -1; } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.findIndexBy(function(o){ return o && value.test(o[property]); }, null, start); }, /** * Find the index of the first matching object in this collection by a function. * If the function returns <i>true</i> it is considered a match. * @param {Function} fn The function to be called. * @param {Mixed} fn.item The collection item. * @param {String} fn.key The key of collection item. * @param {Object} [scope] The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection. * @param {Number} [start=0] The index to start searching at. * @return {Number} The matched index or -1 * @since Ext 2 */ findIndexBy : function(fn, scope, start){ var me = this, keys = me.keys, items = me.items, i = start || 0, len = items.length; for (; i < len; i++) { if (fn.call(scope || me, items[i], keys[i])) { return i; } } return -1; }, /** * Returns a regular expression based on the given value and matching options. This is used internally for finding and filtering, * and by Ext.data.Store#filter * @private * @param {String} value The value to create the regex for. This is escaped using Ext.escapeRe * @param {Boolean} anyMatch True to allow any match - no regex start/end line anchors will be added. Defaults to false * @param {Boolean} caseSensitive True to make the regex case sensitive (adds 'i' switch to regex). Defaults to false. * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true. * @since Ext 3 */ createValueMatcher : function(value, anyMatch, caseSensitive, exactMatch) { if (!value.exec) { // not a regex var er = Ext.String.escapeRegex; value = String(value); if (anyMatch === true) { value = er(value); } else { value = '^' + er(value); if (exactMatch === true) { value += '$'; } } value = new RegExp(value, caseSensitive ? '' : 'i'); } return value; }, /** * Creates a shallow copy of this collection * @return {Ext.util.MixedCollection} * @since Ext 1 */ clone : function() { var me = this, copy = new this.self(), keys = me.keys, items = me.items, i = 0, len = items.length; for(; i < len; i++){ copy.add(keys[i], items[i]); } copy.getKey = me.getKey; return copy; } });
import SimpleComponentDriver from '../Testing/CommonDrivers/simpleComponentDriver'; export default class IconWithTooltipDriver extends SimpleComponentDriver { constructor( wrapper ) { super( wrapper, `.${wrapper.prop( 'cssMap' ).default}` ); this.tooltip = wrapper.find( 'IconWithTooltip > Tooltip' ).first(); } mouseOverIcon() { this.tooltip.driver().mouseOver(); return this; } mouseOutIcon() { this.tooltip.driver().mouseOut(); return this; } getContent() { return this.wrapper.find( `.${this.cssMap.content}` ).children(); } getMessage() { return this.tooltip.driver().getMessage(); } }
import { reactive, readonly } from "vue"; import { useRouter, useRoute } from "vue-router"; import { useAnnouncer, useKirbyApi } from "./"; /** * Returns page data by id or the current route path * * @param {string} [path] The ptional page id (path) to retrieve * @returns {reactive} The readonly reactive page object */ export default (path) => { const router = useRouter(); const { path: currentPath } = useRoute(); const { hasPage, getPage } = useKirbyApi(); const { setAnnouncer } = useAnnouncer(); // Build page id and trim leading or trailing slashes let id = (path ?? currentPath).replace(/^\/|\/$/g, ""); // Fall back to homepage if id is empty if (!id) id = "home"; // Setup page waiter promise let resolve; const promise = new Promise((r) => { resolve = r; }); // Setup reactive page object const page = reactive({ __status: "pending", isReady: false, isReadyPromise: () => promise, }); (async () => { // Check if cached page exists (otherwise skip SWR) const isCached = hasPage(id); // Get page from cache or freshly fetch it const data = await getPage(id); if (!data) { page.__status = "error"; return; } // Check data origin when the hook is used on the current route if (!path) { // Redirect to error page if data returned *is* the error page if (data.__isErrorPage && currentPath !== "/error") { router.replace({ path: "/error" }); return; } // Redirect to offline page if page hasn't been cached either in-store or // by the service worker and the offline fallback JSON was returned // Note: data for `home` and `offline` pages are always available since they // are precached by the service worker if (data.__isOffline) { router.replace({ path: "/offline" }); return; } } // Append page data to reactive page object Object.assign(page, data); page.__status = "resolved"; page.isReady = true; resolve?.(); // Further actions only if the hook was called for the current route if (!path) { // Set document title document.title = page.metaTitle; // Announce new route setAnnouncer(`Navigated to ${page.title}`); } // Revalidate the stale asset asynchronously if ( import.meta.env.VITE_STALE_WHILE_REVALIDATE === "true" && isCached && navigator.onLine ) { const newData = await getPage(id, { revalidate: true }); if (JSON.stringify(newData) !== JSON.stringify(data)) { Object.assign(page, newData); } page.__status = "revalidated"; } })(); return readonly(page); };
from aiohttp import web from .scheduler import app web.run_app(app, host='0.0.0.0', port=5000)
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DirectionalKeyCodes = (_a = {}, _a[38 /* up */] = 1, _a[40 /* down */] = 1, _a[37 /* left */] = 1, _a[39 /* right */] = 1, _a[36 /* home */] = 1, _a[35 /* end */] = 1, _a[9 /* tab */] = 1, _a[33 /* pageUp */] = 1, _a[34 /* pageDown */] = 1, _a); /** * Returns true if the keycode is a directional keyboard key. */ function isDirectionalKeyCode(which) { return !!DirectionalKeyCodes[which]; } exports.isDirectionalKeyCode = isDirectionalKeyCode; /** * Adds a keycode to the list of keys that, when pressed, should cause the focus outlines to be visible. * This can be used to add global shortcut keys that directionally move from section to section within * an app or between focus trap zones. */ function addDirectionalKeyCode(which) { DirectionalKeyCodes[which] = 1; } exports.addDirectionalKeyCode = addDirectionalKeyCode; var _a; //# sourceMappingURL=keyboard.js.map
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# # SpiderBot_Validation.py # # Author(s): Chong Yu Quan, Arijit Dasgupta # # Email(s): chong.yuquan@u.nus.edu, arijit.dasgupta@u.nus.edu # #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# """ In this script, you can test & observe the performance of a model in validation-mode. This means that the spiderbot is not training, but it is merely taking actions depending on the state To run the validation of a model --> specify the training name and the algorithm used below NOTE: The parameters in the walk function have been hardcoded for the SpiderBot Project Validation by Professors/TAs """ # Standard Import import math # SpiderBot Imports from SpiderBot_Walk import walk #~~~~~~~~~~~~ VALIDATION CONFIG SETUP ~~~~~~~~~~~~# # specify the training name training_name = "DDPG_FullyTrained" # DDPG_FullyTrained, DDPG_PartiallyTrained # Specify the Algorithm used model = "DDPG" # What is the target location you wish to set (in metres)? DDPG_FullyTrained can go forward up to 9 metres target_location = 8 # How many episodes do you wish to visualise the SpiderBot for? # Note that every episode will be exactly the same as there is no training going on episodes = 100000000000 # A large number is set to put the simulation on loop #~~~~~~~~~~~~ END OF CONFIG ~~~~~~~~~~~~~~# # set discrete joint velocities for non-DDPG algorithms if model == "A2C_SingleAction": joint_velocities = [x * 0.5 for x in range(-20, 21, 1)] else: joint_velocities = [-10, -5, 0, 5, 10] # set upper and lower joint limits joint_limit_lower = [math.radians(-60) for x in range(32)] joint_limit_upper = [math.radians(60) for x in range(32)] # Run the walk function in test mode to observe a trained SpiderBot walk( mode = "test", model = model, connect_mode = "GUI", training_name = training_name, save_best_model = False, save_data = False, num_of_legs = 8, episodes = episodes, time_step_size = 120./240, joint_limit_lower = joint_limit_lower, joint_limit_upper = joint_limit_upper, joint_velocities = joint_velocities, discount_rate = None, lr_actor = None, lr_critic = None, target_location = target_location, tau = None, max_mem_size = 1000000, batch_size = None, noise = None, max_action = 10, min_action = -10, epsilon = None, epsilon_decay = None, epsilon_min = None, update_target = None, forward_motion_reward = None, forward_distance_reward = None, sideways_velocity_punishment = None, sideways_distance_penalty = None, time_step_penalty = None, flipped_penalty = None, goal_reward = None, out_of_range_penalty = None )
export const getRandomInt = (max = 100, min = 0) => { return min + Math.round(Math.random() * 1000) % (max - min); };
/******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ({ /***/ "./node_modules/process/browser.js": /*!*****************************************!*\ !*** ./node_modules/process/browser.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(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; runClearTimeout(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) { runTimeout(drainQueue); } }; // 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.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } 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; }; /***/ }), /***/ "./node_modules/setimmediate/setImmediate.js": /*!***************************************************!*\ !*** ./node_modules/setimmediate/setImmediate.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); }; } function installSetTimeoutImplementation() { registerImmediate = function(handle) { setTimeout(runIfPresent, 0, handle); }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../process/browser.js */ "./node_modules/process/browser.js"))) /***/ }), /***/ "./node_modules/timers-browserify/main.js": /*!************************************************!*\ !*** ./node_modules/timers-browserify/main.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || (typeof self !== "undefined" && self) || window; var apply = Function.prototype.apply; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { if (timeout) { timeout.close(); } }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(scope, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // setimmediate attaches itself to the global object __webpack_require__(/*! setimmediate */ "./node_modules/setimmediate/setImmediate.js"); // On some exotic environments, it's not clear which object `setimmediate` was // able to install onto. Search each possibility in the same order as the // `setimmediate` library. exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || (typeof global !== "undefined" && global.setImmediate) || (this && this.setImmediate); exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || (typeof global !== "undefined" && global.clearImmediate) || (this && this.clearImmediate); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "./node_modules/vue-socket.io/dist/vue-socketio.js": /*!*********************************************************!*\ !*** ./node_modules/vue-socket.io/dist/vue-socketio.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { !function(t,e){ true?module.exports=e():undefined}("undefined"!=typeof self?self:this,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=23)}([function(t,e,r){(function(n){function o(){var t;try{t=e.storage.debug}catch(t){}return!t&&void 0!==n&&"env"in n&&(t=n.env.DEBUG),t}(e=t.exports=r(26)).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},e.formatArgs=function(t){var r=this.useColors;if(t[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+t[0]+(r?"%c ":" ")+"+"+e.humanize(this.diff),!r)return;var n="color: "+this.color;t.splice(1,0,n,"color: inherit");var o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,function(t){"%%"!==t&&(o++,"%c"===t&&(i=o))}),t.splice(i,0,n)},e.save=function(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(t){}},e.load=o,e.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(t){}}(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},e.enable(o())}).call(this,r(25))},function(t,e,r){function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<n.length;o++)if((r=n[o])===e||r.fn===e){n.splice(o,1);break}return this},n.prototype.emit=function(t){this._callbacks=this._callbacks||{};var e=[].slice.call(arguments,1),r=this._callbacks["$"+t];if(r)for(var n=0,o=(r=r.slice(0)).length;n<o;++n)r[n].apply(this,e);return this},n.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},n.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,r){var n,o=r(36),i=r(16),s=r(37),a=r(38),c=r(39);"undefined"!=typeof ArrayBuffer&&(n=r(40));var u="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),h="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),f=u||h;e.protocol=3;var p=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},l=o(p),d={type:"error",data:"parser error"},y=r(41);function g(t,e,r){for(var n=new Array(t.length),o=a(t.length,r),i=function(t,r,o){e(r,function(e,r){n[t]=r,o(e,n)})},s=0;s<t.length;s++)i(s,t[s],o)}e.encodePacket=function(t,r,n,o){"function"==typeof r&&(o=r,r=!1),"function"==typeof n&&(o=n,n=null);var i=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&i instanceof ArrayBuffer)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=p[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return n(s.buffer)}(t,r,o);if(void 0!==y&&i instanceof y)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);if(f)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},r,!0,n)},o.readAsArrayBuffer(t.data)}(t,r,n);var o=new Uint8Array(1);o[0]=p[t.type];var i=new y([o.buffer,t.data]);return n(i)}(t,r,o);if(i&&i.base64)return function(t,r){var n="b"+e.packets[t.type]+t.data.data;return r(n)}(t,o);var s=p[t.type];return void 0!==t.data&&(s+=n?c.encode(String(t.data),{strict:!1}):String(t.data)),o(""+s)},e.encodeBase64Packet=function(t,r){var n,o="b"+e.packets[t.type];if(void 0!==y&&t.data instanceof y){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];r(o+t)},i.readAsDataURL(t.data)}try{n=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var s=new Uint8Array(t.data),a=new Array(s.length),c=0;c<s.length;c++)a[c]=s[c];n=String.fromCharCode.apply(null,a)}return o+=btoa(n),r(o)},e.decodePacket=function(t,r,n){if(void 0===t)return d;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),r);if(n&&!1===(t=function(t){try{t=c.decode(t,{strict:!1})}catch(t){return!1}return t}(t)))return d;var o=t.charAt(0);return Number(o)==o&&l[o]?t.length>1?{type:l[o],data:t.substring(1)}:{type:l[o]}:d}o=new Uint8Array(t)[0];var i=s(t,1);return y&&"blob"===r&&(i=new y([i])),{type:l[o],data:i}},e.decodeBase64Packet=function(t,e){var r=l[t.charAt(0)];if(!n)return{type:r,data:{base64:!0,data:t.substr(1)}};var o=n.decode(t.substr(1));return"blob"===e&&y&&(o=new y([o])),{type:r,data:o}},e.encodePayload=function(t,r,n){"function"==typeof r&&(n=r,r=null);var o=i(t);if(r&&o)return y&&!f?e.encodePayloadAsBlob(t,n):e.encodePayloadAsArrayBuffer(t,n);if(!t.length)return n("0:");g(t,function(t,n){e.encodePacket(t,!!o&&r,!1,function(t){n(null,function(t){return t.length+":"+t}(t))})},function(t,e){return n(e.join(""))})},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);var o;if("function"==typeof r&&(n=r,r=null),""===t)return n(d,0,1);for(var i,s,a="",c=0,u=t.length;c<u;c++){var h=t.charAt(c);if(":"===h){if(""===a||a!=(i=Number(a)))return n(d,0,1);if(a!=(s=t.substr(c+1,i)).length)return n(d,0,1);if(s.length){if(o=e.decodePacket(s,r,!1),d.type===o.type&&d.data===o.data)return n(d,0,1);if(!1===n(o,c+i,u))return}c+=i,a=""}else a+=h}return""!==a?n(d,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,r){if(!t.length)return r(new ArrayBuffer(0));g(t,function(t,r){e.encodePacket(t,!0,!0,function(t){return r(null,t)})},function(t,e){var n=e.reduce(function(t,e){var r;return t+(r="string"==typeof e?e.length:e.byteLength).toString().length+r+2},0),o=new Uint8Array(n),i=0;return e.forEach(function(t){var e="string"==typeof t,r=t;if(e){for(var n=new Uint8Array(t.length),s=0;s<t.length;s++)n[s]=t.charCodeAt(s);r=n.buffer}o[i++]=e?0:1;var a=r.byteLength.toString();for(s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(n=new Uint8Array(r),s=0;s<n.length;s++)o[i++]=n[s]}),r(o.buffer)})},e.encodePayloadAsBlob=function(t,r){g(t,function(t,r){e.encodePacket(t,!0,!0,function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);t=n.buffer,e[0]=0}var i=(t instanceof ArrayBuffer?t.byteLength:t.size).toString(),s=new Uint8Array(i.length+1);for(o=0;o<i.length;o++)s[o]=parseInt(i[o]);if(s[i.length]=255,y){var a=new y([e.buffer,s.buffer,t]);r(null,a)}})},function(t,e){return r(new y(e))})},e.decodePayloadAsBinary=function(t,r,n){"function"==typeof r&&(n=r,r=null);for(var o=t,i=[];o.byteLength>0;){for(var a=new Uint8Array(o),c=0===a[0],u="",h=1;255!==a[h];h++){if(u.length>310)return n(d,0,1);u+=a[h]}o=s(o,2+u.length),u=parseInt(u);var f=s(o,0,u);if(c)try{f=String.fromCharCode.apply(null,new Uint8Array(f))}catch(t){var p=new Uint8Array(f);f="";for(h=0;h<p.length;h++)f+=String.fromCharCode(p[h])}i.push(f),o=s(o,u)}var l=i.length;i.forEach(function(t,o){n(e.decodePacket(t,r,!0),o,l)})}},function(t,e){e.encode=function(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e},e.decode=function(t){for(var e={},r=t.split("&"),n=0,o=r.length;n<o;n++){var i=r[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(t,e,r){var n=r(0)("socket.io-parser"),o=r(1),i=r(28),s=r(6),a=r(11);function c(){}e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=c,e.Decoder=f;var u=e.ERROR+'"encode error"';function h(t){var r=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(r+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(r+=t.nsp+","),null!=t.id&&(r+=t.id),null!=t.data){var o=function(t){try{return JSON.stringify(t)}catch(t){return!1}}(t.data);if(!1===o)return u;r+=o}return n("encoded %j as %s",t,r),r}function f(){this.reconstructor=null}function p(t){this.reconPack=t,this.buffers=[]}function l(t){return{type:e.ERROR,data:"parser error: "+t}}c.prototype.encode=function(t,r){(n("encoding packet %j",t),e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)?function(t,e){i.removeBlobs(t,function(t){var r=i.deconstructPacket(t),n=h(r.packet),o=r.buffers;o.unshift(n),e(o)})}(t,r):r([h(t)])},o(f.prototype),f.prototype.add=function(t){var r;if("string"==typeof t)r=function(t){var r=0,o={type:Number(t.charAt(0))};if(null==e.types[o.type])return l("unknown packet type "+o.type);if(e.BINARY_EVENT===o.type||e.BINARY_ACK===o.type){for(var i="";"-"!==t.charAt(++r)&&(i+=t.charAt(r),r!=t.length););if(i!=Number(i)||"-"!==t.charAt(r))throw new Error("Illegal attachments");o.attachments=Number(i)}if("/"===t.charAt(r+1))for(o.nsp="";++r;){var a=t.charAt(r);if(","===a)break;if(o.nsp+=a,r===t.length)break}else o.nsp="/";var c=t.charAt(r+1);if(""!==c&&Number(c)==c){for(o.id="";++r;){var a=t.charAt(r);if(null==a||Number(a)!=a){--r;break}if(o.id+=t.charAt(r),r===t.length)break}o.id=Number(o.id)}if(t.charAt(++r)){var u=function(t){try{return JSON.parse(t)}catch(t){return!1}}(t.substr(r)),h=!1!==u&&(o.type===e.ERROR||s(u));if(!h)return l("invalid payload");o.data=u}return n("decoded %s as %j",t,o),o}(t),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type?(this.reconstructor=new p(r),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",r)):this.emit("decoded",r);else{if(!a(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(r=this.reconstructor.takeBinaryData(t))&&(this.reconstructor=null,this.emit("decoded",r))}},f.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},p.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=i.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},p.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){"use strict";(function(t){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ var n=r(29),o=r(30),i=r(31);function s(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(s()<e)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=c.prototype:(null===t&&(t=new c(e)),t.length=e),t}function c(t,e,r){if(!(c.TYPED_ARRAY_SUPPORT||this instanceof c))return new c(t,e,r);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return f(this,t)}return u(this,t,e,r)}function u(t,e,r,n){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,r,n){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");e=void 0===r&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,r):new Uint8Array(e,r,n);c.TYPED_ARRAY_SUPPORT?(t=e).__proto__=c.prototype:t=p(t,e);return t}(t,e,r,n):"string"==typeof e?function(t,e,r){"string"==typeof r&&""!==r||(r="utf8");if(!c.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|d(e,r),o=(t=a(t,n)).write(e,r);o!==n&&(t=t.slice(0,o));return t}(t,e,r):function(t,e){if(c.isBuffer(e)){var r=0|l(e.length);return 0===(t=a(t,r)).length?t:(e.copy(t,0,0,r),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(n=e.length)!=n?a(t,0):p(t,e);if("Buffer"===e.type&&i(e.data))return p(t,e.data)}var n;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function f(t,e){if(h(e),t=a(t,e<0?0:0|l(e)),!c.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function p(t,e){var r=e.length<0?0:0|l(e.length);t=a(t,r);for(var n=0;n<r;n+=1)t[n]=255&e[n];return t}function l(t){if(t>=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function d(t,e){if(c.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return M(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(t).length;default:if(n)return M(t).length;e=(""+e).toLowerCase(),n=!0}}function y(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function g(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=c.from(e,n)),c.isBuffer(e))return 0===e.length?-1:m(t,e,r,n,o);if("number"==typeof e)return e&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):m(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function m(t,e,r,n,o){var i,s=1,a=t.length,c=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,c/=2,r/=2}function u(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(o){var h=-1;for(i=r;i<a;i++)if(u(t,i)===u(e,-1===h?0:i-h)){if(-1===h&&(h=i),i-h+1===c)return h*s}else-1!==h&&(i-=i-h),h=-1}else for(r+c>a&&(r=a-c),i=r;i>=0;i--){for(var f=!0,p=0;p<c;p++)if(u(t,i+p)!==u(e,p)){f=!1;break}if(f)return i}return-1}function v(t,e,r,n){r=Number(r)||0;var o=t.length-r;n?(n=Number(n))>o&&(n=o):n=o;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var s=0;s<n;++s){var a=parseInt(e.substr(2*s,2),16);if(isNaN(a))return s;t[r+s]=a}return s}function b(t,e,r,n){return Y(M(e,t.length-r),t,r,n)}function w(t,e,r,n){return Y(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function k(t,e,r,n){return w(t,e,r,n)}function A(t,e,r,n){return Y(q(e),t,r,n)}function C(t,e,r,n){return Y(function(t,e){for(var r,n,o,i=[],s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function E(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function B(t,e,r){r=Math.min(t.length,r);for(var n=[],o=e;o<r;){var i,s,a,c,u=t[o],h=null,f=u>239?4:u>223?3:u>191?2:1;if(o+f<=r)switch(f){case 1:u<128&&(h=u);break;case 2:128==(192&(i=t[o+1]))&&(c=(31&u)<<6|63&i)>127&&(h=c);break;case 3:i=t[o+1],s=t[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(h=c);break;case 4:i=t[o+1],s=t[o+2],a=t[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(h=c)}null===h?(h=65533,f=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),o+=f}return function(t){var e=t.length;if(e<=x)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=x));return r}(n)}e.Buffer=c,e.SlowBuffer=function(t){+t!=t&&(t=0);return c.alloc(+t)},e.INSPECT_MAX_BYTES=50,c.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=s(),c.poolSize=8192,c._augment=function(t){return t.__proto__=c.prototype,t},c.from=function(t,e,r){return u(null,t,e,r)},c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&c[Symbol.species]===c&&Object.defineProperty(c,Symbol.species,{value:null,configurable:!0})),c.alloc=function(t,e,r){return function(t,e,r,n){return h(e),e<=0?a(t,e):void 0!==r?"string"==typeof n?a(t,e).fill(r,n):a(t,e).fill(r):a(t,e)}(null,t,e,r)},c.allocUnsafe=function(t){return f(null,t)},c.allocUnsafeSlow=function(t){return f(null,t)},c.isBuffer=function(t){return!(null==t||!t._isBuffer)},c.compare=function(t,e){if(!c.isBuffer(t)||!c.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,o=0,i=Math.min(r,n);o<i;++o)if(t[o]!==e[o]){r=t[o],n=e[o];break}return r<n?-1:n<r?1:0},c.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(t,e){if(!i(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return c.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var n=c.allocUnsafe(e),o=0;for(r=0;r<t.length;++r){var s=t[r];if(!c.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,o),o+=s.length}return n},c.byteLength=d,c.prototype._isBuffer=!0,c.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)y(this,e,e+1);return this},c.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)y(this,e,e+3),y(this,e+1,e+2);return this},c.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)y(this,e,e+7),y(this,e+1,e+6),y(this,e+2,e+5),y(this,e+3,e+4);return this},c.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?B(this,0,t):function(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return B(this,e,r);case"ascii":return R(this,e,r);case"latin1":case"binary":return S(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},c.prototype.equals=function(t){if(!c.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===c.compare(this,t)},c.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),"<Buffer "+t+">"},c.prototype.compare=function(t,e,r,n,o){if(!c.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),a=Math.min(i,s),u=this.slice(n,o),h=t.slice(e,r),f=0;f<a;++f)if(u[f]!==h[f]){i=u[f],s=h[f];break}return i<s?-1:s<i?1:0},c.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},c.prototype.indexOf=function(t,e,r){return g(this,t,e,r,!0)},c.prototype.lastIndexOf=function(t,e,r){return g(this,t,e,r,!1)},c.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(r)?(r|=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var o=this.length-e;if((void 0===r||r>o)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return v(this,t,e,r);case"utf8":case"utf-8":return b(this,t,e,r);case"ascii":return w(this,t,e,r);case"latin1":case"binary":return k(this,t,e,r);case"base64":return A(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var x=4096;function R(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;o<r;++o)n+=String.fromCharCode(127&t[o]);return n}function S(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;o<r;++o)n+=String.fromCharCode(t[o]);return n}function T(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var o="",i=e;i<r;++i)o+=j(t[i]);return o}function P(t,e,r){for(var n=t.slice(e,r),o="",i=0;i<n.length;i+=2)o+=String.fromCharCode(n[i]+256*n[i+1]);return o}function _(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,o,i){if(!c.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||e<i)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function U(t,e,r,n){e<0&&(e=65535+e+1);for(var o=0,i=Math.min(t.length-r,2);o<i;++o)t[r+o]=(e&255<<8*(n?o:1-o))>>>8*(n?o:1-o)}function N(t,e,r,n){e<0&&(e=4294967295+e+1);for(var o=0,i=Math.min(t.length-r,4);o<i;++o)t[r+o]=e>>>8*(n?o:3-o)&255}function D(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function I(t,e,r,n,i){return i||D(t,0,r,4),o.write(t,e,r,n,23,4),r+4}function F(t,e,r,n,i){return i||D(t,0,r,8),o.write(t,e,r,n,52,8),r+8}c.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e<t&&(e=t),c.TYPED_ARRAY_SUPPORT)(r=this.subarray(t,e)).__proto__=c.prototype;else{var o=e-t;r=new c(o,void 0);for(var i=0;i<o;++i)r[i]=this[i+t]}return r},c.prototype.readUIntLE=function(t,e,r){t|=0,e|=0,r||_(t,e,this.length);for(var n=this[t],o=1,i=0;++i<e&&(o*=256);)n+=this[t+i]*o;return n},c.prototype.readUIntBE=function(t,e,r){t|=0,e|=0,r||_(t,e,this.length);for(var n=this[t+--e],o=1;e>0&&(o*=256);)n+=this[t+--e]*o;return n},c.prototype.readUInt8=function(t,e){return e||_(t,1,this.length),this[t]},c.prototype.readUInt16LE=function(t,e){return e||_(t,2,this.length),this[t]|this[t+1]<<8},c.prototype.readUInt16BE=function(t,e){return e||_(t,2,this.length),this[t]<<8|this[t+1]},c.prototype.readUInt32LE=function(t,e){return e||_(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},c.prototype.readUInt32BE=function(t,e){return e||_(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},c.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||_(t,e,this.length);for(var n=this[t],o=1,i=0;++i<e&&(o*=256);)n+=this[t+i]*o;return n>=(o*=128)&&(n-=Math.pow(2,8*e)),n},c.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||_(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},c.prototype.readInt8=function(t,e){return e||_(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},c.prototype.readInt16LE=function(t,e){e||_(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(t,e){e||_(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(t,e){return e||_(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},c.prototype.readInt32BE=function(t,e){return e||_(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},c.prototype.readFloatLE=function(t,e){return e||_(t,4,this.length),o.read(this,t,!0,23,4)},c.prototype.readFloatBE=function(t,e){return e||_(t,4,this.length),o.read(this,t,!1,23,4)},c.prototype.readDoubleLE=function(t,e){return e||_(t,8,this.length),o.read(this,t,!0,52,8)},c.prototype.readDoubleBE=function(t,e){return e||_(t,8,this.length),o.read(this,t,!1,52,8)},c.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||O(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i<r&&(o*=256);)this[e+i]=t/o&255;return e+r},c.prototype.writeUIntBE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||O(this,t,e,r,Math.pow(2,8*r)-1,0);var o=r-1,i=1;for(this[e+o]=255&t;--o>=0&&(i*=256);)this[e+o]=t/i&255;return e+r},c.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,1,255,0),c.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},c.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):U(this,t,e,!0),e+2},c.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):U(this,t,e,!1),e+2},c.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):N(this,t,e,!0),e+4},c.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},c.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);O(this,t,e,r,o-1,-o)}var i=0,s=1,a=0;for(this[e]=255&t;++i<r&&(s*=256);)t<0&&0===a&&0!==this[e+i-1]&&(a=1),this[e+i]=(t/s>>0)-a&255;return e+r},c.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);O(this,t,e,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/s>>0)-a&255;return e+r},c.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,1,127,-128),c.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},c.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):U(this,t,e,!0),e+2},c.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):U(this,t,e,!1),e+2},c.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):N(this,t,e,!0),e+4},c.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},c.prototype.writeFloatLE=function(t,e,r){return I(this,t,e,!0,r)},c.prototype.writeFloatBE=function(t,e,r){return I(this,t,e,!1,r)},c.prototype.writeDoubleLE=function(t,e,r){return F(this,t,e,!0,r)},c.prototype.writeDoubleBE=function(t,e,r){return F(this,t,e,!1,r)},c.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);var o,i=n-r;if(this===t&&r<e&&e<n)for(o=i-1;o>=0;--o)t[o+e]=this[o+r];else if(i<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o<i;++o)t[o+e]=this[o+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+i),e);return i},c.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===t.length){var o=t.charCodeAt(0);o<256&&(t=o)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!c.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;var i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{var s=c.isBuffer(t)?t:M(new c(t,n).toString()),a=s.length;for(i=0;i<r-e;++i)this[i+e]=s[i%a]}return this};var L=/[^+\/0-9A-Za-z-_]/g;function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function M(t,e){var r;e=e||1/0;for(var n=t.length,o=null,i=[],s=0;s<n;++s){if((r=t.charCodeAt(s))>55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function q(t){return n.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(L,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Y(t,e,r,n){for(var o=0;o<n&&!(o+r>=e.length||o>=t.length);++o)e[o+r]=t[o];return o}}).call(this,r(12))},function(t,e,r){var n=r(34);t.exports=function(t){var e=t.xdomain,r=t.xscheme,o=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||n))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!r&&o)return new XDomainRequest}catch(t){}if(!e)try{return new(self[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e,r){var n=r(2),o=r(1);function i(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}t.exports=i,o(i.prototype),i.prototype.onError=function(t,e){var r=new Error(t);return r.type="TransportError",r.description=e,this.emit("error",r),this},i.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},i.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},i.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},i.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},i.prototype.onData=function(t){var e=n.decodePacket(t,this.socket.binaryType);this.onPacket(e)},i.prototype.onPacket=function(t){this.emit("packet",t)},i.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e){var r=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s=r.exec(t||""),a={},c=14;c--;)a[n[c]]=s[c]||"";return-1!=o&&-1!=i&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a}},function(t,e,r){(function(e){t.exports=function(t){return r&&e.isBuffer(t)||n&&(t instanceof ArrayBuffer||o(t))};var r="function"==typeof e&&"function"==typeof e.isBuffer,n="function"==typeof ArrayBuffer,o=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}}).call(this,r(7).Buffer)},function(t,e){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e,r){var n=r(32),o=r(19),i=r(1),s=r(5),a=r(20),c=r(21),u=r(0)("socket.io-client:manager"),h=r(18),f=r(46),p=Object.prototype.hasOwnProperty;function l(t,e){if(!(this instanceof l))return new l(t,e);t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new f({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var r=e.parser||s;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this.autoConnect=!1!==e.autoConnect,this.autoConnect&&this.open()}t.exports=l,l.prototype.emitAll=function(){for(var t in this.emit.apply(this,arguments),this.nsps)p.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},l.prototype.updateSocketIds=function(){for(var t in this.nsps)p.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},l.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},i(l.prototype),l.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},l.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},l.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},l.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},l.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},l.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},l.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},l.prototype.open=l.prototype.connect=function(t,e){if(u("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;u("opening %s",this.uri),this.engine=n(this.uri,this.opts);var r=this.engine,o=this;this.readyState="opening",this.skipReconnect=!1;var i=a(r,"open",function(){o.onopen(),t&&t()}),s=a(r,"error",function(e){if(u("connect_error"),o.cleanup(),o.readyState="closed",o.emitAll("connect_error",e),t){var r=new Error("Connection error");r.data=e,t(r)}else o.maybeReconnectOnOpen()});if(!1!==this._timeout){var c=this._timeout;u("connect attempt will timeout after %d",c);var h=setTimeout(function(){u("connect attempt timed out after %d",c),i.destroy(),r.close(),r.emit("error","timeout"),o.emitAll("connect_timeout",c)},c);this.subs.push({destroy:function(){clearTimeout(h)}})}return this.subs.push(i),this.subs.push(s),this},l.prototype.onopen=function(){u("open"),this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(a(t,"data",c(this,"ondata"))),this.subs.push(a(t,"ping",c(this,"onping"))),this.subs.push(a(t,"pong",c(this,"onpong"))),this.subs.push(a(t,"error",c(this,"onerror"))),this.subs.push(a(t,"close",c(this,"onclose"))),this.subs.push(a(this.decoder,"decoded",c(this,"ondecoded")))},l.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},l.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},l.prototype.ondata=function(t){this.decoder.add(t)},l.prototype.ondecoded=function(t){this.emit("packet",t)},l.prototype.onerror=function(t){u("error",t),this.emitAll("error",t)},l.prototype.socket=function(t,e){var r=this.nsps[t];if(!r){r=new o(this,t,e),this.nsps[t]=r;var n=this;r.on("connecting",i),r.on("connect",function(){r.id=n.generateId(t)}),this.autoConnect&&i()}function i(){~h(n.connecting,r)||n.connecting.push(r)}return r},l.prototype.destroy=function(t){var e=h(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},l.prototype.packet=function(t){u("writing packet %j",t);var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,function(r){for(var n=0;n<r.length;n++)e.engine.write(r[n],t.options);e.encoding=!1,e.processPacketQueue()}))},l.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},l.prototype.cleanup=function(){u("cleanup");for(var t=this.subs.length,e=0;e<t;e++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},l.prototype.close=l.prototype.disconnect=function(){u("disconnect"),this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},l.prototype.onclose=function(t){u("onclose"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},l.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)u("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();u("will wait %dms before reconnect attempt",e),this.reconnecting=!0;var r=setTimeout(function(){t.skipReconnect||(u("attempting reconnect"),t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open(function(e){e?(u("reconnect attempt error"),t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):(u("reconnect success"),t.onreconnect())}))},e);this.subs.push({destroy:function(){clearTimeout(r)}})}},l.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,r){var n=r(8),o=r(35),i=r(42),s=r(43);e.polling=function(t){var e=!1,r=!1,s=!1!==t.jsonp;if("undefined"!=typeof location){var a="https:"===location.protocol,c=location.port;c||(c=a?443:80),e=t.hostname!==location.hostname||c!==t.port,r=t.secure!==a}if(t.xdomain=e,t.xscheme=r,"open"in new n(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error("JSONP disabled");return new i(t)},e.websocket=s},function(t,e,r){var n=r(9),o=r(3),i=r(2),s=r(4),a=r(17),c=r(0)("engine.io-client:polling");t.exports=h;var u=null!=new(r(8))({xdomain:!1}).responseType;function h(t){var e=t&&t.forceBase64;u&&!e||(this.supportsBinary=!1),n.call(this,t)}s(h,n),h.prototype.name="polling",h.prototype.doOpen=function(){this.poll()},h.prototype.pause=function(t){var e=this;function r(){c("paused"),e.readyState="paused",t()}if(this.readyState="pausing",this.polling||!this.writable){var n=0;this.polling&&(c("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){c("pre-pause polling complete"),--n||r()})),this.writable||(c("we are currently writing - waiting to pause"),n++,this.once("drain",function(){c("pre-pause writing complete"),--n||r()}))}else r()},h.prototype.poll=function(){c("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},h.prototype.onData=function(t){var e=this;c("polling got data %s",t);i.decodePayload(t,this.socket.binaryType,function(t,r,n){if("opening"===e.readyState&&e.onOpen(),"close"===t.type)return e.onClose(),!1;e.onPacket(t)}),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():c('ignoring poll - transport state "%s"',this.readyState))},h.prototype.doClose=function(){var t=this;function e(){c("writing close packet"),t.write([{type:"close"}])}"open"===this.readyState?(c("transport open - closing"),e()):(c("transport not open - deferring close"),this.once("open",e))},h.prototype.write=function(t){var e=this;this.writable=!1;var r=function(){e.writable=!0,e.emit("drain")};i.encodePayload(t,this.supportsBinary,function(t){e.doWrite(t,r)})},h.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",r="";return!1!==this.timestampRequests&&(t[this.timestampParam]=a()),this.supportsBinary||t.sid||(t.b64=1),t=o.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(r=":"+this.port),t.length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t}},function(t,e,r){(function(e){var n=r(6),o=Object.prototype.toString,i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===o.call(Blob),s="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===o.call(File);t.exports=function t(r){if(!r||"object"!=typeof r)return!1;if(n(r)){for(var o=0,a=r.length;o<a;o++)if(t(r[o]))return!0;return!1}if("function"==typeof e&&e.isBuffer&&e.isBuffer(r)||"function"==typeof ArrayBuffer&&r instanceof ArrayBuffer||i&&r instanceof Blob||s&&r instanceof File)return!0;if(r.toJSON&&"function"==typeof r.toJSON&&1===arguments.length)return t(r.toJSON(),!0);for(var c in r)if(Object.prototype.hasOwnProperty.call(r,c)&&t(r[c]))return!0;return!1}}).call(this,r(7).Buffer)},function(t,e,r){"use strict";var n,o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),i=64,s={},a=0,c=0;function u(t){var e="";do{e=o[t%i]+e,t=Math.floor(t/i)}while(t>0);return e}function h(){var t=u(+new Date);return t!==n?(a=0,n=t):t+"."+u(a++)}for(;c<i;c++)s[o[c]]=c;h.encode=u,h.decode=function(t){var e=0;for(c=0;c<t.length;c++)e=e*i+s[t.charAt(c)];return e},t.exports=h},function(t,e){var r=[].indexOf;t.exports=function(t,e){if(r)return t.indexOf(e);for(var n=0;n<t.length;++n)if(t[n]===e)return n;return-1}},function(t,e,r){var n=r(5),o=r(1),i=r(45),s=r(20),a=r(21),c=r(0)("socket.io-client:socket"),u=r(3),h=r(16);t.exports=l;var f={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},p=o.prototype.emit;function l(t,e,r){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},r&&r.query&&(this.query=r.query),this.io.autoConnect&&this.open()}o(l.prototype),l.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[s(t,"open",a(this,"onopen")),s(t,"packet",a(this,"onpacket")),s(t,"close",a(this,"onclose"))]}},l.prototype.open=l.prototype.connect=function(){return this.connected?this:(this.subEvents(),this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting"),this)},l.prototype.send=function(){var t=i(arguments);return t.unshift("message"),this.emit.apply(this,t),this},l.prototype.emit=function(t){if(f.hasOwnProperty(t))return p.apply(this,arguments),this;var e=i(arguments),r={type:(void 0!==this.flags.binary?this.flags.binary:h(e))?n.BINARY_EVENT:n.EVENT,data:e,options:{}};return r.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(c("emitting packet with ack id %d",this.ids),this.acks[this.ids]=e.pop(),r.id=this.ids++),this.connected?this.packet(r):this.sendBuffer.push(r),this.flags={},this},l.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},l.prototype.onopen=function(){if(c("transport is open - connecting"),"/"!==this.nsp)if(this.query){var t="object"==typeof this.query?u.encode(this.query):this.query;c("sending connect packet with query %s",t),this.packet({type:n.CONNECT,query:t})}else this.packet({type:n.CONNECT})},l.prototype.onclose=function(t){c("close (%s)",t),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},l.prototype.onpacket=function(t){var e=t.nsp===this.nsp,r=t.type===n.ERROR&&"/"===t.nsp;if(e||r)switch(t.type){case n.CONNECT:this.onconnect();break;case n.EVENT:case n.BINARY_EVENT:this.onevent(t);break;case n.ACK:case n.BINARY_ACK:this.onack(t);break;case n.DISCONNECT:this.ondisconnect();break;case n.ERROR:this.emit("error",t.data)}},l.prototype.onevent=function(t){var e=t.data||[];c("emitting event %j",e),null!=t.id&&(c("attaching ack callback to event"),e.push(this.ack(t.id))),this.connected?p.apply(this,e):this.receiveBuffer.push(e)},l.prototype.ack=function(t){var e=this,r=!1;return function(){if(!r){r=!0;var o=i(arguments);c("sending ack %j",o),e.packet({type:h(o)?n.BINARY_ACK:n.ACK,id:t,data:o})}}},l.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e?(c("calling ack %s with %j",t.id,t.data),e.apply(this,t.data),delete this.acks[t.id]):c("bad ack %s",t.id)},l.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},l.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)p.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},l.prototype.ondisconnect=function(){c("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},l.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},l.prototype.close=l.prototype.disconnect=function(){return this.connected&&(c("performing disconnect (%s)",this.nsp),this.packet({type:n.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},l.prototype.compress=function(t){return this.flags.compress=t,this},l.prototype.binary=function(t){return this.flags.binary=t,this}},function(t,e){t.exports=function(t,e,r){return t.on(e,r),{destroy:function(){t.removeListener(e,r)}}}},function(t,e){var r=[].slice;t.exports=function(t,e){if("string"==typeof e&&(e=t[e]),"function"!=typeof e)throw new Error("bind() requires a function");var n=r.call(arguments,2);return function(){return e.apply(t,n.concat(r.call(arguments)))}}},function(t,e,r){var n=r(24),o=r(5),i=r(13),s=r(0)("socket.io-client");t.exports=e=c;var a=e.managers={};function c(t,e){"object"==typeof t&&(e=t,t=void 0),e=e||{};var r,o=n(t),c=o.source,u=o.id,h=o.path,f=a[u]&&h in a[u].nsps;return e.forceNew||e["force new connection"]||!1===e.multiplex||f?(s("ignoring socket cache for %s",c),r=i(c,e)):(a[u]||(s("new io instance for %s",c),a[u]=i(c,e)),r=a[u]),o.query&&!e.query&&(e.query=o.query),r.socket(o.path,e)}e.protocol=o.protocol,e.connect=c,e.Manager=r(13),e.Socket=r(19)},function(t,e,r){t.exports=r(47)},function(t,e,r){var n=r(10),o=r(0)("socket.io-client:url");t.exports=function(t,e){var r=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host);"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(o("protocol-less url %s",t),t=void 0!==e?e.protocol+"//"+t:"https://"+t),o("parse %s",t),r=n(t));r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443"));r.path=r.path||"/";var i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port,r.href=r.protocol+"://"+i+(e&&e.port===r.port?"":":"+r.port),r}},function(t,e){var r,n,o=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(r===setTimeout)return setTimeout(t,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(t){r=i}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(t){n=s}}();var c,u=[],h=!1,f=-1;function p(){h&&c&&(h=!1,c.length?u=c.concat(u):f=-1,u.length&&l())}function l(){if(!h){var t=a(p);h=!0;for(var e=u.length;e;){for(c=u,u=[];++f<e;)c&&c[f].run();f=-1,e=u.length}c=null,h=!1,function(t){if(n===clearTimeout)return clearTimeout(t);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(t);try{n(t)}catch(e){try{return n.call(null,t)}catch(e){return n.call(this,t)}}}(t)}}function d(t,e){this.fun=t,this.array=e}function y(){}o.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];u.push(new d(t,e)),1!==u.length||h||a(l)},d.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=y,o.addListener=y,o.once=y,o.off=y,o.removeListener=y,o.removeAllListeners=y,o.emit=y,o.prependListener=y,o.prependOnceListener=y,o.listeners=function(t){return[]},o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(t,e,r){function n(t){var r;function n(){if(n.enabled){var t=n,o=+new Date,i=o-(r||o);t.diff=i,t.prev=r,t.curr=o,r=o;for(var s=new Array(arguments.length),a=0;a<s.length;a++)s[a]=arguments[a];s[0]=e.coerce(s[0]),"string"!=typeof s[0]&&s.unshift("%O");var c=0;s[0]=s[0].replace(/%([a-zA-Z%])/g,function(r,n){if("%%"===r)return r;c++;var o=e.formatters[n];if("function"==typeof o){var i=s[c];r=o.call(t,i),s.splice(c,1),c--}return r}),e.formatArgs.call(t,s),(n.log||e.log||console.log.bind(console)).apply(t,s)}}return n.namespace=t,n.enabled=e.enabled(t),n.useColors=e.useColors(),n.color=function(t){var r,n=0;for(r in t)n=(n<<5)-n+t.charCodeAt(r),n|=0;return e.colors[Math.abs(n)%e.colors.length]}(t),n.destroy=o,"function"==typeof e.init&&e.init(n),e.instances.push(n),n}function o(){var t=e.instances.indexOf(this);return-1!==t&&(e.instances.splice(t,1),!0)}(e=t.exports=n.debug=n.default=n).coerce=function(t){return t instanceof Error?t.stack||t.message:t},e.disable=function(){e.enable("")},e.enable=function(t){var r;e.save(t),e.names=[],e.skips=[];var n=("string"==typeof t?t:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(t=n[r].replace(/\*/g,".*?"))[0]?e.skips.push(new RegExp("^"+t.substr(1)+"$")):e.names.push(new RegExp("^"+t+"$")));for(r=0;r<e.instances.length;r++){var i=e.instances[r];i.enabled=e.enabled(i.namespace)}},e.enabled=function(t){if("*"===t[t.length-1])return!0;var r,n;for(r=0,n=e.skips.length;r<n;r++)if(e.skips[r].test(t))return!1;for(r=0,n=e.names.length;r<n;r++)if(e.names[r].test(t))return!0;return!1},e.humanize=r(27),e.instances=[],e.names=[],e.skips=[],e.formatters={}},function(t,e){var r=1e3,n=60*r,o=60*n,i=24*o,s=365.25*i;function a(t,e,r){if(!(t<e))return t<1.5*e?Math.floor(t/e)+" "+r:Math.ceil(t/e)+" "+r+"s"}t.exports=function(t,e){e=e||{};var c,u=typeof t;if("string"===u&&t.length>0)return function(t){if((t=String(t)).length>100)return;var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(!e)return;var a=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return a*s;case"days":case"day":case"d":return a*i;case"hours":case"hour":case"hrs":case"hr":case"h":return a*o;case"minutes":case"minute":case"mins":case"min":case"m":return a*n;case"seconds":case"second":case"secs":case"sec":case"s":return a*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}(t);if("number"===u&&!1===isNaN(t))return e.long?a(c=t,i,"day")||a(c,o,"hour")||a(c,n,"minute")||a(c,r,"second")||c+" ms":function(t){if(t>=i)return Math.round(t/i)+"d";if(t>=o)return Math.round(t/o)+"h";if(t>=n)return Math.round(t/n)+"m";if(t>=r)return Math.round(t/r)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,r){var n=r(6),o=r(11),i=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===i.call(Blob),a="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===i.call(File);e.deconstructPacket=function(t){var e=[],r=t.data,i=t;return i.data=function t(e,r){if(!e)return e;if(o(e)){var i={_placeholder:!0,num:r.length};return r.push(e),i}if(n(e)){for(var s=new Array(e.length),a=0;a<e.length;a++)s[a]=t(e[a],r);return s}if("object"==typeof e&&!(e instanceof Date)){var s={};for(var c in e)s[c]=t(e[c],r);return s}return e}(r,e),i.attachments=e.length,{packet:i,buffers:e}},e.reconstructPacket=function(t,e){return t.data=function t(e,r){if(!e)return e;if(e&&e._placeholder)return r[e.num];if(n(e))for(var o=0;o<e.length;o++)e[o]=t(e[o],r);else if("object"==typeof e)for(var i in e)e[i]=t(e[i],r);return e}(t.data,e),t.attachments=void 0,t},e.removeBlobs=function(t,e){var r=0,i=t;!function t(c,u,h){if(!c)return c;if(s&&c instanceof Blob||a&&c instanceof File){r++;var f=new FileReader;f.onload=function(){h?h[u]=this.result:i=this.result,--r||e(i)},f.readAsArrayBuffer(c)}else if(n(c))for(var p=0;p<c.length;p++)t(c[p],p,c);else if("object"==typeof c&&!o(c))for(var l in c)t(c[l],l,c)}(i),r||e(i)}},function(t,e,r){"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){for(var e,r=u(t),n=r[0],s=r[1],a=new i(function(t,e,r){return 3*(e+r)/4-r}(0,n,s)),c=0,h=s>0?n-4:n,f=0;f<h;f+=4)e=o[t.charCodeAt(f)]<<18|o[t.charCodeAt(f+1)]<<12|o[t.charCodeAt(f+2)]<<6|o[t.charCodeAt(f+3)],a[c++]=e>>16&255,a[c++]=e>>8&255,a[c++]=255&e;2===s&&(e=o[t.charCodeAt(f)]<<2|o[t.charCodeAt(f+1)]>>4,a[c++]=255&e);1===s&&(e=o[t.charCodeAt(f)]<<10|o[t.charCodeAt(f+1)]<<4|o[t.charCodeAt(f+2)]>>2,a[c++]=e>>8&255,a[c++]=255&e);return a},e.fromByteArray=function(t){for(var e,r=t.length,o=r%3,i=[],s=0,a=r-o;s<a;s+=16383)i.push(h(t,s,s+16383>a?a:s+16383));1===o?(e=t[r-1],i.push(n[e>>2]+n[e<<4&63]+"==")):2===o&&(e=(t[r-2]<<8)+t[r-1],i.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a<c;++a)n[a]=s[a],o[s.charCodeAt(a)]=a;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function h(t,e,r){for(var o,i,s=[],a=e;a<r;a+=3)o=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(255&t[a+2]),s.push(n[(i=o)>>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(t,e){e.read=function(t,e,r,n,o){var i,s,a=8*o-n-1,c=(1<<a)-1,u=c>>1,h=-7,f=r?o-1:0,p=r?-1:1,l=t[e+f];for(f+=p,i=l&(1<<-h)-1,l>>=-h,h+=a;h>0;i=256*i+t[e+f],f+=p,h-=8);for(s=i&(1<<-h)-1,i>>=-h,h+=n;h>0;s=256*s+t[e+f],f+=p,h-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(l?-1:1);s+=Math.pow(2,n),i-=u}return(l?-1:1)*s*Math.pow(2,i-n)},e.write=function(t,e,r,n,o,i){var s,a,c,u=8*i-o-1,h=(1<<u)-1,f=h>>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:i-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),(e+=s+f>=1?p/c:p*Math.pow(2,1-f))*c>=2&&(s++,c/=2),s+f>=h?(a=0,s=h):s+f>=1?(a=(e*c-1)*Math.pow(2,o),s+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,o),s=0));o>=8;t[r+l]=255&a,l+=d,a/=256,o-=8);for(s=s<<o|a,u+=o;u>0;t[r+l]=255&s,l+=d,s/=256,u-=8);t[r+l-d]|=128*y}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){t.exports=r(33),t.exports.parser=r(2)},function(t,e,r){var n=r(14),o=r(1),i=r(0)("engine.io-client:socket"),s=r(18),a=r(2),c=r(10),u=r(3);function h(t,e){if(!(this instanceof h))return new h(t,e);e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=c(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=c(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=u.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}t.exports=h,h.priorWebsocketSuccess=!1,o(h.prototype),h.protocol=a.protocol,h.Socket=h,h.Transport=r(9),h.transports=r(14),h.parser=r(2),h.prototype.createTransport=function(t){i('creating transport "%s"',t);var e=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}(this.query);e.EIO=a.protocol,e.transport=t;var r=this.transportOptions[t]||{};return this.id&&(e.sid=this.id),new n[t]({query:e,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative})},h.prototype.open=function(){var t;if(this.rememberUpgrade&&h.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout(function(){e.emit("error","No transports available")},0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},h.prototype.setTransport=function(t){i("setting transport %s",t.name);var e=this;this.transport&&(i("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",function(){e.onDrain()}).on("packet",function(t){e.onPacket(t)}).on("error",function(t){e.onError(t)}).on("close",function(){e.onClose("transport close")})},h.prototype.probe=function(t){i('probing transport "%s"',t);var e=this.createTransport(t,{probe:1}),r=!1,n=this;function o(){if(n.onlyBinaryUpgrades){var o=!this.supportsBinary&&n.transport.supportsBinary;r=r||o}r||(i('probe transport "%s" opened',t),e.send([{type:"ping",data:"probe"}]),e.once("packet",function(o){if(!r)if("pong"===o.type&&"probe"===o.data){if(i('probe transport "%s" pong',t),n.upgrading=!0,n.emit("upgrading",e),!e)return;h.priorWebsocketSuccess="websocket"===e.name,i('pausing current transport "%s"',n.transport.name),n.transport.pause(function(){r||"closed"!==n.readyState&&(i("changing transport and sending upgrade packet"),p(),n.setTransport(e),e.send([{type:"upgrade"}]),n.emit("upgrade",e),e=null,n.upgrading=!1,n.flush())})}else{i('probe transport "%s" failed',t);var s=new Error("probe error");s.transport=e.name,n.emit("upgradeError",s)}}))}function s(){r||(r=!0,p(),e.close(),e=null)}function a(r){var o=new Error("probe error: "+r);o.transport=e.name,s(),i('probe transport "%s" failed because of error: %s',t,r),n.emit("upgradeError",o)}function c(){a("transport closed")}function u(){a("socket closed")}function f(t){e&&t.name!==e.name&&(i('"%s" works - aborting "%s"',t.name,e.name),s())}function p(){e.removeListener("open",o),e.removeListener("error",a),e.removeListener("close",c),n.removeListener("close",u),n.removeListener("upgrading",f)}h.priorWebsocketSuccess=!1,e.once("open",o),e.once("error",a),e.once("close",c),this.once("close",u),this.once("upgrading",f),e.open()},h.prototype.onOpen=function(){if(i("socket open"),this.readyState="open",h.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){i("starting upgrade probes");for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])}},h.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(i('socket receive: type "%s", data "%s"',t.type,t.data),this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}else i('packet received with socket readyState "%s"',this.readyState)},h.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},h.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout(function(){"closed"!==e.readyState&&e.onClose("ping timeout")},t||e.pingInterval+e.pingTimeout)},h.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout(function(){i("writing ping packet - expecting pong within %sms",t.pingTimeout),t.ping(),t.onHeartbeat(t.pingTimeout)},t.pingInterval)},h.prototype.ping=function(){var t=this;this.sendPacket("ping",function(){t.emit("ping")})},h.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},h.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(i("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},h.prototype.write=h.prototype.send=function(t,e,r){return this.sendPacket("message",t,e,r),this},h.prototype.sendPacket=function(t,e,r,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof r&&(n=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){(r=r||{}).compress=!1!==r.compress;var o={type:t,data:e,options:r};this.emit("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}},h.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var t=this;this.writeBuffer.length?this.once("drain",function(){this.upgrading?n():e()}):this.upgrading?n():e()}function e(){t.onClose("forced close"),i("socket closing - telling transport to close"),t.transport.close()}function r(){t.removeListener("upgrade",r),t.removeListener("upgradeError",r),e()}function n(){t.once("upgrade",r),t.once("upgradeError",r)}return this},h.prototype.onError=function(t){i("socket error %j",t),h.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},h.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){i('socket close with reason: "%s"',t);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),this.writeBuffer=[],this.prevBufferLen=0}},h.prototype.filterUpgrades=function(t){for(var e=[],r=0,n=t.length;r<n;r++)~s(this.transports,t[r])&&e.push(t[r]);return e}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e,r){var n=r(8),o=r(15),i=r(1),s=r(4),a=r(0)("engine.io-client:polling-xhr");function c(){}function u(t){if(o.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,r=location.port;r||(r=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||r!==t.port,this.xs=t.secure!==e}}function h(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}if(t.exports=u,t.exports.Request=h,s(u,o),u.prototype.supportsBinary=!0,u.prototype.request=function(t){return(t=t||{}).uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new h(t)},u.prototype.doWrite=function(t,e){var r="string"!=typeof t&&void 0!==t,n=this.request({method:"POST",data:t,isBinary:r}),o=this;n.on("success",e),n.on("error",function(t){o.onError("xhr post error",t)}),this.sendXhr=n},u.prototype.doPoll=function(){a("xhr poll");var t=this.request(),e=this;t.on("data",function(t){e.onData(t)}),t.on("error",function(t){e.onError("xhr poll error",t)}),this.pollXhr=t},i(h.prototype),h.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new n(t),r=this;try{a("xhr open %s: %s",this.method,this.uri),e.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var o in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(o)&&e.setRequestHeader(o,this.extraHeaders[o])}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=!0),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){r.onLoad()},e.onerror=function(){r.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");r.supportsBinary&&"application/octet-stream"===t&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?r.onLoad():setTimeout(function(){r.onError(e.status)},0))},a("xhr data %s",this.data),e.send(this.data)}catch(t){return void setTimeout(function(){r.onError(t)},0)}"undefined"!=typeof document&&(this.index=h.requestsCount++,h.requests[this.index]=this)},h.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},h.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},h.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},h.prototype.cleanup=function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=c:this.xhr.onreadystatechange=c,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete h.requests[this.index],this.xhr=null}},h.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t="application/octet-stream"===e&&this.xhr.response||this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},h.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},h.prototype.abort=function(){this.cleanup()},h.requestsCount=0,h.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",p);else if("function"==typeof addEventListener){var f="onpagehide"in self?"pagehide":"unload";addEventListener(f,p,!1)}function p(){for(var t in h.requests)h.requests.hasOwnProperty(t)&&h.requests[t].abort()}},function(t,e){t.exports=Object.keys||function(t){var e=[],r=Object.prototype.hasOwnProperty;for(var n in t)r.call(t,n)&&e.push(n);return e}},function(t,e){t.exports=function(t,e,r){var n=t.byteLength;if(e=e||0,r=r||n,t.slice)return t.slice(e,r);if(e<0&&(e+=n),r<0&&(r+=n),r>n&&(r=n),e>=n||e>=r||0===n)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(r-e),s=e,a=0;s<r;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function r(){}t.exports=function(t,e,n){var o=!1;return n=n||r,i.count=t,0===t?e():i;function i(t,r){if(i.count<=0)throw new Error("after called too many times");--i.count,t?(o=!0,e(t),e=n):0!==i.count||o||e(null,r)}}},function(t,e){ /*! https://mths.be/utf8js v2.1.2 by @mathias */ var r,n,o,i=String.fromCharCode;function s(t){for(var e,r,n=[],o=0,i=t.length;o<i;)(e=t.charCodeAt(o++))>=55296&&e<=56319&&o<i?56320==(64512&(r=t.charCodeAt(o++)))?n.push(((1023&e)<<10)+(1023&r)+65536):(n.push(e),o--):n.push(e);return n}function a(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function c(t,e){return i(t>>e&63|128)}function u(t,e){if(0==(4294967168&t))return i(t);var r="";return 0==(4294965248&t)?r=i(t>>6&31|192):0==(4294901760&t)?(a(t,e)||(t=65533),r=i(t>>12&15|224),r+=c(t,6)):0==(4292870144&t)&&(r=i(t>>18&7|240),r+=c(t,12),r+=c(t,6)),r+=i(63&t|128)}function h(){if(o>=n)throw Error("Invalid byte index");var t=255&r[o];if(o++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function f(t){var e,i;if(o>n)throw Error("Invalid byte index");if(o==n)return!1;if(e=255&r[o],o++,0==(128&e))return e;if(192==(224&e)){if((i=(31&e)<<6|h())>=128)return i;throw Error("Invalid continuation byte")}if(224==(240&e)){if((i=(15&e)<<12|h()<<6|h())>=2048)return a(i,t)?i:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(i=(7&e)<<18|h()<<12|h()<<6|h())>=65536&&i<=1114111)return i;throw Error("Invalid UTF-8 detected")}t.exports={version:"2.1.2",encode:function(t,e){for(var r=!1!==(e=e||{}).strict,n=s(t),o=n.length,i=-1,a="";++i<o;)a+=u(n[i],r);return a},decode:function(t,e){var a=!1!==(e=e||{}).strict;r=s(t),n=r.length,o=0;for(var c,u=[];!1!==(c=f(a));)u.push(c);return function(t){for(var e,r=t.length,n=-1,o="";++n<r;)(e=t[n])>65535&&(o+=i((e-=65536)>>>10&1023|55296),e=56320|1023&e),o+=i(e);return o}(u)}}},function(t,e){!function(){"use strict";for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=new Uint8Array(256),n=0;n<t.length;n++)r[t.charCodeAt(n)]=n;e.encode=function(e){var r,n=new Uint8Array(e),o=n.length,i="";for(r=0;r<o;r+=3)i+=t[n[r]>>2],i+=t[(3&n[r])<<4|n[r+1]>>4],i+=t[(15&n[r+1])<<2|n[r+2]>>6],i+=t[63&n[r+2]];return o%3==2?i=i.substring(0,i.length-1)+"=":o%3==1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(t){var e,n,o,i,s,a=.75*t.length,c=t.length,u=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);var h=new ArrayBuffer(a),f=new Uint8Array(h);for(e=0;e<c;e+=4)n=r[t.charCodeAt(e)],o=r[t.charCodeAt(e+1)],i=r[t.charCodeAt(e+2)],s=r[t.charCodeAt(e+3)],f[u++]=n<<2|o>>4,f[u++]=(15&o)<<4|i>>2,f[u++]=(3&i)<<6|63&s;return h}}()},function(t,e){var r=void 0!==r?r:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,n=function(){try{return 2===new Blob(["hi"]).size}catch(t){return!1}}(),o=n&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(t){return!1}}(),i=r&&r.prototype.append&&r.prototype.getBlob;function s(t){return t.map(function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var r=new Uint8Array(t.byteLength);r.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=r.buffer}return e}return t})}function a(t,e){e=e||{};var n=new r;return s(t).forEach(function(t){n.append(t)}),e.type?n.getBlob(e.type):n.getBlob()}function c(t,e){return new Blob(s(t),e||{})}"undefined"!=typeof Blob&&(a.prototype=Blob.prototype,c.prototype=Blob.prototype),t.exports=n?o?Blob:c:i?a:void 0},function(t,e,r){(function(e){var n=r(15),o=r(4);t.exports=h;var i,s=/\n/g,a=/\\n/g;function c(){}function u(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==e?e:{}}function h(t){if(n.call(this,t),this.query=this.query||{},!i){var e=u();i=e.___eio=e.___eio||[]}this.index=i.length;var r=this;i.push(function(t){r.onData(t)}),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",function(){r.script&&(r.script.onerror=c)},!1)}o(h,n),h.prototype.supportsBinary=!1,h.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),n.prototype.doClose.call(this)},h.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(e,r):(document.head||document.body).appendChild(e),this.script=e,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout(function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)},100)},h.prototype.doWrite=function(t,e){var r=this;if(!this.form){var n,o=document.createElement("form"),i=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;o.className="socketio",o.style.position="absolute",o.style.top="-1000px",o.style.left="-1000px",o.target=c,o.method="POST",o.setAttribute("accept-charset","utf-8"),i.name="d",o.appendChild(i),document.body.appendChild(o),this.form=o,this.area=i}function u(){h(),e()}function h(){if(r.iframe)try{r.form.removeChild(r.iframe)}catch(t){r.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+r.iframeId+'">';n=document.createElement(t)}catch(t){(n=document.createElement("iframe")).name=r.iframeId,n.src="javascript:0"}n.id=r.iframeId,r.form.appendChild(n),r.iframe=n}this.form.action=this.uri(),h(),t=t.replace(a,"\\\n"),this.area.value=t.replace(s,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===r.iframe.readyState&&u()}:this.iframe.onload=u}}).call(this,r(12))},function(t,e,r){(function(e){var n,o,i=r(9),s=r(2),a=r(3),c=r(4),u=r(17),h=r(0)("engine.io-client:websocket");if("undefined"!=typeof WebSocket)n=WebSocket;else if("undefined"!=typeof self)n=self.WebSocket||self.MozWebSocket;else try{o=r(44)}catch(t){}var f=n||o;function p(t){t&&t.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=n&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(f=o),i.call(this,t)}t.exports=p,c(p,i),p.prototype.name="websocket",p.prototype.supportsBinary=!0,p.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,r={agent:this.agent,perMessageDeflate:this.perMessageDeflate};r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized,this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new f(t,e):new f(t):new f(t,e,r)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},p.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},p.prototype.write=function(t){var r=this;this.writable=!1;for(var n=t.length,o=0,i=n;o<i;o++)!function(t){s.encodePacket(t,r.supportsBinary,function(o){if(!r.usingBrowserWebSocket){var i={};if(t.options&&(i.compress=t.options.compress),r.perMessageDeflate)("string"==typeof o?e.byteLength(o):o.length)<r.perMessageDeflate.threshold&&(i.compress=!1)}try{r.usingBrowserWebSocket?r.ws.send(o):r.ws.send(o,i)}catch(t){h("websocket closed before onclose event")}--n||a()})}(t[o]);function a(){r.emit("flush"),setTimeout(function(){r.writable=!0,r.emit("drain")},0)}},p.prototype.onClose=function(){i.prototype.onClose.call(this)},p.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},p.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",r="";return this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(r=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=u()),this.supportsBinary||(t.b64=1),(t=a.encode(t)).length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t},p.prototype.check=function(){return!(!f||"__initialize"in f&&this.name===p.prototype.name)}}).call(this,r(7).Buffer)},function(t,e){},function(t,e){t.exports=function(t,e){for(var r=[],n=(e=e||0)||0;n<t.length;n++)r[n-e]=t[n];return r}},function(t,e){function r(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=r,r.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),r=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-r:t+r}return 0|Math.min(t,this.max)},r.prototype.reset=function(){this.attempts=0},r.prototype.setMin=function(t){this.ms=t},r.prototype.setMax=function(t){this.max=t},r.prototype.setJitter=function(t){this.jitter=t}},function(t,e,r){"use strict";r.r(e);var n={beforeCreate(){this.sockets||(this.sockets={}),this.sockets.subscribe=((t,e)=>{this.$vueSocketIo.emitter.addListener(t,e,this)}),this.sockets.unsubscribe=(t=>{this.$vueSocketIo.emitter.removeListener(t,this)})},mounted(){this.$options.sockets&&Object.keys(this.$options.sockets).forEach(t=>{"subscribe"!==t&&"unsubscribe"!==t&&this.$vueSocketIo.emitter.addListener(t,this.$options.sockets[t],this)})},beforeDestroy(){this.$options.sockets&&Object.keys(this.$options.sockets).forEach(t=>{this.$vueSocketIo.emitter.removeListener(t,this)})}};function o(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var i=new(function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.debug=!1,this.prefix="%cVue-Socket.io: "}var e,r,n;return e=t,(r=[{key:"info",value:function(t,e=""){this.debug&&window.console.info(this.prefix+`%c${t}`,"color: blue; font-weight: 600","color: #333333",e)}},{key:"error",value:function(){this.debug&&window.console.error(this.prefix,...arguments)}},{key:"warn",value:function(){this.debug&&window.console.warn(this.prefix,...arguments)}},{key:"event",value:function(t,e=""){this.debug&&window.console.info(this.prefix+`%c${t}`,"color: blue; font-weight: 600","color: #333333",e)}}])&&o(e.prototype,r),n&&o(e,n),t}());function s(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}let a=function(){function t(e,r){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.io=e,this.register(),this.emitter=r}var e,r,n;return e=t,(r=[{key:"register",value:function(){this.io.onevent=(t=>{let[e,...r]=t.data;1===r.length&&(r=r[0]),this.onEvent(e,r)}),t.staticEvents.forEach(t=>this.io.on(t,e=>this.onEvent(t,e)))}},{key:"onEvent",value:function(t,e){this.emitter.emit(t,e)}}])&&s(e.prototype,r),n&&s(e,n),t}();var c,u,h;function f(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}h=["connect","error","disconnect","reconnect","reconnect_attempt","reconnecting","reconnect_error","reconnect_failed","connect_error","connect_timeout","connecting","ping","pong"],(u="staticEvents")in(c=a)?Object.defineProperty(c,u,{value:h,enumerable:!0,configurable:!0,writable:!0}):c[u]=h;let p=function(){function t(e={}){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),i.info(e?"Vuex adapter enabled":"Vuex adapter disabled"),i.info(e.mutationPrefix?"Vuex socket mutations enabled":"Vuex socket mutations disabled"),i.info(e?"Vuex socket actions enabled":"Vuex socket actions disabled"),this.store=e.store,this.actionPrefix=e.actionPrefix?e.actionPrefix:"SOCKET_",this.mutationPrefix=e.mutationPrefix,this.listeners=new Map}var e,r,n;return e=t,(r=[{key:"addListener",value:function(t,e,r){if("function"!=typeof e)throw new Error("callback must be a function");this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t).push({callback:e,component:r}),i.info(`#${t} subscribe, component: ${r.$options.name}`)}},{key:"removeListener",value:function(t,e){if(this.listeners.has(t)){const r=this.listeners.get(t).filter(t=>t.component!==e);r.length>0?this.listeners.set(t,r):this.listeners.delete(t),i.info(`#${t} unsubscribe, component: ${e.$options.name}`)}}},{key:"emit",value:function(t,e){this.listeners.has(t)&&(i.info(`Broadcasting: #${t}, Data:`,e),this.listeners.get(t).forEach(t=>{t.callback.call(t.component,e)})),"ping"!==t&&"pong"!==t&&this.dispatchStore(t,e)}},{key:"dispatchStore",value:function(t,e){if(this.store&&this.store._actions){let r=this.actionPrefix+t;for(let t in this.store._actions){t.split("/").pop()===r&&(i.info(`Dispatching Action: ${t}, Data:`,e),this.store.dispatch(t,e))}if(this.mutationPrefix){let r=this.mutationPrefix+t;for(let t in this.store._mutations){t.split("/").pop()===r&&(i.info(`Commiting Mutation: ${t}, Data:`,e),this.store.commit(t,e))}}}}}])&&f(e.prototype,r),n&&f(e,n),t}();var l=r(22),d=r.n(l);function y(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}r.d(e,"default",function(){return g});let g=function(){function t({connection:e,vuex:r,debug:n,options:o}){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),i.debug=n,this.io=this.connect(e,o),this.emitter=new p(r),this.listener=new a(this.io,this.emitter)}var e,r,o;return e=t,(r=[{key:"install",value:function(t){t.prototype.$socket=this.io,t.prototype.$vueSocketIo=this,t.mixin(n),i.info("Vue-Socket.io plugin enabled")}},{key:"connect",value:function(t,e){if(t&&"object"==typeof t)return i.info("Received socket.io-client instance"),t;if("string"==typeof t)return i.info("Received connection string"),this.io=d()(t,e);throw new Error("Unsupported connection type")}}])&&y(e.prototype,r),o&&y(e,o),t}()}]).default}); /***/ }), /***/ "./node_modules/vue/dist/vue.common.dev.js": /*!*************************************************!*\ !*** ./node_modules/vue/dist/vue.common.dev.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global, setImmediate) {/*! * Vue.js v2.6.12 * (c) 2014-2020 Evan You * Released under the MIT License. */ /* */ var emptyObject = Object.freeze({}); // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive. */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value, e.g., [object Object]. */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } function isPromise (val) { return ( isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function' ) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val) } /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if an attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array. */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether an object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind polyfill for environments that do not support it, * e.g., PhantomJS 1.x. Technically, we don't need this anymore * since native bind is now performant enough in most browsers. * But removing it would mean breaking code that was able to run in * PhantomJS 1.x, so this must be kept for backward compatibility. */ /* istanbul ignore next */ function polyfillBind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length; return boundFn } function nativeBind (fn, ctx) { return fn.bind(ctx) } var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /* eslint-disable no-unused-vars */ /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /* eslint-enable no-unused-vars */ /** * Return the same value. */ var identity = function (_) { return _; }; /** * Generate a string containing static keys from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime() } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } /** * Return the first index at which a loosely equal value can be * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured', 'serverPrefetch' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ // $flow-disable-line optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: "development" !== 'production', /** * Whether to enable devtools */ devtools: "development" !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ // $flow-disable-line keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Perform updates asynchronously. Intended to be used by Vue Test Utils * This will significantly reduce performance if set to false. */ async: true, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ /** * unicode letters used for parsing html tags, component names and property paths. * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname * skipping \u10000-\uEFFFF due to it freezing up PhantomJS */ var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/; /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]")); function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; var isPhantomJS = UA && /phantomjs/.test(UA); var isFF = UA && UA.match(/firefox\/(\d+)/); // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && !inWeex && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = /*@__PURE__*/(function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); if (!config.async) { // subs aren't sorted in scheduler if not running async // we need to sort them now to make sure they fire in correct // order subs.sort(function (a, b) { return a.id - b.id; }); } for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // The current target watcher being evaluated. // This is globally unique because only one watcher // can be evaluated at a time. Dep.target = null; var targetStack = []; function pushTarget (target) { targetStack.push(target); Dep.target = target; } function popTarget () { targetStack.pop(); Dep.target = targetStack[targetStack.length - 1]; } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.fnContext = undefined; this.fnOptions = undefined; this.fnScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, // #7975 // clone children array to avoid mutating original in case of cloning // a child. vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.fnContext = vnode.fnContext; cloned.fnOptions = vnode.fnOptions; cloned.fnScopeId = vnode.fnScopeId; cloned.asyncMeta = vnode.asyncMeta; cloned.isCloned = true; return cloned } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); var methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * In some cases we may want to disable observation inside a component's * update computation. */ var shouldObserve = true; function toggleObserving (value) { shouldObserve = value; } /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { if (hasProto) { protoAugment(value, arrayMethods); } else { copyAugment(value, arrayMethods, arrayKeys); } this.observeArray(value); } else { this.walk(value); } }; /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment a target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment a target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; if ((!getter || setter) && arguments.length === 2) { val = obj[key]; } var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (customSetter) { customSetter(); } // #7981: for accessor properties without setter if (getter && !setter) { return } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = hasSymbol ? Reflect.ownKeys(from) : Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; // in case the object is already observed... if (key === '__ob__') { continue } toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if ( toVal !== fromVal && isPlainObject(toVal) && isPlainObject(fromVal) ) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this, this) : childVal, typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal ) } } else { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res } function dedupeHooks (hooks) { var res = []; for (var i = 0; i < hooks.length; i++) { if (res.indexOf(hooks[i]) === -1) { res.push(hooks[i]); } } return res } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && "development" !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { validateComponentName(key); } } function validateComponentName (name) { if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'should conform to valid custom element name in html5 specification.' ); } if (isBuiltInTag(name) || config.isReservedTag(name)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + name ); } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; if (!inject) { return } var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def$$1 = dirs[key]; if (typeof def$$1 === 'function') { dirs[key] = { bind: def$$1, update: def$$1 }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); // Apply extends and mixins on the child options, // but only if it is a raw options object that isn't // the result of another mergeOptions call. // Only merged options has the _base property. if (!child._base) { if (child.extends) { parent = mergeOptions(parent, child.extends, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // boolean casting var booleanIndex = getTypeIndex(Boolean, prop.type); if (booleanIndex > -1) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { // only cast empty string / same name to boolean if // boolean has higher priority var stringIndex = getTypeIndex(String, prop.type); if (stringIndex < 0 || booleanIndex < stringIndex) { value = true; } } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldObserve = shouldObserve; toggleObserving(true); observe(value); toggleObserving(prevShouldObserve); } { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( getInvalidTypeMessage(name, value, expectedTypes), vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isSameType (a, b) { return getType(a) === getType(b) } function getTypeIndex (type, expectedTypes) { if (!Array.isArray(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } for (var i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } return -1 } function getInvalidTypeMessage (name, value, expectedTypes) { var message = "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')); var expectedType = expectedTypes[0]; var receivedType = toRawType(value); var expectedValue = styleValue(value, expectedType); var receivedValue = styleValue(value, receivedType); // check if we need to specify expected value if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) { message += " with value " + expectedValue; } message += ", got " + receivedType + " "; // check if we need to specify received value if (isExplicable(receivedType)) { message += "with value " + receivedValue + "."; } return message } function styleValue (value, type) { if (type === 'String') { return ("\"" + value + "\"") } else if (type === 'Number') { return ("" + (Number(value))) } else { return ("" + value) } } function isExplicable (value) { var explicitTypes = ['string', 'number', 'boolean']; return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; }) } function isBoolean () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }) } /* */ function handleError (err, vm, info) { // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. // See: https://github.com/vuejs/vuex/issues/1505 pushTarget(); try { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } finally { popTarget(); } } function invokeWithErrorHandling ( handler, context, args, vm, info ) { var res; try { res = args ? handler.apply(context, args) : handler.call(context); if (res && !res._isVue && isPromise(res) && !res._handled) { res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); // issue #9511 // avoid catch triggering multiple times when nested calls res._handled = true; } } catch (e) { handleError(e, vm, info); } return res } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { // if the user intentionally throws the original error in the handler, // do not log it twice if (e !== err) { logError(e, null, 'config.errorHandler'); } } } logError(err, vm, info); } function logError (err, vm, info) { { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if ((inBrowser || inWeex) && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ var isUsingMicroTask = false; var callbacks = []; var pending = false; function flushCallbacks () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // Here we have async deferring wrappers using microtasks. // In 2.5 we used (macro) tasks (in combination with microtasks). // However, it has subtle problems when state is changed right before repaint // (e.g. #6813, out-in transitions). // Also, using (macro) tasks in event handler would cause some weird behaviors // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109). // So we now use microtasks everywhere, again. // A major drawback of this tradeoff is that there are some scenarios // where microtasks have too high a priority and fire in between supposedly // sequential events (e.g. #4521, #6690, which have workarounds) // or even between bubbling of the same event (#6566). var timerFunc; // The nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); timerFunc = function () { p.then(flushCallbacks); // In problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; isUsingMicroTask = true; } else if (!isIE && typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // Use MutationObserver where native Promise is not available, // e.g. PhantomJS, iOS7, Android 4.4 // (#6466 MutationObserver is unreliable in IE11) var counter = 1; var observer = new MutationObserver(flushCallbacks); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; isUsingMicroTask = true; } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { // Fallback to setImmediate. // Technically it leverages the (macro) task queue, // but it is still a better choice than setTimeout. timerFunc = function () { setImmediate(flushCallbacks); }; } else { // Fallback to setTimeout. timerFunc = function () { setTimeout(flushCallbacks, 0); }; } function nextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } /* */ var mark; var measure; { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); // perf.clearMeasures(name) }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var warnReservedPrefix = function (target, key) { warn( "Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " + 'properties starting with "$" or "_" are not proxied in the Vue instance to ' + 'prevent conflicts with Vue internals. ' + 'See: https://vuejs.org/v2/api/#data', target ); }; var hasProxy = typeof Proxy !== 'undefined' && isNative(Proxy); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data)); if (!has && !isAllowed) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var seenObjects = new _Set(); /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ function traverse (val) { _traverse(val, seenObjects); seenObjects.clear(); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns, vm) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); } } else { // return handler return value for single handlers return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler") } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, createOnceHandler, vm ) { var name, def$$1, cur, old, event; for (name in on) { def$$1 = cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur, vm); } if (isTrue(event.once)) { cur = on[name] = createOnceHandler(event.name, cur, event.capture); } add(event.name, cur, event.capture, event.passive, event.params); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { if (def instanceof VNode) { def = def.data.hook || (def.data.hook = {}); } var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, lastIndex, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } lastIndex = res.length - 1; last = res[lastIndex]; // nested if (Array.isArray(c)) { if (c.length > 0) { c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)); // merge adjacent text nodes if (isTextNode(c[0]) && isTextNode(last)) { res[lastIndex] = createTextVNode(last.text + (c[0]).text); c.shift(); } res.push.apply(res, c); } } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings res[lastIndex] = createTextVNode(last.text + c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[lastIndex] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { toggleObserving(false); Object.keys(result).forEach(function (key) { /* istanbul ignore else */ { defineReactive$$1(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } }); toggleObserving(true); } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); var keys = hasSymbol ? Reflect.ownKeys(inject) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; // #6574 in case the inject object is observed... if (key === '__ob__') { continue } var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && hasOwn(source._provided, provideKey)) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (!source) { if ('default' in inject[key]) { var provideDefault = inject[key].default; result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else { warn(("Injection \"" + key + "\" not found"), vm); } } } return result } } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { if (!children || !children.length) { return {} } var slots = {}; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var data = child.data; // remove slot attribute if the node is resolved as a Vue slot node if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot; } // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.fnContext === context) && data && data.slot != null ) { var name = data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children || []); } else { slot.push(child); } } else { (slots.default || (slots.default = [])).push(child); } } // ignore slots that contains only whitespace for (var name$1 in slots) { if (slots[name$1].every(isWhitespace)) { delete slots[name$1]; } } return slots } function isWhitespace (node) { return (node.isComment && !node.asyncFactory) || node.text === ' ' } /* */ function normalizeScopedSlots ( slots, normalSlots, prevSlots ) { var res; var hasNormalSlots = Object.keys(normalSlots).length > 0; var isStable = slots ? !!slots.$stable : !hasNormalSlots; var key = slots && slots.$key; if (!slots) { res = {}; } else if (slots._normalized) { // fast path 1: child component re-render only, parent did not change return slots._normalized } else if ( isStable && prevSlots && prevSlots !== emptyObject && key === prevSlots.$key && !hasNormalSlots && !prevSlots.$hasNormal ) { // fast path 2: stable scoped slots w/ no normal slots to proxy, // only need to normalize once return prevSlots } else { res = {}; for (var key$1 in slots) { if (slots[key$1] && key$1[0] !== '$') { res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]); } } } // expose normal slots on scopedSlots for (var key$2 in normalSlots) { if (!(key$2 in res)) { res[key$2] = proxyNormalSlot(normalSlots, key$2); } } // avoriaz seems to mock a non-extensible $scopedSlots object // and when that is passed down this would cause an error if (slots && Object.isExtensible(slots)) { (slots)._normalized = res; } def(res, '$stable', isStable); def(res, '$key', key); def(res, '$hasNormal', hasNormalSlots); return res } function normalizeScopedSlot(normalSlots, key, fn) { var normalized = function () { var res = arguments.length ? fn.apply(null, arguments) : fn({}); res = res && typeof res === 'object' && !Array.isArray(res) ? [res] // single vnode : normalizeChildren(res); return res && ( res.length === 0 || (res.length === 1 && res[0].isComment) // #9658 ) ? undefined : res }; // this is a slot using the new v-slot syntax without scope. although it is // compiled as a scoped slot, render fn users would expect it to be present // on this.$slots because the usage is semantically a normal slot. if (fn.proxy) { Object.defineProperty(normalSlots, key, { get: normalized, enumerable: true, configurable: true }); } return normalized } function proxyNormalSlot(slots, key) { return function () { return slots[key]; } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { if (hasSymbol && val[Symbol.iterator]) { ret = []; var iterator = val[Symbol.iterator](); var result = iterator.next(); while (!result.done) { ret.push(render(result.value, ret.length)); result = iterator.next(); } } else { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } } if (!isDef(ret)) { ret = []; } (ret)._isVList = true; return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; var nodes; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { if (!isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } props = extend(extend({}, bindObject), props); } nodes = scopedSlotFn(props) || fallback; } else { nodes = this.$slots[name] || fallback; } var target = props && props.slot; if (target) { return this.$createElement('template', { slot: target }, nodes) } else { return nodes } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ function isKeyNotMatch (expect, actual) { if (Array.isArray(expect)) { return expect.indexOf(actual) === -1 } else { return expect !== actual } } /** * Runtime helper for checking keyCodes from config. * exposed as Vue.prototype._k * passing in eventKeyName as last argument separately for backwards compat */ function checkKeyCodes ( eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName ) { var mappedKeyCode = config.keyCodes[key] || builtInKeyCode; if (builtInKeyName && eventKeyName && !config.keyCodes[key]) { return isKeyNotMatch(builtInKeyName, eventKeyName) } else if (mappedKeyCode) { return isKeyNotMatch(mappedKeyCode, eventKeyCode) } else if (eventKeyName) { return hyphenate(eventKeyName) !== key } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; var loop = function ( key ) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } var camelizedKey = camelize(key); var hyphenatedKey = hyphenate(key); if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) { hash[key] = value[key]; if (isSync) { var on = data.on || (data.on = {}); on[("update:" + key)] = function ($event) { value[key] = $event; }; } } }; for (var key in value) loop( key ); } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor ) { var cached = this._staticTrees || (this._staticTrees = []); var tree = cached[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree. if (tree && !isInFor) { return tree } // otherwise, render a fresh tree. tree = cached[index] = this.$options.staticRenderFns[index].call( this._renderProxy, null, this // for render fns generated for functional component templates ); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners (data, value) { if (value) { if (!isPlainObject(value)) { warn( 'v-on without argument expects an Object value', this ); } else { var on = data.on = data.on ? extend({}, data.on) : {}; for (var key in value) { var existing = on[key]; var ours = value[key]; on[key] = existing ? [].concat(existing, ours) : ours; } } } return data } /* */ function resolveScopedSlots ( fns, // see flow/vnode res, // the following are added in 2.6 hasDynamicKeys, contentHashKey ) { res = res || { $stable: !hasDynamicKeys }; for (var i = 0; i < fns.length; i++) { var slot = fns[i]; if (Array.isArray(slot)) { resolveScopedSlots(slot, res, hasDynamicKeys); } else if (slot) { // marker for reverse proxying v-slot without scope on this.$slots if (slot.proxy) { slot.fn.proxy = true; } res[slot.key] = slot.fn; } } if (contentHashKey) { (res).$key = contentHashKey; } return res } /* */ function bindDynamicKeys (baseObj, values) { for (var i = 0; i < values.length; i += 2) { var key = values[i]; if (typeof key === 'string' && key) { baseObj[values[i]] = values[i + 1]; } else if (key !== '' && key !== null) { // null is a special value for explicitly removing a binding warn( ("Invalid value for dynamic directive argument (expected string or null): " + key), this ); } } return baseObj } // helper to dynamically append modifier runtime markers to event names. // ensure only append when value is already string, otherwise it will be cast // to string and cause the type check to miss. function prependModifier (value, symbol) { return typeof value === 'string' ? symbol + value : value } /* */ function installRenderHelpers (target) { target._o = markOnce; target._n = toNumber; target._s = toString; target._l = renderList; target._t = renderSlot; target._q = looseEqual; target._i = looseIndexOf; target._m = renderStatic; target._f = resolveFilter; target._k = checkKeyCodes; target._b = bindObjectProps; target._v = createTextVNode; target._e = createEmptyVNode; target._u = resolveScopedSlots; target._g = bindObjectListeners; target._d = bindDynamicKeys; target._p = prependModifier; } /* */ function FunctionalRenderContext ( data, props, children, parent, Ctor ) { var this$1 = this; var options = Ctor.options; // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var contextVm; if (hasOwn(parent, '_uid')) { contextVm = Object.create(parent); // $flow-disable-line contextVm._original = parent; } else { // the context vm passed in is a functional context as well. // in this case we want to make sure we are able to get a hold to the // real context instance. contextVm = parent; // $flow-disable-line parent = parent._original; } var isCompiled = isTrue(options._compiled); var needNormalization = !isCompiled; this.data = data; this.props = props; this.children = children; this.parent = parent; this.listeners = data.on || emptyObject; this.injections = resolveInject(options.inject, parent); this.slots = function () { if (!this$1.$slots) { normalizeScopedSlots( data.scopedSlots, this$1.$slots = resolveSlots(children, parent) ); } return this$1.$slots }; Object.defineProperty(this, 'scopedSlots', ({ enumerable: true, get: function get () { return normalizeScopedSlots(data.scopedSlots, this.slots()) } })); // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options; // pre-resolve slots for renderSlot() this.$slots = this.slots(); this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots); } if (options._scopeId) { this._c = function (a, b, c, d) { var vnode = createElement(contextVm, a, b, c, d, needNormalization); if (vnode && !Array.isArray(vnode)) { vnode.fnScopeId = options._scopeId; vnode.fnContext = parent; } return vnode }; } else { this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); }; } } installRenderHelpers(FunctionalRenderContext.prototype); function createFunctionalComponent ( Ctor, propsData, data, contextVm, children ) { var options = Ctor.options; var props = {}; var propOptions = options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || emptyObject); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } var renderContext = new FunctionalRenderContext( data, props, children, contextVm, Ctor ); var vnode = options.render.call(null, renderContext._c, renderContext); if (vnode instanceof VNode) { return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext) } else if (Array.isArray(vnode)) { var vnodes = normalizeChildren(vnode) || []; var res = new Array(vnodes.length); for (var i = 0; i < vnodes.length; i++) { res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext); } return res } } function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) { // #7817 clone node before setting fnContext, otherwise if the node is reused // (e.g. it was from a cached normal slot) the fnContext causes named slots // that should not be matched to match. var clone = cloneVNode(vnode); clone.fnContext = contextVm; clone.fnOptions = options; { (clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext; } if (data.slot) { (clone.data || (clone.data = {})).slot = data.slot; } return clone } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ /* */ /* */ /* */ // inline hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init (vnode, hydrating) { if ( vnode.componentInstance && !vnode.componentInstance._isDestroyed && vnode.data.keepAlive ) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } else { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component var asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow var slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // install component management hooks onto the placeholder node installComponentHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }, asyncFactory ); return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent // activeInstance in lifecycle state ) { var options = { _isComponent: true, _parentVnode: vnode, parent: parent }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnode.componentOptions.Ctor(options) } function installComponentHooks (data) { var hooks = data.hook || (data.hook = {}); for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var existing = hooks[key]; var toMerge = componentVNodeHooks[key]; if (existing !== toMerge && !(existing && existing._merged)) { hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge; } } } function mergeHook$1 (f1, f2) { var merged = function (a, b) { // flow complains about extra args which is why we use any f1(a, b); f2(a, b); }; merged._merged = true; return merged } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input' ;(data.attrs || (data.attrs = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); var existing = on[event]; var callback = data.model.callback; if (isDef(existing)) { if ( Array.isArray(existing) ? existing.indexOf(callback) === -1 : existing !== callback ) { on[event] = [callback].concat(existing); } } else { on[event] = callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements if (isDef(data) && isDef(data.nativeOn)) { warn( ("The .native modifier for v-on is only valid on components but it was used on <" + tag + ">."), context ); } vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (Array.isArray(vnode)) { return vnode } else if (isDef(vnode)) { if (isDef(ns)) { applyNS(vnode, ns); } if (isDef(data)) { registerDeepBindings(data); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns, force) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject ns = undefined; force = true; } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && ( isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) { applyNS(child, ns, force); } } } } // ref #5318 // necessary to ensure parent re-render when deep bindings like :style and // :class are used on slot nodes function registerDeepBindings (data) { if (isObject(data.style)) { traverse(data.style); } if (isObject(data.class)) { traverse(data.class); } } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; // v-once cached trees var options = vm.$options; var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated var parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ { defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } } var currentRenderingInstance = null; function renderMixin (Vue) { // install runtime convenience helpers installRenderHelpers(Vue.prototype); Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var _parentVnode = ref._parentVnode; if (_parentVnode) { vm.$scopedSlots = normalizeScopedSlots( _parentVnode.data.scopedSlots, vm.$slots, vm.$scopedSlots ); } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { // There's no need to maintain a stack because all render fns are called // separately from one another. Nested component's render fns are called // when parent component is patched. currentRenderingInstance = vm; vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e); } catch (e) { handleError(e, vm, "renderError"); vnode = vm._vnode; } } else { vnode = vm._vnode; } } finally { currentRenderingInstance = null; } // if the returned array contains only a single node, allow it if (Array.isArray(vnode) && vnode.length === 1) { vnode = vnode[0]; } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; } /* */ function ensureCtor (comp, base) { if ( comp.__esModule || (hasSymbol && comp[Symbol.toStringTag] === 'Module') ) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp } function createAsyncPlaceholder ( factory, data, context, children, tag ) { var node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data: data, context: context, children: children, tag: tag }; return node } function resolveAsyncComponent ( factory, baseCtor ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } var owner = currentRenderingInstance; if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) { // already pending factory.owners.push(owner); } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (owner && !isDef(factory.owners)) { var owners = factory.owners = [owner]; var sync = true; var timerLoading = null; var timerTimeout = null ;(owner).$on('hook:destroyed', function () { return remove(owners, owner); }); var forceRender = function (renderCompleted) { for (var i = 0, l = owners.length; i < l; i++) { (owners[i]).$forceUpdate(); } if (renderCompleted) { owners.length = 0; if (timerLoading !== null) { clearTimeout(timerLoading); timerLoading = null; } if (timerTimeout !== null) { clearTimeout(timerTimeout); timerTimeout = null; } } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(true); } else { owners.length = 0; } }); var reject = once(function (reason) { warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(true); } }); var res = factory(resolve, reject); if (isObject(res)) { if (isPromise(res)) { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isPromise(res.component)) { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { timerLoading = setTimeout(function () { timerLoading = null; if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(false); } }, res.delay || 200); } } if (isDef(res.timeout)) { timerTimeout = setTimeout(function () { timerTimeout = null; if (isUndef(factory.resolved)) { reject( "timeout (" + (res.timeout) + "ms)" ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function isAsyncPlaceholder (node) { return node.isComment && node.asyncFactory } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn) { target.$on(event, fn); } function remove$1 (event, fn) { target.$off(event, fn); } function createOnceHandler (event, fn) { var _target = target; return function onceHandler () { var res = fn.apply(null, arguments); if (res !== null) { _target.$off(event, onceHandler); } } } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm); target = undefined; } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { vm.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i$1 = 0, l = event.length; i$1 < l; i$1++) { vm.$off(event[i$1], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (!fn) { vm._events[event] = null; return vm } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); var info = "event handler for \"" + event + "\""; for (var i = 0, l = cbs.length; i < l; i++) { invokeWithErrorHandling(cbs[i], vm, args, vm, info); } } return vm }; } /* */ var activeInstance = null; var isUpdatingChildComponent = false; function setActiveInstance(vm) { var prevActiveInstance = activeInstance; activeInstance = vm; return function () { activeInstance = prevActiveInstance; } } function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; var prevEl = vm.$el; var prevVnode = vm._vnode; var restoreActiveInstance = setActiveInstance(vm); vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */); } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } restoreActiveInstance(); // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null; } }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure(("vue " + name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure(("vue " + name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, { before: function before () { if (vm._isMounted && !vm._isDestroyed) { callHook(vm, 'beforeUpdate'); } } }, true /* isRenderWatcher */); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren. // check if there are dynamic scopedSlots (hand-written or compiled but with // dynamic slot names). Static scoped slots compiled from template has the // "$stable" marker. var newScopedSlots = parentVnode.data.scopedSlots; var oldScopedSlots = vm.$scopedSlots; var hasDynamicScopedSlot = !!( (newScopedSlots && !newScopedSlots.$stable) || (oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) || (newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key) ); // Any static slot children from the parent may have changed during parent's // update. Dynamic scoped slots may also have changed. In such cases, a forced // update is necessary to ensure correctness. var needsForceUpdate = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots hasDynamicScopedSlot ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listeners hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = parentVnode.data.attrs || emptyObject; vm.$listeners = listeners || emptyObject; // update props if (propsData && vm.$options.props) { toggleObserving(false); var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; var propOptions = vm.$options.props; // wtf flow? props[key] = validateProp(key, propOptions, propsData, vm); } toggleObserving(true); // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners listeners = listeners || emptyObject; var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); // resolve slots + force update if has children if (needsForceUpdate) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } { isUpdatingChildComponent = false; } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { // #7573 disable dep collection when invoking lifecycle hooks pushTarget(); var handlers = vm.$options[hook]; var info = hook + " hook"; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { invokeWithErrorHandling(handlers[i], vm, null, vm, info); } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } popTarget(); } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; { circular = {}; } waiting = flushing = false; } // Async edge case #6566 requires saving the timestamp when event listeners are // attached. However, calling performance.now() has a perf overhead especially // if the page has thousands of event listeners. Instead, we take a timestamp // every time the scheduler flushes and use that for all event listeners // attached during that flush. var currentFlushTimestamp = 0; // Async edge case fix requires storing an event listener's attach timestamp. var getNow = Date.now; // Determine what event timestamp the browser is using. Annoyingly, the // timestamp can either be hi-res (relative to page load) or low-res // (relative to UNIX epoch), so in order to compare time we have to use the // same timestamp type when saving the flush timestamp. // All IE versions use low-res event timestamps, and have problematic clock // implementations (#9632) if (inBrowser && !isIE) { var performance = window.performance; if ( performance && typeof performance.now === 'function' && getNow() > document.createEvent('Event').timeStamp ) { // if the event timestamp, although evaluated AFTER the Date.now(), is // smaller than it, it means the event is using a hi-res timestamp, // and we need to use the hi-res version for event listener timestamps as // well. getNow = function () { return performance.now(); }; } } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { currentFlushTimestamp = getNow(); flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; if (watcher.before) { watcher.before(); } id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; if (!config.async) { flushSchedulerQueue(); return } nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options, isRenderWatcher ) { this.vm = vm; if (isRenderWatcher) { vm._watcher = this; } vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; this.before = options.before; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = expOrFn.toString(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = noop; warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds.has(dep.id)) { dep.removeSub(this); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; } }; /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted if (!isRoot) { toggleObserving(false); } var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ { var hyphenatedKey = hyphenate(key); if (isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) { warn( ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(props, key, value, function () { if (!isRoot && !isUpdatingChildComponent) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); toggleObserving(true); } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var methods = vm.$options.methods; var i = keys.length; while (i--) { var key = keys[i]; { if (methods && hasOwn(methods, key)) { warn( ("Method \"" + key + "\" has already been defined as a data property."), vm ); } } if (props && hasOwn(props, key)) { warn( "The data property \"" + key + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(key)) { proxy(vm, "_data", key); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { // #7573 disable dep collection when invoking data getters pushTarget(); try { return data.call(vm, vm) } catch (e) { handleError(e, vm, "data()"); return {} } finally { popTarget(); } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { // $flow-disable-line var watchers = vm._computedWatchers = Object.create(null); // computed properties are just getters during SSR var isSSR = isServerRendering(); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (getter == null) { warn( ("Getter is missing for computed property \"" + key + "\"."), vm ); } if (!isSSR) { // create internal watcher for the computed property. watchers[key] = new Watcher( vm, getter || noop, noop, computedWatcherOptions ); } // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed ( target, key, userDef ) { var shouldCache = !isServerRendering(); if (typeof userDef === 'function') { sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : createGetterInvoker(userDef); sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : createGetterInvoker(userDef.get) : noop; sharedPropertyDefinition.set = userDef.set || noop; } if (sharedPropertyDefinition.set === noop) { sharedPropertyDefinition.set = function () { warn( ("Computed property \"" + key + "\" was assigned to but it has no setter."), this ); }; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function createGetterInvoker(fn) { return function computedGetter () { return fn.call(this, this) } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { { if (typeof methods[key] !== 'function') { warn( "Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("Method \"" + key + "\" has already been defined as a prop."), vm ); } if ((key in vm) && isReserved(key)) { warn( "Method \"" + key + "\" conflicts with an existing Vue instance method. " + "Avoid defining component methods that start with _ or $." ); } } vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm); } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher ( vm, expOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(expOrFn, handler, options) } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; { dataDef.set = function () { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { try { cb.call(vm, watcher.value); } catch (error) { handleError(error, vm, ("callback for immediate watcher \"" + (watcher.expression) + "\"")); } } return function unwatchFn () { watcher.teardown(); } }; } /* */ var uid$3 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$3++; var startTag, endTag; /* istanbul ignore if */ if (config.performance && mark) { startTag = "vue-perf-start:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ { initProxy(vm); } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(("vue " + (vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. var parentVnode = options._parentVnode; opts.parent = options.parent; opts._parentVnode = parentVnode; var vnodeComponentOptions = parentVnode.componentOptions; opts.propsData = vnodeComponentOptions.propsData; opts._parentListeners = vnodeComponentOptions.listeners; opts._renderChildren = vnodeComponentOptions.children; opts._componentTag = vnodeComponentOptions.tag; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = latest[key]; } } return modified } function Vue (options) { if (!(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); renderMixin(Vue); /* */ function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (name) { validateComponentName(name); } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (type === 'component') { validateComponentName(id); } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (keepAliveInstance, filter) { var cache = keepAliveInstance.cache; var keys = keepAliveInstance.keys; var _vnode = keepAliveInstance._vnode; for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode); } } } } function pruneCacheEntry ( cache, key, keys, current ) { var cached$$1 = cache[key]; if (cached$$1 && (!current || cached$$1.tag !== current.tag)) { cached$$1.componentInstance.$destroy(); } cache[key] = null; remove(keys, key); } var patternTypes = [String, RegExp, Array]; var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created: function created () { this.cache = Object.create(null); this.keys = []; }, destroyed: function destroyed () { for (var key in this.cache) { pruneCacheEntry(this.cache, key, this.keys); } }, mounted: function mounted () { var this$1 = this; this.$watch('include', function (val) { pruneCache(this$1, function (name) { return matches(val, name); }); }); this.$watch('exclude', function (val) { pruneCache(this$1, function (name) { return !matches(val, name); }); }); }, render: function render () { var slot = this.$slots.default; var vnode = getFirstComponentChild(slot); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); var ref = this; var include = ref.include; var exclude = ref.exclude; if ( // not included (include && (!name || !matches(include, name))) || // excluded (exclude && name && matches(exclude, name)) ) { return vnode } var ref$1 = this; var cache = ref$1.cache; var keys = ref$1.keys; var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } else { cache[key] = vnode; keys.push(key); // prune oldest entry if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } vnode.data.keepAlive = true; } return vnode || (slot && slot[0]) } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive$$1 }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; // 2.6 explicit observable API Vue.observable = function (obj) { observe(obj); return obj }; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue); Object.defineProperty(Vue.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }); // expose FunctionalRenderContext for ssr runtime helper installation Object.defineProperty(Vue, 'FunctionalRenderContext', { value: FunctionalRenderContext }); Vue.version = '2.6.12'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select,progress'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only'); var convertEnumeratedValue = function (key, value) { return isFalsyAttrValue(value) || value === 'false' ? 'false' // allow arbitrary string value for contenteditable : key === 'contenteditable' && isValidContentEditableValue(value) ? value : 'true' }; var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode && childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode && parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function renderClass ( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (Array.isArray(value)) { return stringifyArray(value) } if (isObject(value)) { return stringifyObject(value) } if (typeof value === 'string') { return value } /* istanbul ignore next */ return '' } function stringifyArray (value) { var res = ''; var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res } function stringifyObject (value) { var res = ''; for (var key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } var isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setStyleScope (node, scopeId) { node.setAttribute(scopeId, ''); } var nodeOps = /*#__PURE__*/Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setStyleScope: setStyleScope }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!isDef(key)) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ref]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) } function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove$$1 () { if (--remove$$1.listeners === 0) { removeNode(childElm); } } remove$$1.listeners = listeners; return remove$$1 } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } function isUnknownElement$$1 (vnode, inVPre) { return ( !inVPre && !vnode.ns && !( config.ignoredElements.length && config.ignoredElements.some(function (ignore) { return isRegExp(ignore) ? ignore.test(vnode.tag) : ignore === vnode.tag }) ) && config.isUnknownElement(vnode.tag) ) } var creatingElmInVPre = 0; function createElm ( vnode, insertedVnodeQueue, parentElm, refElm, nested, ownerArray, index ) { if (isDef(vnode.elm) && isDef(ownerArray)) { // This vnode was used in a previous render! // now it's used as a new node, overwriting its elm would cause // potential patch errors down the road when it's used as an insertion // reference node. Instead, we clone the node on-demand before creating // associated DOM element for it. vnode = ownerArray[index] = cloneVNode(vnode); } vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { { if (data && data.pre) { creatingElmInVPre++; } if (isUnknownElement$$1(vnode, creatingElmInVPre)) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (data && data.pre) { creatingElmInVPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); insert(parentElm, vnode.elm, refElm); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (nodeOps.parentNode(ref$$1) === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { { checkDuplicateKeys(children); } for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text))); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.fnScopeId)) { nodeOps.setStyleScope(vnode.elm, i); } else { var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setStyleScope(vnode.elm, i); } ancestor = ancestor.parent; } } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId) ) { nodeOps.setStyleScope(vnode.elm, i); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, vnodeToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; { checkDuplicateKeys(newCh); } while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx); if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } else { vnodeToMove = oldCh[idxInOld]; if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm); } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } } newStartVnode = newCh[++newStartIdx]; } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(oldCh, oldStartIdx, oldEndIdx); } } function checkDuplicateKeys (children) { var seenKeys = {}; for (var i = 0; i < children.length; i++) { var vnode = children[i]; var key = vnode.key; if (isDef(key)) { if (seenKeys[key]) { warn( ("Duplicate keys detected: '" + key + "'. This may cause an update error."), vnode.context ); } else { seenKeys[key] = true; } } } } function findIdxInOld (node, oldCh, start, end) { for (var i = start; i < end; i++) { var c = oldCh[i]; if (isDef(c) && sameVnode(node, c)) { return i } } } function patchVnode ( oldVnode, vnode, insertedVnodeQueue, ownerArray, index, removeOnly ) { if (oldVnode === vnode) { return } if (isDef(vnode.elm) && isDef(ownerArray)) { // clone reused vnode vnode = ownerArray[index] = cloneVNode(vnode); } var elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { { checkDuplicateKeys(ch); } if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var hydrationBailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization // Note: style is excluded because it relies on initial clone for future // deep updates (#7063). var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue, inVPre) { var i; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; inVPre = inVPre || (data && data.pre); vnode.elm = elm; if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.isAsyncPlaceholder = true; return true } // assert node match { if (!assertNodeMatch(elm, vnode, inVPre)) { return false } } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { // v-html and domProps: innerHTML if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) { if (i !== elm.innerHTML) { /* istanbul ignore if */ if (typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('server innerHTML: ', i); console.warn('client innerHTML: ', elm.innerHTML); } return false } } else { // iterate and compare children lists var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { /* istanbul ignore if */ if (typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } } if (isDef(data)) { var fullInvoke = false; for (var key in data) { if (!isRenderedModule(key)) { fullInvoke = true; invokeCreateHooks(vnode, insertedVnodeQueue); break } } if (!fullInvoke && data['class']) { // ensure collecting deps for deep class bindings for future updates traverse(data['class']); } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode, inVPre) { if (isDef(vnode.tag)) { return vnode.tag.indexOf('vue-component') === 0 || ( !isUnknownElement$$1(vnode, inVPre) && vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm = nodeOps.parentNode(oldElm); // create new node createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm, nodeOps.nextSibling(oldElm) ); // update parent placeholder node element, recursively if (isDef(vnode.parent)) { var ancestor = vnode.parent; var patchable = isPatchable(vnode); while (ancestor) { for (var i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor); } ancestor.elm = vnode.elm; if (patchable) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, ancestor); } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. var insert = ancestor.data.hook.insert; if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (var i$2 = 1; i$2 < insert.fns.length; i$2++) { insert.fns[i$2](); } } } else { registerRef(ancestor); } ancestor = ancestor.parent; } } // destroy old node if (isDef(parentElm)) { removeVnodes([oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; dir.oldArg = oldDir.arg; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode, 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode, 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { // $flow-disable-line return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { // $flow-disable-line dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } // $flow-disable-line return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { var opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] // #6666: IE/Edge forces progress value down to 1 before setting a max /* istanbul ignore if */ if ((isIE || isEdge) && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (el.tagName.indexOf('-') > -1) { baseSetAttr(el, key, value); } else if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // technically allowfullscreen is a boolean attribute for <iframe>, // but Flash expects a value of "true" when used on <embed> tag value = key === 'allowfullscreen' && el.tagName === 'EMBED' ? 'true' : key; el.setAttribute(key, value); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, convertEnumeratedValue(key, value)); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { baseSetAttr(el, key, value); } } function baseSetAttr (el, key, value) { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // #7138: IE10 & 11 fires input event when setting placeholder on // <textarea>... block the first input event and remove the blocker // immediately. /* istanbul ignore if */ if ( isIE && !isIE9 && el.tagName === 'TEXTAREA' && key === 'placeholder' && value !== '' && !el.__ieph ) { var blocker = function (e) { e.stopImmediatePropagation(); el.removeEventListener('input', blocker); }; el.addEventListener('input', blocker); // $flow-disable-line el.__ieph = true; /* IE placeholder patched */ } el.setAttribute(key, value); } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + (args !== ')' ? ',' + args : args)) } } /* */ /* eslint-disable no-unused-vars */ function baseWarn (msg, range) { console.error(("[Vue compiler]: " + msg)); } /* eslint-enable no-unused-vars */ function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value, range, dynamic) { (el.props || (el.props = [])).push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range)); el.plain = false; } function addAttr (el, name, value, range, dynamic) { var attrs = dynamic ? (el.dynamicAttrs || (el.dynamicAttrs = [])) : (el.attrs || (el.attrs = [])); attrs.push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range)); el.plain = false; } // add a raw attr (use this in preTransforms) function addRawAttr (el, name, value, range) { el.attrsMap[name] = value; el.attrsList.push(rangeSetItem({ name: name, value: value }, range)); } function addDirective ( el, name, rawName, value, arg, isDynamicArg, modifiers, range ) { (el.directives || (el.directives = [])).push(rangeSetItem({ name: name, rawName: rawName, value: value, arg: arg, isDynamicArg: isDynamicArg, modifiers: modifiers }, range)); el.plain = false; } function prependModifierMarker (symbol, name, dynamic) { return dynamic ? ("_p(" + name + ",\"" + symbol + "\")") : symbol + name // mark the event as captured } function addHandler ( el, name, value, modifiers, important, warn, range, dynamic ) { modifiers = modifiers || emptyObject; // warn prevent and passive modifier /* istanbul ignore if */ if ( warn && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.', range ); } // normalize click.right and click.middle since they don't actually fire // this is technically browser-specific, but at least for now browsers are // the only target envs that have right/middle clicks. if (modifiers.right) { if (dynamic) { name = "(" + name + ")==='click'?'contextmenu':(" + name + ")"; } else if (name === 'click') { name = 'contextmenu'; delete modifiers.right; } } else if (modifiers.middle) { if (dynamic) { name = "(" + name + ")==='click'?'mouseup':(" + name + ")"; } else if (name === 'click') { name = 'mouseup'; } } // check capture modifier if (modifiers.capture) { delete modifiers.capture; name = prependModifierMarker('!', name, dynamic); } if (modifiers.once) { delete modifiers.once; name = prependModifierMarker('~', name, dynamic); } /* istanbul ignore if */ if (modifiers.passive) { delete modifiers.passive; name = prependModifierMarker('&', name, dynamic); } var events; if (modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = rangeSetItem({ value: value.trim(), dynamic: dynamic }, range); if (modifiers !== emptyObject) { newHandler.modifiers = modifiers; } var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } el.plain = false; } function getRawBindingAttr ( el, name ) { return el.rawAttrsMap[':' + name] || el.rawAttrsMap['v-bind:' + name] || el.rawAttrsMap[name] } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } // note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. function getAndRemoveAttr ( el, name, removeFromMap ) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } if (removeFromMap) { delete el.attrsMap[name]; } return val } function getAndRemoveAttrByRegex ( el, name ) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { var attr = list[i]; if (name.test(attr.name)) { list.splice(i, 1); return attr } } } function rangeSetItem ( item, range ) { if (range) { if (range.start != null) { item.start = range.start; } if (range.end != null) { item.end = range.end; } } return item } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: JSON.stringify(value), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var res = parseModel(value); if (res.key === null) { return (value + "=" + assignment) } else { return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")") } } /** * Parse a v-model expression into a base path and a final key segment. * Handles both dot-path and possible square brackets. * * Possible cases: * * - test * - test[key] * - test[test1[key]] * - test["a"][key] * - xxx.test[a[a].test1[key]] * - test.xxx.a["asa"][test1[key]] * */ var len, str, chr, index$1, expressionPos, expressionEndPos; function parseModel (val) { // Fix https://github.com/vuejs/vue/pull/7730 // allow v-model="obj.val " (trailing whitespace) val = val.trim(); len = val.length; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { index$1 = val.lastIndexOf('.'); if (index$1 > -1) { return { exp: val.slice(0, index$1), key: '"' + val.slice(index$1 + 1) + '"' } } else { return { exp: val, key: null } } } str = val; index$1 = expressionPos = expressionEndPos = 0; while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.slice(0, expressionPos), key: val.slice(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; { // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead.", el.rawAttrsMap['v-model'] ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.', el.rawAttrsMap['v-model'] ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$el.checked){$$i<0&&(" + (genAssignmentCode(value, '$$a.concat([$$v])')) + ")}" + "else{$$i>-1&&(" + (genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))')) + ")}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; // warn if v-bind:value conflicts with v-model // except for inputs with v-bind:type { var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value']; var typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (value$1 && !typeBinding) { var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'; warn$1( binding + "=\"" + value$1 + "\" conflicts with v-model on the same element " + 'because the latter already expands to a value binding internally', el.rawAttrsMap[binding] ); } } var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event var event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } // This was originally intended to fix #4521 but no longer necessary // after 2.5. Keeping it for backwards compat with generated code from < 2.4 /* istanbul ignore if */ if (isDef(on[CHECKBOX_RADIO_TOKEN])) { on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function createOnceHandler$1 (event, handler, capture) { var _target = target$1; // save current target element in closure return function onceHandler () { var res = handler.apply(null, arguments); if (res !== null) { remove$2(event, onceHandler, capture, _target); } } } // #9446: Firefox <= 53 (in particular, ESR 52) has incorrect Event.timeStamp // implementation and does not fire microtasks in between event propagation, so // safe to exclude. var useMicrotaskFix = isUsingMicroTask && !(isFF && Number(isFF[1]) <= 53); function add$1 ( name, handler, capture, passive ) { // async edge case #6566: inner click event triggers patch, event handler // attached to outer element during patch, and triggered again. This // happens because browsers fire microtask ticks between event propagation. // the solution is simple: we save the timestamp when a handler is attached, // and the handler would only fire if the event passed to it was fired // AFTER it was attached. if (useMicrotaskFix) { var attachedTimestamp = currentFlushTimestamp; var original = handler; handler = original._wrapper = function (e) { if ( // no bubbling, should always fire. // this is just a safety net in case event.timeStamp is unreliable in // certain weird environments... e.target === e.currentTarget || // event is fired after handler attachment e.timeStamp >= attachedTimestamp || // bail for environments that have buggy event.timeStamp implementations // #9462 iOS 9 bug: event.timeStamp is 0 after history.pushState // #9681 QtWebEngine event.timeStamp is negative value e.timeStamp <= 0 || // #9448 bail if event is fired in another document in a multi-page // electron/nw.js app, since event.timeStamp will be using a different // starting reference e.target.ownerDocument !== document ) { return original.apply(this, arguments) } }; } target$1.addEventListener( name, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( name, handler, capture, _target ) { (_target || target$1).removeEventListener( name, handler._wrapper || handler, capture ); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, createOnceHandler$1, vnode.context); target$1 = undefined; } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ var svgContainer; function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (!(key in props)) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } // #6601 work around Chrome version <= 55 bug where single textNode // replaced by innerHTML/textContent retains its parentNode property if (elm.childNodes.length === 1) { elm.removeChild(elm.childNodes[0]); } } if (key === 'value' && elm.tagName !== 'PROGRESS') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, strCur)) { elm.value = strCur; } } else if (key === 'innerHTML' && isSVG(elm.tagName) && isUndef(elm.innerHTML)) { // IE doesn't support innerHTML for SVG elements svgContainer = svgContainer || document.createElement('div'); svgContainer.innerHTML = "<svg>" + cur + "</svg>"; var svg = svgContainer.firstChild; while (elm.firstChild) { elm.removeChild(elm.firstChild); } while (svg.firstChild) { elm.appendChild(svg.firstChild); } } else if ( // skip the update if old and new VDOM state is the same. // `value` is handled separately because the DOM value may be temporarily // out of sync with VDOM state due to focus, composition and modifiers. // This #4521 by skipping the unnecessary `checked` update. cur !== oldProps[key] ) { // some property updates can throw // e.g. `value` on <progress> w/ non-finite value try { elm[key] = cur; } catch (e) {} } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue (elm, checkVal) { return (!elm.composing && ( elm.tagName === 'OPTION' || isNotInFocusAndDirty(elm, checkVal) || isDirtyWithModifiers(elm, checkVal) )) } function isNotInFocusAndDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value var notInFocus = true; // #6157 // work around IE bug when accessing document.activeElement in an iframe try { notInFocus = document.activeElement !== elm; } catch (e) {} return notInFocus && elm.value !== checkVal } function isDirtyWithModifiers (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers)) { if (modifiers.number) { return toNumber(value) !== toNumber(newVal) } if (modifiers.trim) { return value.trim() !== newVal.trim() } } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if ( childNode && childNode.data && (styleData = normalizeStyleData(childNode.data)) ) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(hyphenate(name), val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var vendorNames = ['Webkit', 'Moz', 'ms']; var emptyStyle; var normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop } var capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < vendorNames.length; i++) { var name = vendorNames[i] + capName; if (name in emptyStyle) { return name } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likely wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ var whitespaceRE = /\s+/; /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition (def$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function (fn) { return fn(); }; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { var transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); // JSDOM may return undefined for transition properties var transitionDelays = (styles[transitionProp + 'Delay'] || '').split(', '); var transitionDurations = (styles[transitionProp + 'Duration'] || '').split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = (styles[animationProp + 'Delay'] || '').split(', '); var animationDurations = (styles[animationProp + 'Duration'] || '').split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } // Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers // in a locale-dependent way, using a comma instead of a dot. // If comma is not replaced with a dot, the input will be rounded down (i.e. acting // as a floor function) causing unexpected behaviors function toMs (s) { return Number(s.slice(0, -1).replace(',', '.')) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { context = transitionNode.context; transitionNode = transitionNode.parent; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode, 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { removeTransitionClass(el, startClass); if (!cb.cancelled) { addTransitionClass(el, toClass); if (!userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data) || el.nodeType !== 1) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb)) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show && el.parentNode) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { removeTransitionClass(el, leaveClass); if (!cb.cancelled) { addTransitionClass(el, leaveToClass); if (!userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var directive = { inserted: function inserted (el, binding, vnode, oldVnode) { if (vnode.tag === 'select') { // #6903 if (oldVnode.elm && !oldVnode.elm._vOptions) { mergeVNodeHook(vnode, 'postpatch', function () { directive.componentUpdated(el, binding, vnode); }); } else { setSelected(el, binding, vnode.context); } el._vOptions = [].map.call(el.options, getValue); } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var prevOptions = el._vOptions; var curOptions = el._vOptions = [].map.call(el.options, getValue); if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) { // trigger change event if // no matching option found for at least one value var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions); if (needReset) { trigger(el, 'change'); } } } } }; function setSelected (el, binding, vm) { actuallySetSelected(el, binding, vm); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(function () { actuallySetSelected(el, binding, vm); }, 0); } } function actuallySetSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { return options.every(function (o) { return !looseEqual(o, value); }) } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (!value === !oldValue) { return } vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; if (transition$$1) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: directive, show: show }; /* */ var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var isNotTextNode = function (c) { return c.tag || isAsyncPlaceholder(c); }; var isVShowDirective = function (d) { return d.name === 'show'; }; var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(isNotTextNode); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(isVShowDirective)) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) && // #6687 component root is a comment node !(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment) ) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild } var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } }; /* */ var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, beforeMount: function beforeMount () { var this$1 = this; var update = this._update; this._update = function (vnode, hydrating) { var restoreActiveInstance = setActiveInstance(this$1); // force removing pass this$1.__patch__( this$1._vnode, this$1.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this$1._vnode = this$1.kept; restoreActiveInstance(); update.call(this$1, vnode, hydrating); }; }, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position // assign to this to avoid being removed in tree-shaking // $flow-disable-line this._reflow = document.body.offsetHeight; children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (e && e.target !== el) { return } if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue.config.mustUseProp = mustUseProp; Vue.config.isReservedTag = isReservedTag; Vue.config.isReservedAttr = isReservedAttr; Vue.config.getTagNamespace = getTagNamespace; Vue.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue.options.directives, platformDirectives); extend(Vue.options.components, platformComponents); // install platform patch function Vue.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ if (inBrowser) { setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } else { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (config.productionTip !== false && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); } /* */ var defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var rawTokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, tokenValue; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { rawTokens.push(tokenValue = text.slice(lastIndex, index)); tokens.push(JSON.stringify(tokenValue)); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); rawTokens.push({ '@binding': exp }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { rawTokens.push(tokenValue = text.slice(lastIndex)); tokens.push(JSON.stringify(tokenValue)); } return { expression: tokens.join('+'), tokens: rawTokens } } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (staticClass) { var res = parseText(staticClass, options.delimiters); if (res) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.', el.rawAttrsMap['class'] ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ { var res = parseText(staticStyle, options.delimiters); if (res) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.', el.rawAttrsMap['style'] ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$1 }; /* */ var decoder; var he = { decode: function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } }; /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; var dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; var ncname = "[a-zA-Z_][\\-\\.0-9_a-zA-Z" + (unicodeRegExp.source) + "]*"; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; // #7298: escape - to avoid being passed as HTML comment when inlined in page var comment = /^<!\--/; var conditionalComment = /^<!\[/; // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n', '&#9;': '\t', '&#39;': "'" }; var encodedAttr = /&(?:lt|gt|quot|amp|#39);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); } if (textEnd < 0) { text = html; } if (text) { advance(text.length); } if (options.chars && text) { options.chars(text, index - text.length, index); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298 .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (!stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\""), { start: index + html.length }); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) { attr.start = index; advance(attr[0].length); attr.end = index; match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; var value = args[3] || args[4] || args[5] || ''; var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines; attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) }; if (options.outputSourceRange) { attrs[i].start = args.start + args[0].match(/^\s*/).length; attrs[i].end = args.end; } } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } // Find the closest opened tag of the same type if (tagName) { lowerCasedTagName = tagName.toLowerCase(); for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (i > pos || !tagName && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag."), { start: stack[i].start, end: stack[i].end } ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:|^#/; var forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; var stripParensRE = /^\(|\)$/g; var dynamicArgRE = /^\[.*\]$/; var argRE = /:(.*)$/; var bindRE = /^:|^\.|^v-bind:/; var modifierRE = /\.[^.\]]+(?=[^\]]*$)/g; var slotRE = /^v-slot(:|$)|^#/; var lineBreakRE = /[\r\n]/; var whitespaceRE$1 = /\s+/g; var invalidAttributeRE = /[\s"'<>\/=]/; var decodeHTMLCached = cached(he.decode); var emptySlotScopeToken = "_empty_"; // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; var maybeComponent; function createASTElement ( tag, attrs, parent ) { return { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), rawAttrsMap: {}, parent: parent, children: [] } } /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; var isReservedTag = options.isReservedTag || no; maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); }; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var whitespaceOption = options.whitespace; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg, range) { if (!warned) { warned = true; warn$2(msg, range); } } function closeElement (element) { trimEndingWhitespace(element); if (!inVPre && !element.processed) { element = processElement(element, options); } // tree management if (!stack.length && element !== root) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { { checkRootConstraints(element); } addIfCondition(root, { exp: element.elseif, block: element }); } else { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead.", { start: element.start } ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else { if (element.slotScope) { // scoped slot // keep it in the children list so that v-else(-if) conditions can // find it as the prev node. var name = element.slotTarget || '"default"' ;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } currentParent.children.push(element); element.parent = currentParent; } } // final children cleanup // filter out scoped slots element.children = element.children.filter(function (c) { return !(c).slotScope; }); // remove trailing whitespace node again trimEndingWhitespace(element); // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } // apply post-transforms for (var i = 0; i < postTransforms.length; i++) { postTransforms[i](element, options); } } function trimEndingWhitespace (el) { // remove trailing whitespace node if (!inPre) { var lastNode; while ( (lastNode = el.children[el.children.length - 1]) && lastNode.type === 3 && lastNode.text === ' ' ) { el.children.pop(); } } } function checkRootConstraints (el) { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.', { start: el.start } ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.', el.rawAttrsMap['v-for'] ); } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref, shouldKeepComment: options.comments, outputSourceRange: options.outputSourceRange, start: function start (tag, attrs, unary, start$1, end) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = createASTElement(tag, attrs, currentParent); if (ns) { element.ns = ns; } { if (options.outputSourceRange) { element.start = start$1; element.end = end; element.rawAttrsMap = element.attrsList.reduce(function (cumulated, attr) { cumulated[attr.name] = attr; return cumulated }, {}); } attrs.forEach(function (attr) { if (invalidAttributeRE.test(attr.name)) { warn$2( "Invalid dynamic argument expression: attribute names cannot contain " + "spaces, quotes, <, >, / or =.", { start: attr.start + attr.name.indexOf("["), end: attr.start + attr.name.length } ); } }); } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.', { start: element.start } ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { element = preTransforms[i](element, options) || element; } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else if (!element.processed) { // structural directives processFor(element); processIf(element); processOnce(element); } if (!root) { root = element; { checkRootConstraints(root); } } if (!unary) { currentParent = element; stack.push(element); } else { closeElement(element); } }, end: function end (tag, start, end$1) { var element = stack[stack.length - 1]; // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; if (options.outputSourceRange) { element.end = end$1; } closeElement(element); }, chars: function chars (text, start, end) { if (!currentParent) { { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.', { start: start } ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored."), { start: start } ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; if (inPre || text.trim()) { text = isTextTag(currentParent) ? text : decodeHTMLCached(text); } else if (!children.length) { // remove the whitespace-only node right after an opening tag text = ''; } else if (whitespaceOption) { if (whitespaceOption === 'condense') { // in condense mode, remove the whitespace node if it contains // line break, otherwise condense to a single space text = lineBreakRE.test(text) ? '' : ' '; } else { text = ' '; } } else { text = preserveWhitespace ? ' ' : ''; } if (text) { if (!inPre && whitespaceOption === 'condense') { // condense consecutive whitespaces into single space text = text.replace(whitespaceRE$1, ' '); } var res; var child; if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) { child = { type: 2, expression: res.expression, tokens: res.tokens, text: text }; } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { child = { type: 3, text: text }; } if (child) { if (options.outputSourceRange) { child.start = start; child.end = end; } children.push(child); } } }, comment: function comment (text, start, end) { // adding anything as a sibling to the root node is forbidden // comments should still be allowed, but ignored if (currentParent) { var child = { type: 3, text: text, isComment: true }; if (options.outputSourceRange) { child.start = start; child.end = end; } currentParent.children.push(child); } } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var list = el.attrsList; var len = list.length; if (len) { var attrs = el.attrs = new Array(len); for (var i = 0; i < len; i++) { attrs[i] = { name: list[i].name, value: JSON.stringify(list[i].value) }; if (list[i].start != null) { attrs[i].start = list[i].start; attrs[i].end = list[i].end; } } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processElement ( element, options ) { processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = ( !element.key && !element.scopedSlots && !element.attrsList.length ); processRef(element); processSlotContent(element); processSlotOutlet(element); processComponent(element); for (var i = 0; i < transforms.length; i++) { element = transforms[i](element, options) || element; } processAttrs(element); return element } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { { if (el.tag === 'template') { warn$2( "<template> cannot be keyed. Place the key on real elements instead.", getRawBindingAttr(el, 'key') ); } if (el.for) { var iterator = el.iterator2 || el.iterator1; var parent = el.parent; if (iterator && iterator === exp && parent && parent.tag === 'transition-group') { warn$2( "Do not use v-for index as key on <transition-group> children, " + "this is the same as not using keys.", getRawBindingAttr(el, 'key'), true /* tip */ ); } } } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var res = parseFor(exp); if (res) { extend(el, res); } else { warn$2( ("Invalid v-for expression: " + exp), el.rawAttrsMap['v-for'] ); } } } function parseFor (exp) { var inMatch = exp.match(forAliasRE); if (!inMatch) { return } var res = {}; res.for = inMatch[2].trim(); var alias = inMatch[1].trim().replace(stripParensRE, ''); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { res.alias = alias.replace(forIteratorRE, '').trim(); res.iterator1 = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.iterator2 = iteratorMatch[2].trim(); } } else { res.alias = alias; } return res } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if.", el.rawAttrsMap[el.elseif ? 'v-else-if' : 'v-else'] ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored.", children[i] ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } // handle content being passed to a component as slot, // e.g. <template slot="xxx">, <div slot-scope="xxx"> function processSlotContent (el) { var slotScope; if (el.tag === 'template') { slotScope = getAndRemoveAttr(el, 'scope'); /* istanbul ignore if */ if (slotScope) { warn$2( "the \"scope\" attribute for scoped slots have been deprecated and " + "replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " + "can also be used on plain elements in addition to <template> to " + "denote scoped slots.", el.rawAttrsMap['scope'], true ); } el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope'); } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) { /* istanbul ignore if */ if (el.attrsMap['v-for']) { warn$2( "Ambiguous combined usage of slot-scope and v-for on <" + (el.tag) + "> " + "(v-for takes higher priority). Use a wrapper <template> for the " + "scoped slot to make it clearer.", el.rawAttrsMap['slot-scope'], true ); } el.slotScope = slotScope; } // slot="xxx" var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; el.slotTargetDynamic = !!(el.attrsMap[':slot'] || el.attrsMap['v-bind:slot']); // preserve slot as an attribute for native shadow DOM compat // only for non-scoped slots. if (el.tag !== 'template' && !el.slotScope) { addAttr(el, 'slot', slotTarget, getRawBindingAttr(el, 'slot')); } } // 2.6 v-slot syntax { if (el.tag === 'template') { // v-slot on <template> var slotBinding = getAndRemoveAttrByRegex(el, slotRE); if (slotBinding) { { if (el.slotTarget || el.slotScope) { warn$2( "Unexpected mixed usage of different slot syntaxes.", el ); } if (el.parent && !maybeComponent(el.parent)) { warn$2( "<template v-slot> can only appear at the root level inside " + "the receiving component", el ); } } var ref = getSlotName(slotBinding); var name = ref.name; var dynamic = ref.dynamic; el.slotTarget = name; el.slotTargetDynamic = dynamic; el.slotScope = slotBinding.value || emptySlotScopeToken; // force it into a scoped slot for perf } } else { // v-slot on component, denotes default slot var slotBinding$1 = getAndRemoveAttrByRegex(el, slotRE); if (slotBinding$1) { { if (!maybeComponent(el)) { warn$2( "v-slot can only be used on components or <template>.", slotBinding$1 ); } if (el.slotScope || el.slotTarget) { warn$2( "Unexpected mixed usage of different slot syntaxes.", el ); } if (el.scopedSlots) { warn$2( "To avoid scope ambiguity, the default slot should also use " + "<template> syntax when there are other named slots.", slotBinding$1 ); } } // add the component's children to its default slot var slots = el.scopedSlots || (el.scopedSlots = {}); var ref$1 = getSlotName(slotBinding$1); var name$1 = ref$1.name; var dynamic$1 = ref$1.dynamic; var slotContainer = slots[name$1] = createASTElement('template', [], el); slotContainer.slotTarget = name$1; slotContainer.slotTargetDynamic = dynamic$1; slotContainer.children = el.children.filter(function (c) { if (!c.slotScope) { c.parent = slotContainer; return true } }); slotContainer.slotScope = slotBinding$1.value || emptySlotScopeToken; // remove children as they are returned from scopedSlots now el.children = []; // mark el non-plain so data gets generated el.plain = false; } } } } function getSlotName (binding) { var name = binding.name.replace(slotRE, ''); if (!name) { if (binding.name[0] !== '#') { name = 'default'; } else { warn$2( "v-slot shorthand syntax requires a slot name.", binding ); } } return dynamicArgRE.test(name) // dynamic [name] ? { name: name.slice(1, -1), dynamic: true } // static name : { name: ("\"" + name + "\""), dynamic: false } } // handle <slot/> outlets function processSlotOutlet (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead.", getRawBindingAttr(el, 'key') ); } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, syncGen, isDynamic; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name.replace(dirRE, '')); // support .foo shorthand syntax for the .prop modifier if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isDynamic = dynamicArgRE.test(name); if (isDynamic) { name = name.slice(1, -1); } if ( value.trim().length === 0 ) { warn$2( ("The value for a v-bind expression cannot be empty. Found in \"v-bind:" + name + "\"") ); } if (modifiers) { if (modifiers.prop && !isDynamic) { name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel && !isDynamic) { name = camelize(name); } if (modifiers.sync) { syncGen = genAssignmentCode(value, "$event"); if (!isDynamic) { addHandler( el, ("update:" + (camelize(name))), syncGen, null, false, warn$2, list[i] ); if (hyphenate(name) !== camelize(name)) { addHandler( el, ("update:" + (hyphenate(name))), syncGen, null, false, warn$2, list[i] ); } } else { // handler w/ dynamic event name addHandler( el, ("\"update:\"+(" + name + ")"), syncGen, null, false, warn$2, list[i], true // dynamic ); } } } if ((modifiers && modifiers.prop) || ( !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value, list[i], isDynamic); } else { addAttr(el, name, value, list[i], isDynamic); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); isDynamic = dynamicArgRE.test(name); if (isDynamic) { name = name.slice(1, -1); } addHandler(el, name, value, modifiers, false, warn$2, list[i], isDynamic); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; isDynamic = false; if (arg) { name = name.slice(0, -(arg.length + 1)); if (dynamicArgRE.test(arg)) { arg = arg.slice(1, -1); isDynamic = true; } } addDirective(el, name, rawName, value, arg, isDynamic, modifiers, list[i]); if (name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute { var res = parseText(value, delimiters); if (res) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.', list[i] ); } } addAttr(el, name, JSON.stringify(value), list[i]); // #6887 firefox doesn't update muted state if set via attribute // even immediately after element creation if (!el.component && name === 'muted' && platformMustUseProp(el.tag, el.attrsMap.type, name)) { addProp(el, name, 'true', list[i]); } } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name, attrs[i]); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead.", el.rawAttrsMap['v-model'] ); } _el = _el.parent; } } /* */ function preTransformNode (el, options) { if (el.tag === 'input') { var map = el.attrsMap; if (!map['v-model']) { return } var typeBinding; if (map[':type'] || map['v-bind:type']) { typeBinding = getBindingAttr(el, 'type'); } if (!map.type && !typeBinding && map['v-bind']) { typeBinding = "(" + (map['v-bind']) + ").type"; } if (typeBinding) { var ifCondition = getAndRemoveAttr(el, 'v-if', true); var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : ""; var hasElse = getAndRemoveAttr(el, 'v-else', true) != null; var elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true); // 1. checkbox var branch0 = cloneASTElement(el); // process for on the main node processFor(branch0); addRawAttr(branch0, 'type', 'checkbox'); processElement(branch0, options); branch0.processed = true; // prevent it from double-processed branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra; addIfCondition(branch0, { exp: branch0.if, block: branch0 }); // 2. add radio else-if condition var branch1 = cloneASTElement(el); getAndRemoveAttr(branch1, 'v-for', true); addRawAttr(branch1, 'type', 'radio'); processElement(branch1, options); addIfCondition(branch0, { exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra, block: branch1 }); // 3. other var branch2 = cloneASTElement(el); getAndRemoveAttr(branch2, 'v-for', true); addRawAttr(branch2, ':type', typeBinding); processElement(branch2, options); addIfCondition(branch0, { exp: ifCondition, block: branch2 }); if (hasElse) { branch0.else = true; } else if (elseIfCondition) { branch0.elseif = elseIfCondition; } return branch0 } } } function cloneASTElement (el) { return createASTElement(el.tag, el.attrsList.slice(), el.parent) } var model$1 = { preTransformNode: preTransformNode }; var modules$1 = [ klass$1, style$1, model$1 ]; /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")"), dir); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"), dir); } } var directives$1 = { model: model, text: text, html: html }; /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { var block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function(?:\s+[\w$]+)?\s*\(/; var fnInvokeRE = /\([^)]*?\);*$/; var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // KeyboardEvent.keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // KeyboardEvent.key aliases var keyNames = { // #7880: IE11 and Edge use `Esc` for Escape key name. esc: ['Esc', 'Escape'], tab: 'Tab', enter: 'Enter', // #9112: IE11 uses `Spacebar` for Space key name. space: [' ', 'Spacebar'], // #7806: IE11 uses key names without `Arrow` prefix for arrow keys. up: ['Up', 'ArrowUp'], left: ['Left', 'ArrowLeft'], right: ['Right', 'ArrowRight'], down: ['Down', 'ArrowDown'], // #9112: IE11 uses `Del` for Delete key name. 'delete': ['Backspace', 'Delete', 'Del'] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative ) { var prefix = isNative ? 'nativeOn:' : 'on:'; var staticHandlers = ""; var dynamicHandlers = ""; for (var name in events) { var handlerCode = genHandler(events[name]); if (events[name] && events[name].dynamic) { dynamicHandlers += name + "," + handlerCode + ","; } else { staticHandlers += "\"" + name + "\":" + handlerCode + ","; } } staticHandlers = "{" + (staticHandlers.slice(0, -1)) + "}"; if (dynamicHandlers) { return prefix + "_d(" + staticHandlers + ",[" + (dynamicHandlers.slice(0, -1)) + "])" } else { return prefix + staticHandlers } } function genHandler (handler) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); var isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, '')); if (!handler.modifiers) { if (isMethodPath || isFunctionExpression) { return handler.value } return ("function($event){" + (isFunctionInvocation ? ("return " + (handler.value)) : handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else if (key === 'exact') { var modifiers = (handler.modifiers); genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] .filter(function (keyModifier) { return !modifiers[keyModifier]; }) .map(function (keyModifier) { return ("$event." + keyModifier + "Key"); }) .join('||') ); } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? ("return " + (handler.value) + "($event)") : isFunctionExpression ? ("return (" + (handler.value) + ")($event)") : isFunctionInvocation ? ("return " + (handler.value)) : handler.value; return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ( // make sure the key filters only apply to KeyboardEvents // #9441: can't use 'keyCode' in $event because Chrome autofill fires fake // key events that do not have keyCode property... "if(!$event.type.indexOf('key')&&" + (keys.map(genFilterCode).join('&&')) + ")return null;" ) } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var keyCode = keyCodes[key]; var keyName = keyNames[key]; return ( "_k($event.keyCode," + (JSON.stringify(key)) + "," + (JSON.stringify(keyCode)) + "," + "$event.key," + "" + (JSON.stringify(keyName)) + ")" ) } /* */ function on (el, dir) { if (dir.modifiers) { warn("v-on without argument does not support modifiers."); } el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); }; } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")") }; } /* */ var baseDirectives = { on: on, bind: bind$1, cloak: noop }; /* */ var CodegenState = function CodegenState (options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); var isReservedTag = options.isReservedTag || no; this.maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; this.pre = false; }; function generate ( ast, options ) { var state = new CodegenState(options); var code = ast ? genElement(ast, state) : '_c("div")'; return { render: ("with(this){return " + code + "}"), staticRenderFns: state.staticRenderFns } } function genElement (el, state) { if (el.parent) { el.pre = el.pre || el.parent.pre; } if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget && !state.pre) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el, state); } else { var data; if (!el.plain || (el.pre && state.maybeComponent(el))) { data = genData$2(el, state); } var children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el, state) { el.staticProcessed = true; // Some elements (templates) need to behave differently inside of a v-pre // node. All pre nodes are static roots, so we can use this as a location to // wrap a state change and reset it upon exiting the pre node. var originalPreState = state.pre; if (el.pre) { state.pre = el.pre; } state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}")); state.pre = originalPreState; return ("_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { state.warn( "v-once can only be used inside v-for that is keyed. ", el.rawAttrsMap['v-once'] ); return genElement(el, state) } return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")") } else { return genStatic(el, state) } } function genIf ( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty) } function genIfConditions ( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state) } } function genFor ( el, state, altGen, altHelper ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if (state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", el.rawAttrsMap['v-for'], true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + "((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + ((altGen || genElement)(el, state)) + '})' } function genData$2 (el, state) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:" + (genProps(el.attrs)) + ","; } // DOM props if (el.props) { data += "domProps:" + (genProps(el.props)) + ","; } // event handlers if (el.events) { data += (genHandlers(el.events, false)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true)) + ","; } // slot target // only for non-scoped slots if (el.slotTarget && !el.slotScope) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el, el.scopedSlots, state)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind dynamic argument wrap // v-bind with dynamic arguments must be applied using the same v-bind object // merge helper so that class/style/mustUseProp attrs are handled correctly. if (el.dynamicAttrs) { data = "_b(" + data + ",\"" + (el.tag) + "\"," + (genProps(el.dynamicAttrs)) + ")"; } // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data } function genDirectives (el, state) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:" + (dir.isDynamicArg ? dir.arg : ("\"" + (dir.arg) + "\""))) : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el, state) { var ast = el.children[0]; if (el.children.length !== 1 || ast.type !== 1) { state.warn( 'Inline-template components must have exactly one child element.', { start: el.start } ); } if (ast && ast.type === 1) { var inlineRenderFns = generate(ast, state.options); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots ( el, slots, state ) { // by default scoped slots are considered "stable", this allows child // components with only scoped slots to skip forced updates from parent. // but in some cases we have to bail-out of this optimization // for example if the slot contains dynamic names, has v-if or v-for on them... var needsForceUpdate = el.for || Object.keys(slots).some(function (key) { var slot = slots[key]; return ( slot.slotTargetDynamic || slot.if || slot.for || containsSlotChild(slot) // is passing down slot from parent which may be dynamic ) }); // #9534: if a component with scoped slots is inside a conditional branch, // it's possible for the same component to be reused but with different // compiled slot content. To avoid that, we generate a unique key based on // the generated code of all the slot contents. var needsKey = !!el.if; // OR when it is inside another scoped slot or v-for (the reactivity may be // disconnected due to the intermediate scope variable) // #9438, #9506 // TODO: this can be further optimized by properly analyzing in-scope bindings // and skip force updating ones that do not actually use scope variables. if (!needsForceUpdate) { var parent = el.parent; while (parent) { if ( (parent.slotScope && parent.slotScope !== emptySlotScopeToken) || parent.for ) { needsForceUpdate = true; break } if (parent.if) { needsKey = true; } parent = parent.parent; } } var generatedSlots = Object.keys(slots) .map(function (key) { return genScopedSlot(slots[key], state); }) .join(','); return ("scopedSlots:_u([" + generatedSlots + "]" + (needsForceUpdate ? ",null,true" : "") + (!needsForceUpdate && needsKey ? (",null,false," + (hash(generatedSlots))) : "") + ")") } function hash(str) { var hash = 5381; var i = str.length; while(i) { hash = (hash * 33) ^ str.charCodeAt(--i); } return hash >>> 0 } function containsSlotChild (el) { if (el.type === 1) { if (el.tag === 'slot') { return true } return el.children.some(containsSlotChild) } return false } function genScopedSlot ( el, state ) { var isLegacySyntax = el.attrsMap['slot-scope']; if (el.if && !el.ifProcessed && !isLegacySyntax) { return genIf(el, state, genScopedSlot, "null") } if (el.for && !el.forProcessed) { return genFor(el, state, genScopedSlot) } var slotScope = el.slotScope === emptySlotScopeToken ? "" : String(el.slotScope); var fn = "function(" + slotScope + "){" + "return " + (el.tag === 'template' ? el.if && isLegacySyntax ? ("(" + (el.if) + ")?" + (genChildren(el, state) || 'undefined') + ":undefined") : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}"; // reverse proxy v-slot without scope on this.$slots var reverseProxy = slotScope ? "" : ",proxy:true"; return ("{key:" + (el.slotTarget || "\"default\"") + ",fn:" + fn + reverseProxy + "}") } function genChildren ( el, state, checkSkip, altGenElement, altGenNode ) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { var normalizationType = checkSkip ? state.maybeComponent(el$1) ? ",1" : ",0" : ""; return ("" + ((altGenElement || genElement)(el$1, state)) + normalizationType) } var normalizationType$1 = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; var gen = altGenNode || genNode; return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType$1 ? ("," + normalizationType$1) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType ( children, maybeComponent ) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function genNode (node, state) { if (node.type === 1) { return genElement(node, state) } else if (node.type === 3 && node.isComment) { return genComment(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genComment (comment) { return ("_e(" + (JSON.stringify(comment.text)) + ")") } function genSlot (el, state) { var slotName = el.slotName || '"default"'; var children = genChildren(el, state); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs || el.dynamicAttrs ? genProps((el.attrs || []).concat(el.dynamicAttrs || []).map(function (attr) { return ({ // slot props are camelized name: camelize(attr.name), value: attr.value, dynamic: attr.dynamic }); })) : null; var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent ( componentName, el, state ) { var children = el.inlineTemplate ? null : genChildren(el, state, true); return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var staticProps = ""; var dynamicProps = ""; for (var i = 0; i < props.length; i++) { var prop = props[i]; var value = transformSpecialNewlines(prop.value); if (prop.dynamic) { dynamicProps += (prop.name) + "," + value + ","; } else { staticProps += "\"" + (prop.name) + "\":" + value + ","; } } staticProps = "{" + (staticProps.slice(0, -1)) + "}"; if (dynamicProps) { return ("_d(" + staticProps + ",[" + (dynamicProps.slice(0, -1)) + "])") } else { return staticProps } } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast, warn) { if (ast) { checkNode(ast, warn); } } function checkNode (node, warn) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { var range = node.rawAttrsMap[name]; if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), warn, range); } else if (name === 'v-slot' || name[0] === '#') { checkFunctionParameterExpression(value, (name + "=\"" + value + "\""), warn, range); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), warn, range); } else { checkExpression(value, (name + "=\"" + value + "\""), warn, range); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], warn); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, warn, node); } } function checkEvent (exp, text, warn, range) { var stripped = exp.replace(stripStringRE, ''); var keywordMatch = stripped.match(unaryOperatorsRE); if (keywordMatch && stripped.charAt(keywordMatch.index - 1) !== '$') { warn( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()), range ); } checkExpression(exp, text, warn, range); } function checkFor (node, text, warn, range) { checkExpression(node.for || '', text, warn, range); checkIdentifier(node.alias, 'v-for alias', text, warn, range); checkIdentifier(node.iterator1, 'v-for iterator', text, warn, range); checkIdentifier(node.iterator2, 'v-for iterator', text, warn, range); } function checkIdentifier ( ident, type, text, warn, range ) { if (typeof ident === 'string') { try { new Function(("var " + ident + "=_")); } catch (e) { warn(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())), range); } } } function checkExpression (exp, text, warn, range) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { warn( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()), range ); } else { warn( "invalid expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n", range ); } } } function checkFunctionParameterExpression (exp, text, warn, range) { try { new Function(exp, ''); } catch (e) { warn( "invalid function parameter expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n", range ); } } /* */ var range = 2; function generateCodeFrame ( source, start, end ) { if ( start === void 0 ) start = 0; if ( end === void 0 ) end = source.length; var lines = source.split(/\r?\n/); var count = 0; var res = []; for (var i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (var j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) { continue } res.push(("" + (j + 1) + (repeat$1(" ", 3 - String(j + 1).length)) + "| " + (lines[j]))); var lineLength = lines[j].length; if (j === i) { // push underline var pad = start - (count - lineLength) + 1; var length = end > count ? lineLength - pad : end - start; res.push(" | " + repeat$1(" ", pad) + repeat$1("^", length)); } else if (j > i) { if (end > count) { var length$1 = Math.min(end - count, lineLength); res.push(" | " + repeat$1("^", length$1)); } count += lineLength + 1; } } break } } return res.join('\n') } function repeat$1 (str, n) { var result = ''; if (n > 0) { while (true) { // eslint-disable-line if (n & 1) { result += str; } n >>>= 1; if (n <= 0) { break } str += str; } } return result } /* */ function createFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompileToFunctionFn (compile) { var cache = Object.create(null); return function compileToFunctions ( template, options, vm ) { options = extend({}, options); var warn$$1 = options.warn || warn; delete options.warn; /* istanbul ignore if */ { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn$$1( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips { if (compiled.errors && compiled.errors.length) { if (options.outputSourceRange) { compiled.errors.forEach(function (e) { warn$$1( "Error compiling template:\n\n" + (e.msg) + "\n\n" + generateCodeFrame(template, e.start, e.end), vm ); }); } else { warn$$1( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } } if (compiled.tips && compiled.tips.length) { if (options.outputSourceRange) { compiled.tips.forEach(function (e) { return tip(e.msg, vm); }); } else { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function (code) { return createFunction(code, fnGenErrors) }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn$$1( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (cache[key] = res) } } /* */ function createCompilerCreator (baseCompile) { return function createCompiler (baseOptions) { function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; var warn = function (msg, range, tip) { (tip ? tips : errors).push(msg); }; if (options) { if (options.outputSourceRange) { // $flow-disable-line var leadingSpaceLength = template.match(/^\s*/)[0].length; warn = function (msg, range, tip) { var data = { msg: msg }; if (range) { if (range.start != null) { data.start = range.start + leadingSpaceLength; } if (range.end != null) { data.end = range.end + leadingSpaceLength; } } (tip ? tips : errors).push(data); }; } // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives || null), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } finalOptions.warn = warn; var compiled = baseCompile(template.trim(), finalOptions); { detectErrors(compiled.ast, warn); } compiled.errors = errors; compiled.tips = tips; return compiled } return { compile: compile, compileToFunctions: createCompileToFunctionFn(compile) } } } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. var createCompiler = createCompilerCreator(function baseCompile ( template, options ) { var ast = parse(template.trim(), options); if (options.optimize !== false) { optimize(ast, options); } var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } }); /* */ var ref$1 = createCompiler(baseOptions); var compile = ref$1.compile; var compileToFunctions = ref$1.compileToFunctions; /* */ // check whether current browser encodes a char inside attribute values var div; function getShouldDecode (href) { div = div || document.createElement('div'); div.innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>"; return div.innerHTML.indexOf('&#10;') > 0 } // #3663: IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false; // #6828: chrome encodes content in a[href] var shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue.prototype.$mount; Vue.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (!template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { outputSourceRange: "development" !== 'production', shouldDecodeNewlines: shouldDecodeNewlines, shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref, delimiters: options.delimiters, comments: options.comments }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (config.performance && mark) { mark('compile end'); measure(("vue " + (this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue.compile = compileToFunctions; module.exports = Vue; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../../timers-browserify/main.js */ "./node_modules/timers-browserify/main.js").setImmediate)) /***/ }), /***/ "./node_modules/vue/dist/vue.common.js": /*!*********************************************!*\ !*** ./node_modules/vue/dist/vue.common.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { if (false) {} else { module.exports = __webpack_require__(/*! ./vue.common.dev.js */ "./node_modules/vue/dist/vue.common.dev.js") } /***/ }), /***/ "./node_modules/webpack/buildin/global.js": /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ "./resources/js/app.js": /*!*****************************!*\ !*** ./resources/js/app.js ***! \*****************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vue */ "./node_modules/vue/dist/vue.common.js"); /* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vue__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var vue_socket_io__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vue-socket.io */ "./node_modules/vue-socket.io/dist/vue-socketio.js"); /* harmony import */ var vue_socket_io__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(vue_socket_io__WEBPACK_IMPORTED_MODULE_1__); vue__WEBPACK_IMPORTED_MODULE_0___default.a.use(new vue_socket_io__WEBPACK_IMPORTED_MODULE_1___default.a({ // debug: true, connection: 'http://localhost:3001/metaSearch', options: { path: "/ws" } })); var app = new vue__WEBPACK_IMPORTED_MODULE_0___default.a({ el: '#app', data: function data() { return { text: '', messages: [] }; }, methods: { sendMessage: function sendMessage() { console.log(this.$socket); this.$socket.emit('msgToEveryOne', this.text); this.text = ''; } }, sockets: { connect: function connect() { console.log('socket connected'); }, msgToClient: function msgToClient(data) { console.log(data); this.messages.push(data); } } }); /***/ }), /***/ "./resources/scss/app.scss": /*!*********************************!*\ !*** ./resources/scss/app.scss ***! \*********************************/ /*! no static exports found */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /***/ 0: /*!*************************************************************!*\ !*** multi ./resources/js/app.js ./resources/scss/app.scss ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! /opt/nest.ws.toturial/resources/js/app.js */"./resources/js/app.js"); module.exports = __webpack_require__(/*! /opt/nest.ws.toturial/resources/scss/app.scss */"./resources/scss/app.scss"); /***/ }) /******/ });
import React, { useState, useEffect } from "react" import { graphql } from "gatsby" import Img from "gatsby-image" import { motion, useAnimation } from "framer-motion" import { useScrollPosition } from "@n8tb1t/use-scroll-position" import { documentToReactComponents } from "@contentful/rich-text-react-renderer" import { BLOCKS } from "@contentful/rich-text-types" import Layout from "../components/layout" const IndexPage = ({ data: { allContentfulGroup } }) => { const [selectedComic, setComic] = useState(null) const [selectedMember, setMember] = useState(null) const controls = useAnimation() const memberControls = useAnimation() const [once, setOnce] = useState(false) useScrollPosition(({ prevPos, currPos }) => { if (currPos.y < -5 && !once) { controls.start("half") setOnce(true) } }, []) useEffect(() => { memberControls.start(i => ({ opacity: 1, x: 0, transition: { type: "spring", delay: i * 0.2, duration: 2 }, })) }, []) const { edges: [{ node }], } = allContentfulGroup const variants = { half: { maxHeight: "300px", transition: { duration: 1 } }, full: { maxHeight: "720px" }, } const closeDialog = () => { setComic(null) setMember(null) } return ( <Layout title="Home" closeDialog={closeDialog} selectedComic={selectedComic} selectedMember={selectedMember} > <> <div id="get" className="mt-4 pl-12 w-full md:w-3/5 relative" style={{ perspective: "1200px" }} > <motion.div animate={{ rotateY: 0, opacity: 1 }} style={{ originX: 0, originY: 0.5 }} initial={{ opacity: 0 }} transition={{ from: 90, duration: 2, ease: [0.04, 0, 0, 0.91], }} > <motion.img id="logo" className="object-scale-down text-left h-auto w-full" src={node.image.file.url} alt="Avengers" initial="full" variants={variants} animate={controls} ></motion.img> </motion.div> <div className="mt-8 overflow-y-scroll"> {documentToReactComponents(node.history.json, { renderNode: { [BLOCKS.HEADING_3]: (node, children) => ( <h2 className="text-xl font-semibold pb-4">{children}</h2> ), [BLOCKS.PARAGRAPH]: (node, children) => ( <p className="text-sm font-medium pb-4">{children}</p> ), }, })} <h2 className="text-3xl font-mont pb-4">Explore</h2> <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4"> {node.comics.map((comic, i) => { return ( <motion.div key={`${comic.id}-${i}`} onClick={() => setComic(comic)} layoutId={comic.id} className="flex flex-col" > <Img className="object-cover w-40 h-40" fluid={comic.image.fluid} /> <p className="text-xs text-gray-900 font-semibold text-sm"> {comic.title} </p> <span className="text-xs text-gray-700"> {comic.writer} </span> </motion.div> ) })} </div> </div> </div> <div className="w-full md:w-2/5 pl-12 relative"> <div className="flex flex-col justify-around" style={{ minHeight: "640px" }} > <h1 className="text-5xl font-mont">Avengers</h1> <div className="mb-4"> <p className="text-gray-900 font-mont text-sm"> Base of Operations </p> <span className="text-gray-700">{node.baseOfOperations}</span> </div> <div className="mb-4"> <p className="text-gray-900 font-mont text-sm">Slogan</p> <span className="text-gray-700">Avengers Assemble !!!</span> </div> <div className="mb-4"> <p className="text-gray-900 font-mont text-sm"> Place of formation </p> <span className="text-gray-700">Detroit, Michigan</span> </div> <div className="mb-4"> <p className="text-gray-900 font-mont text-sm">Creators</p> <span className="text-gray-700">Stan Lee, Jack Kirby</span> </div> <div className="mb-4"> <p className="text-gray-900 font-mont text-sm"> First Appearance </p> <span className="text-gray-700">Avengers #1 (1963)</span> </div> <div> <p className="text-gray-900 text-lg font-mont">Members</p> <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4"> {node.members.map((member, i) => ( <motion.div key={member.id} custom={i} layoutId={member.id} initial={{ x: -200, opacity: 0 }} onClick={() => setMember(member)} animate={memberControls} className="flex flex-col" > <Img className="object-cover w-24 h-24" fluid={member.avatar.fluid} /> <span className="text-xs font-medium text-gray-700 work-break"> {member.fullName} </span> </motion.div> ))} </div> </div> </div> </div> </> </Layout> ) } export default IndexPage export const query = graphql` { allContentfulGroup { edges { node { id title history { history json } baseOfOperations image { file { url } } members { id fullName gender powers groupAffiliation bio { bio json } avatar { fluid(maxWidth: 800) { ...GatsbyContentfulFluid_withWebp } } } comics { id title slug writer published(fromNow: true) description { json description } artists image { fluid(maxWidth: 800) { ...GatsbyContentfulFluid_withWebp } } } } } } } `
const childProc = require('child_process'); const path = require('path'); const http = require('http'); const tmp = require('tmp'); const fs = require('fs'); const disableIntermediatePkiEngine = function( vaultBinary, vaultUrlPath, vaultToken ) { console.log('Disabling PKI secret engine at ' + vaultUrlPath); const vaultLoginCommand = [ vaultBinary, 'login', vaultToken ]; try { childProc.execSync( vaultLoginCommand.join(' ') ); var vaultDisablePkiSecret = [ vaultBinary, 'secrets', 'disable', vaultUrlPath ]; childProc.execSync( vaultDisablePkiSecret.join(' ') ); } catch ( error ) { console.log("Could not create PKI engine"); } }; const createServiceRole = function( vaultUrlPath, vaultToken, allowedDomains ) { const createRoleRequest = { "allowed_domains": allowedDomains, "allow_subdomains": true }; console.log('Creating service role for : ' + allowedDomains); const postData = JSON.stringify( createRoleRequest ); const createServiceRoleRequest = { hostname: 'localhost', port: 8200, path: '/v1/' + vaultUrlPath + '/roles/services', method: 'POST', headers: { 'X-Vault-Token': vaultToken, 'Content-Length': Buffer.byteLength( postData ), 'Content-Type': 'application/json' } }; const req = http.request( createServiceRoleRequest, (res) => { var data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Service Role Created'); }); }); req.on('error', (e) => { console.error(`problem creating service role: ${e.message}`); }); req.write( postData ); req.end(); } const createIntermediatePkiEngine = function( vaultBinary, vaultUrlPath, vaultToken ) { console.log('Creating PKI secret engine at ' + vaultUrlPath); try { const vaultLoginCommand = [ vaultBinary, 'login', vaultToken ]; childProc.execSync( vaultLoginCommand.join(' ') ); var vaultCreatePkiSecret = [ vaultBinary, 'secrets', 'enable', '-path=' + vaultUrlPath, 'pki' ]; childProc.execSync( vaultCreatePkiSecret.join(' ') ); var vaultTunePkiSecret = [ vaultBinary, 'secrets', 'tune', '-max-lease-ttl=336h', vaultUrlPath ]; childProc.execSync( vaultTunePkiSecret.join(' ') ); } catch ( error ) { console.log("Could not create PKI engine"); } }; const buildTrustChain = function( baseCaFolder ) { const caFolder = path.resolve( baseCaFolder ); const parentCaFolder = path.resolve( baseCaFolder + path.sep + '..' ); const caName = caFolder.split(path.sep).pop(); var caPublicFileName = ''; if( caName == 'root' ) { caPublicFileName = caName + '.pem'; } else { caPublicFileName = caName + '-intermediate.pem'; } const caPublicFilePath = path.resolve( caFolder + path.sep + caPublicFileName ); var publicCa = fs.readFileSync( caPublicFilePath ); if( caName == 'root' ) { return publicCa; } else { return publicCa + buildTrustChain( parentCaFolder ); } }; const uploadSignedCertificate = function( parentCaDir, signedRequest, vaultUrlPath, vaultToken, allowedDomains ) { var trustChain = ""; try { trustChain = buildTrustChain( parentCaDir ); console.log('Trust Chain :\n'+trustChain); } catch ( error ) { console.log('Error building trust chain: ' + error); } if( trustChain ) { const signedCaRequest = { 'certificate': signedRequest + '\n' + trustChain }; const postData = JSON.stringify( signedCaRequest ); console.log("Signed request : " + postData); const uploadSignedCa = { hostname: 'localhost', port: 8200, path: '/v1/' + vaultUrlPath + '/intermediate/set-signed', method: 'POST', headers: { 'X-Vault-Token': vaultToken, 'Content-Length': Buffer.byteLength( postData ), 'Content-Type': 'application/json' } }; const req = http.request( uploadSignedCa, (res) => { var data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { createServiceRole( vaultUrlPath, vaultToken, allowedDomains ); console.log('Certificate Uploaded - Ready to Use'); }); }); req.on('error', (e) => { console.error(`problem uploading singed certificate: ${e.message}`); }); req.write( postData ); req.end(); } else { console.log('Cannot upload an empty trust chain'); } }; const signCertificate = function( parentCaDir, certResponse, vaultUrlPath, vaultToken, allowedDomains ) { const parentCaFolder = path.resolve( parentCaDir ); const parentCaPublicFileName = parentCaFolder.split(path.sep).pop() + '-intermediate.pem'; const parentCaPrivateFileName = parentCaFolder.split(path.sep).pop() + '-key.pem'; const parentCaPublicFilePath = path.resolve( parentCaDir + path.sep + parentCaPublicFileName ); const parentCaPrivateFilePath = path.resolve( parentCaDir + path.sep + parentCaPrivateFileName ); const vaultCert = JSON.parse( certResponse ); const vaultIntermediateConfig = { "signing": { "default": { "usages": [ "signing", "key encipherment", "cert sign", "crl sign" ], "expiry": "672h", "is_ca": true, "ca_constraint": { "is_ca": true, "max_path_len": 0, "max_path_len_zero": false } } } }; var tmpVaultPublicCert = tmp.fileSync(); var tmpVaultPublicCertConfig = tmp.fileSync(); var tmpDir = tmp.dirSync(); var intermediatePemName = path.resolve( tmpDir.name, 'vault-intermediate' ); fs.writeFileSync( tmpVaultPublicCert.fd, vaultCert.data.csr ); fs.writeFileSync( tmpVaultPublicCertConfig.fd, JSON.stringify( vaultIntermediateConfig ) ); console.log( "Signing Certificate: \n" + vaultCert.data.csr ); try { var cfsslCommand = [ 'cfssl','sign', '-ca',parentCaPublicFilePath, '-ca-key',parentCaPrivateFilePath, '-config',tmpVaultPublicCertConfig.name, tmpVaultPublicCert.name, '|', 'cfssljson','-bare', intermediatePemName ]; childProc.execSync( cfsslCommand.join(' ') ); console.log('Signed cert writed to ' + intermediatePemName + '.pem'); var signedCa = fs.readFileSync( intermediatePemName + ".pem" ); console.log("Signed Cert :\n" + signedCa); } catch ( error ) { console.log("Error signing intermediate CA: " + error); } uploadSignedCertificate( parentCaDir, signedCa, vaultUrlPath, vaultToken, allowedDomains ); }; const createIntermediateCA = function( parentCaDir, caInfo, vaultUrlPath, vaultToken, allowedDomains ) { const postData = JSON.stringify(caInfo); const generateCaOptions = { hostname: 'localhost', port: 8200, path: '/v1/' + vaultUrlPath + '/intermediate/generate/internal', method: 'POST', headers: { 'X-Vault-Token': vaultToken, 'Content-Length': Buffer.byteLength( postData ), 'Content-Type': 'application/json' } }; const req = http.request( generateCaOptions, (res) => { var data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { signCertificate( parentCaDir, data, vaultUrlPath, vaultToken, allowedDomains ); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); req.write( postData ); req.end(); }; const createIntermediate = function( parentCaDir, vaultDirPath, vaultUrlPath, vaultToken, commonName, options ) { const vaultBinary = path.resolve( vaultDirPath + path.sep + 'vault.exe' ); const intermediateFolder = path.resolve( parentCaDir ); const intermediatePublicFile = intermediateFolder.split(path.sep).pop() + '-intermediate.pem'; const intermediatePrivateFile = intermediateFolder.split(path.sep).pop() + '-key.pem'; console.log('Vault Binary : ' + vaultBinary); console.log('Intermediate Directory : ' + intermediateFolder); console.log('Intermediate Public File : ' + intermediatePublicFile); console.log('Intermediate Private File: ' + intermediatePrivateFile); console.log('Hashicorp Vault Token : ' + vaultToken); if( options.replace ) { disableIntermediatePkiEngine( vaultBinary, vaultUrlPath, vaultToken ); } createIntermediatePkiEngine( vaultBinary, vaultUrlPath, vaultToken ); const caInfo = { 'common_name': commonName }; if( options.organization ) { caInfo.organization = options.organization; } if( options.ou ) { caInfo.ou = options.ou; } if( options.country ) { caInfo.country = options.country; } if( options.locality ) { caInfo.locality = options.locality; } if( options.province ) { caInfo.province = options.province; } if( options.street ) { caInfo.street_address = options.street; } if( options.postalCode ) { caInfo.postal_code = options.postalCode; } if( options.names ) { caInfo.alt_names = options.names; } if( options.ttl ) { caInfo.ttl = options.ttl; } allowedDomains = options.domains || ['example.com']; createIntermediateCA( parentCaDir, caInfo, vaultUrlPath, vaultToken, allowedDomains ); }; module.exports = { createIntermediate };
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import fs from "fs"; import path from "path"; import { useStrict } from "mobx"; import { verifyFile, FileTypes, parseSuiteRequirements, migrateTestCase, migrateProject, migrateUrls } from "../../../IO/legacy/migrate"; useStrict(true); describe("file classifier", () => { it("should recognize suite", () => { const suite = fs.readFileSync(path.join(__dirname, "IDE_test_4/000_clear_mandant_Suite.html")).toString(); expect(verifyFile(suite)).toBe(FileTypes.Suite); }); it("should recognize test case", () => { const test = fs.readFileSync(path.join(__dirname, "IDE_test.html")).toString(); expect(verifyFile(test)).toBe(FileTypes.TestCase); }); it("should throw when another file is given", () => { expect(() => { verifyFile("something is wrong here"); }).toThrowError("Unknown file was received"); }); }); describe("selenium test case migration", () => { it("should migrate the set example", () => { const file = fs.readFileSync(path.join(__dirname, "IDE_test.html")).toString(); const { test } = migrateTestCase(file); expect(test.commands.length).toBe(4); const command = test.commands[0]; expect(command.command).toBe("open"); expect(command.target).toBe("/?gfe_rd=cr&dcr=0&ei=9vz6Way_KdPPXqjmsbgI&gws_rd=ssl"); expect(command.value).toBe(""); }); it("should migrate the second example", () => { const file = fs.readFileSync(path.join(__dirname, "IDE_test_2.html")).toString(); const { test } = migrateTestCase(file); expect(test.commands.length).toBe(26); }); it("should join line breaks to <br /> in the target field", () => { const file = fs.readFileSync(path.join(__dirname, "IDE_test_2.html")).toString(); const { test } = migrateTestCase(file); expect(test.commands[8].target).toBe("//a[contains(text(),'Most<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;followers')]"); }); it("should sanitize the input prior to converting", () => { const file = fs.readFileSync(path.join(__dirname, "IDE_test_3.html")).toString(); const { test } = migrateTestCase(file); expect(test.name).toBe("Show Details"); expect(test.commands[0].target).toBe("http://unknow.url/?func=ll&objid=2838227"); }); it("should decode the input post conversion", () => { const file = fs.readFileSync(path.join(__dirname, "IDE_test_8.html")).toString(); const { test } = migrateTestCase(file); expect(test.commands[14].target).toBe("//a[@onclick='return confirm(\"Wollen Sie den Datensatz wirklich löschen?\")']"); }); }); describe("selenium suite migration", () => { it("should give a list of required test cases", () => { const suite = fs.readFileSync(path.join(__dirname, "IDE_test_4/000_clear_mandant_Suite.html")).toString(); const required = parseSuiteRequirements(suite); expect(required.length).toBe(3); expect(required).toEqual(["einzeltests/MH_delete.html", "einzeltests/kontakte_leeren.html", "einzeltests/DMS_clear.html"]); }); it("should migrate the suite", () => { const files = [ { name: "000_clear_mandant_Suite.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "000_clear_mandant_Suite.html")).toString() }, { name: "einzeltests/DMS_clear.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/DMS_clear.html")).toString() }, { name: "einzeltests/kontakte_leeren.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/kontakte_leeren.html")).toString() }, { name: "einzeltests/MH_delete.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/MH_delete.html")).toString() } ]; expect(migrateProject(files).suites.length).toBe(1); }); it("should fail to migrate due to missing test case", () => { const files = [ { name: "000_clear_mandant_Suite.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "000_clear_mandant_Suite.html")).toString() }, { name: "einzeltests/DMS_clear.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/DMS_clear.html")).toString() }, { name: "einzeltests/kontakte_leeren.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/kontakte_leeren.html")).toString() } ]; expect(() => { migrateProject(files); }).toThrow("The file einzeltests/MH_delete.html is missing, suite can't be migrated"); }); it("should migrate multiple suites", () => { const files = [ { name: "000_clear_mandant_Suite.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "000_clear_mandant_Suite.html")).toString() }, { name: "001_clear_mandant_Suite.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "000_clear_mandant_Suite.html")).toString() }, { name: "einzeltests/DMS_clear.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/DMS_clear.html")).toString() }, { name: "einzeltests/kontakte_leeren.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/kontakte_leeren.html")).toString() }, { name: "einzeltests/MH_delete.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/MH_delete.html")).toString() } ]; const project = migrateProject(files); expect(project.suites.length).toBe(2); expect(project.tests.length).toBe(3); }); it("should create a suite if none was given", () => { const files = [ { name: "einzeltests/DMS_clear.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/DMS_clear.html")).toString() }, { name: "einzeltests/kontakte_leeren.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/kontakte_leeren.html")).toString() }, { name: "einzeltests/MH_delete.html", contents: fs.readFileSync(path.join(__dirname, "IDE_test_4", "einzeltests/MH_delete.html")).toString() } ]; const project = migrateProject(files); expect(project.suites.length).toBe(1); expect(project.tests.length).toBe(3); }); }); describe("url migration", () => { it("should migrate all urls to absolute ones", () => { const test = { commands: [ { command: "open", target: "/index.html" }, { command: "open", target: "/users" } ] }; const baseUrl = "https://seleniumhq.org/"; const migrated = migrateUrls(test, baseUrl); expect(migrated.commands[0].target).toBe("https://seleniumhq.org/index.html"); expect(migrated.commands[1].target).toBe("https://seleniumhq.org/users"); }); it("should not migrate absolute urls", () => { const test = { commands: [ { command: "open", target: "https://seleniumhq.org/index.html" } ] }; const baseUrl = "https://wikipedia.org"; const migrated = migrateUrls(test, baseUrl); expect(migrated.commands[0].target).toBe("https://seleniumhq.org/index.html"); }); });
import React from "react"; import { render } from "react-dom"; import { AppContainer } from "react-hot-loader"; import configureStore, { history } from "./store/configureStore"; import Root from "./components/Root"; import "./styles/styles.scss"; // Tell webpack to load favicon.ico require("./favicon.ico"); const store = configureStore(); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById("app") ); if (module.hot) { module.hot.accept("./components/Root", () => { const NewRoot = require("./components/Root").default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById("app") ); }); }
const features = require('../../config/features'); module.exports.tests = {}; // test exports module.exports.tests.interface = function(test, common) { test('interface: features', function(t) { t.true(Array.isArray(features.tags), 'valid taglist'); t.end(); }); }; // ensure some tags are excluded module.exports.tests.blacklist = function(test, common) { test('blacklist default tags', function(t) { // see: https://github.com/pelias/openstreetmap/pull/280 t.false( features.tags.includes('aeroway+name') ); t.false( features.tags.includes('aeroway~gate+name') ); t.false( features.tags.includes('railway+name') ); t.false( features.tags.includes('railway~rail+name') ); t.end(); }); }; // ensure some tags are included // we exclude by default tags corresponding to venues module.exports.tests.whitelist = function(test, common) { test('whitelist default tags', function(t) { t.true( features.tags.includes('addr:housenumber+addr:street') ); t.false( features.tags.includes('amenity+name') ); t.end(); }); }; // ensure some venue tags are included module.exports.tests.whitelist_venue_tags = function(test, common) { test('whitelist venue tags', function(t) { t.true( features.venue_tags.includes('amenity+name') ); t.true( features.venue_tags.includes('building+name') ); t.true( features.venue_tags.includes('shop+name') ); t.true( features.venue_tags.includes('office+name') ); t.true( features.venue_tags.includes('public_transport+name') ); t.true( features.venue_tags.includes('cuisine+name') ); t.true( features.venue_tags.includes('railway~tram_stop+name') ); t.true( features.venue_tags.includes('railway~station+name') ); t.true( features.venue_tags.includes('railway~halt+name') ); t.true( features.venue_tags.includes('railway~subway_entrance+name') ); t.true( features.venue_tags.includes('railway~train_station_entrance+name') ); t.true( features.venue_tags.includes('sport+name') ); t.true( features.venue_tags.includes('natural+name') ); t.true( features.venue_tags.includes('tourism+name') ); t.true( features.venue_tags.includes('leisure+name') ); t.true( features.venue_tags.includes('historic+name') ); t.true( features.venue_tags.includes('man_made+name') ); t.true( features.venue_tags.includes('landuse+name') ); t.true( features.venue_tags.includes('waterway+name') ); t.true( features.venue_tags.includes('aerialway+name') ); t.true( features.venue_tags.includes('craft+name') ); t.true( features.venue_tags.includes('military+name') ); t.true( features.venue_tags.includes('aeroway~terminal+name') ); t.true( features.venue_tags.includes('aeroway~aerodrome+name') ); t.true( features.venue_tags.includes('aeroway~helipad+name') ); t.true( features.venue_tags.includes('aeroway~airstrip+name') ); t.true( features.venue_tags.includes('aeroway~heliport+name') ); t.true( features.venue_tags.includes('aeroway~areodrome+name') ); t.true( features.venue_tags.includes('aeroway~spaceport+name') ); t.true( features.venue_tags.includes('aeroway~landing_strip+name') ); t.true( features.venue_tags.includes('aeroway~airfield+name') ); t.true( features.venue_tags.includes('aeroway~airport+name') ); t.true( features.venue_tags.includes('brand+name') ); t.true( features.venue_tags.includes('healthcare+name') ); t.end(); }); }; module.exports.all = function (tape, common) { function test(name, testFunction) { return tape('features: ' + name, testFunction); } for( var testCase in module.exports.tests ){ module.exports.tests[testCase](test, common); } };
from pyinfra import config from pyinfra.operations import server config.SUDO = True # Various different outputs # To see output need to run pyinfra with '-v' a = server.script( name='Hello', src='files/hello.bash', ) print('a', a) # To see output need to run pyinfra with '-v' b = server.shell( name='Say Hello', commands='echo Hello', ) print('b', b)
/* PrismJS 1.13.0 http://prismjs.com/download.html#themes=prism-solarizedlight&languages=markup+css+clike+javascript+bash */ var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-([\w-]+)\b/i,t=0,n=_self.Prism={manual:_self.Prism&&_self.Prism.manual,disableWorkerMessageHandler:_self.Prism&&_self.Prism.disableWorkerMessageHandler,util:{encode:function(e){return e instanceof r?new r(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},objId:function(e){return e.__id||Object.defineProperty(e,"__id",{value:++t}),e.__id},clone:function(e,t){var r=n.util.type(e);switch(t=t||{},r){case"Object":if(t[n.util.objId(e)])return t[n.util.objId(e)];var a={};t[n.util.objId(e)]=a;for(var l in e)e.hasOwnProperty(l)&&(a[l]=n.util.clone(e[l],t));return a;case"Array":if(t[n.util.objId(e)])return t[n.util.objId(e)];var a=[];return t[n.util.objId(e)]=a,e.forEach(function(e,r){a[r]=n.util.clone(e,t)}),a}return e}},languages:{extend:function(e,t){var r=n.util.clone(n.languages[e]);for(var a in t)r[a]=t[a];return r},insertBefore:function(e,t,r,a){a=a||n.languages;var l=a[e];if(2==arguments.length){r=arguments[1];for(var i in r)r.hasOwnProperty(i)&&(l[i]=r[i]);return l}var o={};for(var s in l)if(l.hasOwnProperty(s)){if(s==t)for(var i in r)r.hasOwnProperty(i)&&(o[i]=r[i]);o[s]=l[s]}return n.languages.DFS(n.languages,function(t,n){n===a[e]&&t!=e&&(this[t]=o)}),a[e]=o},DFS:function(e,t,r,a){a=a||{};for(var l in e)e.hasOwnProperty(l)&&(t.call(e,l,e[l],r||l),"Object"!==n.util.type(e[l])||a[n.util.objId(e[l])]?"Array"!==n.util.type(e[l])||a[n.util.objId(e[l])]||(a[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,l,a)):(a[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,null,a)))}},plugins:{},highlightAll:function(e,t){n.highlightAllUnder(document,e,t)},highlightAllUnder:function(e,t,r){var a={callback:r,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};n.hooks.run("before-highlightall",a);for(var l,i=a.elements||e.querySelectorAll(a.selector),o=0;l=i[o++];)n.highlightElement(l,t===!0,a.callback)},highlightElement:function(t,r,a){for(var l,i,o=t;o&&!e.test(o.className);)o=o.parentNode;o&&(l=(o.className.match(e)||[,""])[1].toLowerCase(),i=n.languages[l]),t.className=t.className.replace(e,"").replace(/\s+/g," ")+" language-"+l,t.parentNode&&(o=t.parentNode,/pre/i.test(o.nodeName)&&(o.className=o.className.replace(e,"").replace(/\s+/g," ")+" language-"+l));var s=t.textContent,u={element:t,language:l,grammar:i,code:s};if(n.hooks.run("before-sanity-check",u),!u.code||!u.grammar)return u.code&&(n.hooks.run("before-highlight",u),u.element.textContent=u.code,n.hooks.run("after-highlight",u)),n.hooks.run("complete",u),void 0;if(n.hooks.run("before-highlight",u),r&&_self.Worker){var g=new Worker(n.filename);g.onmessage=function(e){u.highlightedCode=e.data,n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,a&&a.call(u.element),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},g.postMessage(JSON.stringify({language:u.language,code:u.code,immediateClose:!0}))}else u.highlightedCode=n.highlight(u.code,u.grammar,u.language),n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,a&&a.call(t),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},highlight:function(e,t,a){var l={code:e,grammar:t,language:a};return n.hooks.run("before-tokenize",l),l.tokens=n.tokenize(l.code,l.grammar),n.hooks.run("after-tokenize",l),r.stringify(n.util.encode(l.tokens),l.language)},matchGrammar:function(e,t,r,a,l,i,o){var s=n.Token;for(var u in r)if(r.hasOwnProperty(u)&&r[u]){if(u==o)return;var g=r[u];g="Array"===n.util.type(g)?g:[g];for(var c=0;c<g.length;++c){var h=g[c],f=h.inside,d=!!h.lookbehind,m=!!h.greedy,p=0,y=h.alias;if(m&&!h.pattern.global){var v=h.pattern.toString().match(/[imuy]*$/)[0];h.pattern=RegExp(h.pattern.source,v+"g")}h=h.pattern||h;for(var b=a,k=l;b<t.length;k+=t[b].length,++b){var w=t[b];if(t.length>e.length)return;if(!(w instanceof s)){if(m&&b!=t.length-1){h.lastIndex=k;var _=h.exec(e);if(!_)break;for(var j=_.index+(d?_[1].length:0),P=_.index+_[0].length,A=b,x=k,O=t.length;O>A&&(P>x||!t[A].type&&!t[A-1].greedy);++A)x+=t[A].length,j>=x&&(++b,k=x);if(t[b]instanceof s)continue;I=A-b,w=e.slice(k,x),_.index-=k}else{h.lastIndex=0;var _=h.exec(w),I=1}if(_){d&&(p=_[1]?_[1].length:0);var j=_.index+p,_=_[0].slice(p),P=j+_.length,N=w.slice(0,j),S=w.slice(P),C=[b,I];N&&(++b,k+=N.length,C.push(N));var E=new s(u,f?n.tokenize(_,f):_,y,_,m);if(C.push(E),S&&C.push(S),Array.prototype.splice.apply(t,C),1!=I&&n.matchGrammar(e,t,r,b,k,!0,u),i)break}else if(i)break}}}}},tokenize:function(e,t){var r=[e],a=t.rest;if(a){for(var l in a)t[l]=a[l];delete t.rest}return n.matchGrammar(e,r,t,0,0,!1),r},hooks:{all:{},add:function(e,t){var r=n.hooks.all;r[e]=r[e]||[],r[e].push(t)},run:function(e,t){var r=n.hooks.all[e];if(r&&r.length)for(var a,l=0;a=r[l++];)a(t)}}},r=n.Token=function(e,t,n,r,a){this.type=e,this.content=t,this.alias=n,this.length=0|(r||"").length,this.greedy=!!a};if(r.stringify=function(e,t,a){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return r.stringify(n,t,e)}).join("");var l={type:e.type,content:r.stringify(e.content,t,a),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:a};if(e.alias){var i="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(l.classes,i)}n.hooks.run("wrap",l);var o=Object.keys(l.attributes).map(function(e){return e+'="'+(l.attributes[e]||"").replace(/"/g,"&quot;")+'"'}).join(" ");return"<"+l.tag+' class="'+l.classes.join(" ")+'"'+(o?" "+o:"")+">"+l.content+"</"+l.tag+">"},!_self.document)return _self.addEventListener?(n.disableWorkerMessageHandler||_self.addEventListener("message",function(e){var t=JSON.parse(e.data),r=t.language,a=t.code,l=t.immediateClose;_self.postMessage(n.highlight(a,n.languages[r],r)),l&&_self.close()},!1),_self.Prism):_self.Prism;var a=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return a&&(n.filename=a.src,n.manual||a.hasAttribute("data-manual")||("loading"!==document.readyState?window.requestAnimationFrame?window.requestAnimationFrame(n.highlightAll):window.setTimeout(n.highlightAll,16):document.addEventListener("DOMContentLoaded",n.highlightAll))),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); Prism.languages.markup={comment:/<!--[\s\S]*?-->/,prolog:/<\?[\s\S]+?\?>/,doctype:/<!DOCTYPE[\s\S]+?>/i,cdata:/<!\[CDATA\[[\s\S]*?]]>/i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+))?)*\s*\/?>/i,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+)/i,inside:{punctuation:[/^=/,{pattern:/(^|[^\\])["']/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/&#?[\da-z]{1,8};/i},Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity,Prism.hooks.add("wrap",function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&amp;/,"&"))}),Prism.languages.xml=Prism.languages.markup,Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup; Prism.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-]+?.*?(?:;|(?=\s*\{))/i,inside:{rule:/@[\w-]+/}},url:/url\((?:(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,selector:/[^{}\s][^{};]*?(?=\s*\{)/,string:{pattern:/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},property:/[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i,important:/\B!important\b/i,"function":/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:]/},Prism.languages.css.atrule.inside.rest=Prism.languages.css,Prism.languages.markup&&(Prism.languages.insertBefore("markup","tag",{style:{pattern:/(<style[\s\S]*?>)[\s\S]*?(?=<\/style>)/i,lookbehind:!0,inside:Prism.languages.css,alias:"language-css",greedy:!0}}),Prism.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:Prism.languages.markup.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:Prism.languages.css}},alias:"language-css"}},Prism.languages.markup.tag)); Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,"boolean":/\b(?:true|false)\b/,"function":/[a-z0-9_]+(?=\()/i,number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,punctuation:/[{}[\];(),.:]/}; Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,number:/\b(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|NaN|Infinity)\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?/,"function":/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*\()/i,operator:/-[-=]?|\+[+=]?|!=?=?|<<?=?|>>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[[^\]\r\n]+]|\\.|[^\/\\\[\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,lookbehind:!0,greedy:!0},"function-variable":{pattern:/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=\s*(?:function\b|(?:\([^()]*\)|[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/i,alias:"function"},constant:/\b[A-Z][A-Z\d_]*\b/}),Prism.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\[\s\S]|[^\\`])*`/,greedy:!0,inside:{interpolation:{pattern:/\$\{[^}]+\}/,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/(<script[\s\S]*?>)[\s\S]*?(?=<\/script>)/i,lookbehind:!0,inside:Prism.languages.javascript,alias:"language-javascript",greedy:!0}}),Prism.languages.js=Prism.languages.javascript; !function(e){var t={variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\([^)]+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},/\$(?:[\w#?*!@]+|\{[^}]+\})/i]};e.languages.bash={shebang:{pattern:/^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/,alias:"important"},comment:{pattern:/(^|[^"{\\])#.*/,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<\s*)["']?(\w+?)["']?\s*\r?\n(?:[\s\S])*?\r?\n\2/,lookbehind:!0,greedy:!0,inside:t},{pattern:/(["'])(?:\\[\s\S]|\$\([^)]+\)|`[^`]+`|(?!\1)[^\\])*\1/,greedy:!0,inside:t}],variable:t.variable,"function":{pattern:/(^|[\s;|&])(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|npm|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|[\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&])(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|[\s;|&])/,lookbehind:!0},"boolean":{pattern:/(^|[\s;|&])(?:true|false)(?=$|[\s;|&])/,lookbehind:!0},operator:/&&?|\|\|?|==?|!=?|<<<?|>>|<=?|>=?|=~/,punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];]/};var a=t.variable[1].inside;a.string=e.languages.bash.string,a["function"]=e.languages.bash["function"],a.keyword=e.languages.bash.keyword,a.boolean=e.languages.bash.boolean,a.operator=e.languages.bash.operator,a.punctuation=e.languages.bash.punctuation,e.languages.shell=e.languages.bash}(Prism);
function _defineProperty(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function asyncGeneratorStep(e,r,t,s,n,i,o){try{var l=e[i](o),c=l.value}catch(a){return void t(a)}l.done?r(c):Promise.resolve(c).then(s,n)}function _asyncToGenerator(e){return function(){var r=this,t=arguments;return new Promise((function(s,n){var i=e.apply(r,t);function o(e){asyncGeneratorStep(i,s,n,o,l,"next",e)}function l(e){asyncGeneratorStep(i,s,n,o,l,"throw",e)}o(void 0)}))}}function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var s=r[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),e}(window.webpackJsonp=window.webpackJsonp||[]).push([[67],{CXux:function(e,r,t){"use strict";t.r(r),t.d(r,"ion_refresher",(function(){return o})),t.d(r,"ion_refresher_content",(function(){return l}));var s=t("c1op"),n=t("AfW+"),i=t("YtD4"),o=function(){function e(r){_classCallCheck(this,e),Object(s.l)(this,r),this.appliedStyles=!1,this.didStart=!1,this.progress=0,this.state=1,this.pullMin=60,this.pullMax=this.pullMin+60,this.closeDuration="280ms",this.snapbackDuration="280ms",this.pullFactor=1,this.disabled=!1,this.ionRefresh=Object(s.e)(this,"ionRefresh",7),this.ionPull=Object(s.e)(this,"ionPull",7),this.ionStart=Object(s.e)(this,"ionStart",7)}var r,n,i;return _createClass(e,[{key:"disabledChanged",value:function(){this.gesture&&this.gesture.setDisabled(this.disabled)}},{key:"connectedCallback",value:(i=_asyncToGenerator(regeneratorRuntime.mark((function e(){var r,s=this;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("fixed"===this.el.getAttribute("slot")){e.next=2;break}return e.abrupt("return",void console.error('Make sure you use: <ion-refresher slot="fixed">'));case 2:if(!(r=this.el.closest("ion-content"))){e.next=13;break}return e.next=6,r.getScrollElement();case 6:return this.scrollEl=e.sent,e.next=9,Promise.resolve().then(t.bind(null,"mUkt"));case 9:this.gesture=e.sent.createGesture({el:r,gestureName:"refresher",gesturePriority:10,direction:"y",threshold:20,passive:!1,canStart:function(){return s.canStart()},onStart:function(){return s.onStart()},onMove:function(e){return s.onMove(e)},onEnd:function(){return s.onEnd()}}),this.disabledChanged(),e.next=14;break;case 13:console.error("<ion-refresher> must be used inside an <ion-content>");case 14:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"disconnectedCallback",value:function(){this.scrollEl=void 0,this.gesture&&(this.gesture.destroy(),this.gesture=void 0)}},{key:"complete",value:(n=_asyncToGenerator(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.close(32,"120ms");case 1:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"cancel",value:(r=_asyncToGenerator(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.close(16,"");case 1:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"getProgress",value:function(){return Promise.resolve(this.progress)}},{key:"canStart",value:function(){return!(!this.scrollEl||1!==this.state||this.scrollEl.scrollTop>0)}},{key:"onStart",value:function(){this.progress=0,this.state=1}},{key:"onMove",value:function(e){if(this.scrollEl){var r=e.event;if(!(r.touches&&r.touches.length>1)&&0==(56&this.state)){var t=Number.isNaN(this.pullFactor)||this.pullFactor<0?1:this.pullFactor,s=e.deltaY*t;if(s<=0)return this.progress=0,this.state=1,this.appliedStyles?void this.setCss(0,"",!1,""):void 0;if(1===this.state){if(this.scrollEl.scrollTop>0)return void(this.progress=0);this.state=2}if(r.cancelable&&r.preventDefault(),this.setCss(s,"0ms",!0,""),0!==s){var n=this.pullMin;this.progress=s/n,this.didStart||(this.didStart=!0,this.ionStart.emit()),this.ionPull.emit(),s<n?this.state=2:s>this.pullMax?this.beginRefresh():this.state=4}else this.progress=0}}}},{key:"onEnd",value:function(){4===this.state?this.beginRefresh():2===this.state&&this.cancel()}},{key:"beginRefresh",value:function(){this.state=8,this.setCss(this.pullMin,this.snapbackDuration,!0,""),this.ionRefresh.emit({complete:this.complete.bind(this)})}},{key:"close",value:function(e,r){var t=this;setTimeout((function(){t.state=1,t.progress=0,t.didStart=!1,t.setCss(0,"0ms",!1,"")}),600),this.state=e,this.setCss(0,this.closeDuration,!0,r)}},{key:"setCss",value:function(e,r,t,n){var i=this;this.appliedStyles=e>0,Object(s.m)((function(){if(i.scrollEl){var s=i.scrollEl.style;s.transform=e>0?"translateY(".concat(e,"px) translateZ(0px)"):"translateZ(0px)",s.transitionDuration=r,s.transitionDelay=n,s.overflow=t?"hidden":""}}))}},{key:"render",value:function(){var e,r=Object(s.d)(this);return Object(s.i)(s.a,{slot:"fixed",class:(e={},_defineProperty(e,r,!0),_defineProperty(e,"refresher-"+r,!0),_defineProperty(e,"refresher-active",1!==this.state),_defineProperty(e,"refresher-pulling",2===this.state),_defineProperty(e,"refresher-ready",4===this.state),_defineProperty(e,"refresher-refreshing",8===this.state),_defineProperty(e,"refresher-cancelling",16===this.state),_defineProperty(e,"refresher-completing",32===this.state),e)})}},{key:"el",get:function(){return Object(s.f)(this)}}],[{key:"watchers",get:function(){return{disabled:["disabledChanged"]}}},{key:"style",get:function(){return"ion-refresher{left:0;top:0;display:none;position:absolute;width:100%;height:60px;z-index:-1}:host-context([dir=rtl]) ion-refresher,[dir=rtl] ion-refresher{left:unset;right:unset;right:0}ion-refresher.refresher-active{display:block}ion-refresher-content{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;height:100%}.refresher-pulling,.refresher-refreshing{display:none;width:100%}.refresher-pulling-icon,.refresher-refreshing-icon{-webkit-transform-origin:center;transform-origin:center;-webkit-transition:.2s;transition:.2s;font-size:30px;text-align:center}:host-context([dir=rtl]) .refresher-pulling-icon,:host-context([dir=rtl]) .refresher-refreshing-icon,[dir=rtl] .refresher-pulling-icon,[dir=rtl] .refresher-refreshing-icon{-webkit-transform-origin:calc(100% - center);transform-origin:calc(100% - center)}.refresher-pulling-text,.refresher-refreshing-text{font-size:16px;text-align:center}.refresher-pulling ion-refresher-content .refresher-pulling,.refresher-ready ion-refresher-content .refresher-pulling{display:block}.refresher-ready ion-refresher-content .refresher-pulling-icon{-webkit-transform:rotate(180deg);transform:rotate(180deg)}.refresher-cancelling ion-refresher-content .refresher-pulling,.refresher-refreshing ion-refresher-content .refresher-refreshing{display:block}.refresher-cancelling ion-refresher-content .refresher-pulling-icon{-webkit-transform:scale(0);transform:scale(0)}.refresher-completing ion-refresher-content .refresher-refreshing{display:block}.refresher-completing ion-refresher-content .refresher-refreshing-icon{-webkit-transform:scale(0);transform:scale(0)}.refresher-ios .refresher-pulling-icon,.refresher-ios .refresher-pulling-text,.refresher-ios .refresher-refreshing-icon,.refresher-ios .refresher-refreshing-text{color:var(--ion-text-color,#000)}.refresher-ios .refresher-refreshing .spinner-crescent circle,.refresher-ios .refresher-refreshing .spinner-lines-ios line,.refresher-ios .refresher-refreshing .spinner-lines-small-ios line{stroke:var(--ion-text-color,#000)}.refresher-ios .refresher-refreshing .spinner-bubbles circle,.refresher-ios .refresher-refreshing .spinner-circles circle,.refresher-ios .refresher-refreshing .spinner-dots circle{fill:var(--ion-text-color,#000)}"}}]),e}(),l=function(){function e(r){_classCallCheck(this,e),Object(s.l)(this,r)}return _createClass(e,[{key:"componentWillLoad",value:function(){if(void 0===this.pullingIcon&&(this.pullingIcon=n.b.get("refreshingIcon","arrow-down")),void 0===this.refreshingSpinner){var e=Object(s.d)(this);this.refreshingSpinner=n.b.get("refreshingSpinner",n.b.get("spinner","ios"===e?"lines":"crescent"))}}},{key:"render",value:function(){return Object(s.i)(s.a,{class:Object(s.d)(this)},Object(s.i)("div",{class:"refresher-pulling"},this.pullingIcon&&Object(s.i)("div",{class:"refresher-pulling-icon"},Object(s.i)("ion-icon",{icon:this.pullingIcon,lazy:!1})),this.pullingText&&Object(s.i)("div",{class:"refresher-pulling-text",innerHTML:Object(i.a)(this.pullingText)})),Object(s.i)("div",{class:"refresher-refreshing"},this.refreshingSpinner&&Object(s.i)("div",{class:"refresher-refreshing-icon"},Object(s.i)("ion-spinner",{name:this.refreshingSpinner})),this.refreshingText&&Object(s.i)("div",{class:"refresher-refreshing-text",innerHTML:Object(i.a)(this.refreshingText)})))}}]),e}()}}]);
'use strict'; class LimitChars { constructor(element = null) { this._element = element; if (element.hasAttribute('maxlength')) this.setMaxLength(element.getAttribute('maxlength')); else this._maxLength = 0; if (element.hasAttribute('data-count-output')) this._countOutput = element.getAttribute('data-count-output'); else this._countOutput = null; element.addEventListener('input', () => { this._input(); }); this._input(); } _input() { let value = this._element.value; let maxLength = parseInt(this._maxLength); if (maxLength && value.length > maxLength) this._element.value = value.substr(0, maxLength); if (this._countOutput) { let nodes = document.querySelectorAll(this._countOutput); nodes = [].slice.call(nodes); nodes.forEach((elem) => { if (maxLength) { elem.innerHTML = maxLength - value.length; } else elem.innerHTML = value.length; }); } } setCountOutput(selector) { this._countOutput = selector; return this; } setMaxLength(length) { this._maxLength = parseInt(length); return this; } }
import request from 'supertest-as-promised'; import httpStatus from 'http-status'; import jwt from 'jsonwebtoken'; import chai, { expect } from 'chai'; import app from '../../index'; import config from '../../config/config'; import User from '../../server/models/user.model'; chai.config.includeStack = true; describe('## Auth APIs', () => { // Email based login const validUserCredentialsWithEmail = { username: 'react2', email: 'react2@email.com', name: 'Software Dev', password: 'express' }; const validEmailAsUsernameLogin = { username: 'react2@email.com', password: 'express' }; const validEmailLogin = { email: 'react2@email.com', password: 'express' }; const invalidEmailLogin = { email: 'react2@email.com', password: 'express21321' }; // ------------------------- const validUserCredentials = { username: 'react', password: 'express' }; const invalidUserCredentials = { username: 'react', }; const invalidLogin = { username: 'react', password: 'wrong', }; let jwtToken; afterEach((done) => { User.remove({}).exec() .then(() => { done(); }); }); // loingWithEmail describe('# POST /api/auth/register (with email & name)', () => { it('should get valid JWT token', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentialsWithEmail) .expect(httpStatus.CREATED) // We make sure we actually login: .then((res) => { //eslint-disable-line return request(app) .post('/api/auth/loginWithEmail') .send(validEmailLogin) .expect(httpStatus.OK); }) .then((res) => { expect(res.body).to.have.property('token'); jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => { expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions expect(decoded.username).to.equal(validUserCredentialsWithEmail.username); jwtToken = `Bearer ${res.body.token}`; done(); }); }) .catch(done); }); }); describe('# POST /api/auth/loginWithEmail', () => { it('should return Authentication error', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentialsWithEmail) .expect(httpStatus.CREATED) // We want to make sure we reject bad login .then((res) => { //eslint-disable-line return request(app) .post('/api/auth/loginWithEmail') .send(invalidEmailLogin) .expect(httpStatus.UNAUTHORIZED); }) .then((res) => { expect(res.body.message).to.equal('Password is incorrect.'); done(); }) .catch(done); }); }); describe('# POST /api/auth/loginWithEmail v2', () => { it('should return Authentication error', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentialsWithEmail) .expect(httpStatus.CREATED) // We want to make sure we reject bad login .then((res) => { //eslint-disable-line return request(app) .post('/api/auth/loginWithEmail') // THIS is an improperly formatted login format without an email field: .send(invalidLogin) .expect(httpStatus.BAD_REQUEST); }) .then((res) => { expect(res.body.message).to.equal('"email" is required'); done(); }) .catch(done); }); }); // -------- username <-> email login describe('# POST /api/auth/register (+ login with email field as username)', () => { it('should get valid JWT token', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentialsWithEmail) .expect(httpStatus.CREATED) // We make sure we actually login: .then((res) => { //eslint-disable-line return request(app) .post('/api/auth/login') .send(validEmailAsUsernameLogin) .expect(httpStatus.OK); }) .then((res) => { expect(res.body).to.have.property('token'); jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => { expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions expect(decoded.username).to.equal(validUserCredentialsWithEmail.username); jwtToken = `Bearer ${res.body.token}`; done(); }); }) .catch(done); }); }); describe('# POST /api/auth/login fail on not including username field', () => { it('should return Authentication error', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentialsWithEmail) .expect(httpStatus.CREATED) // We want to make sure we reject bad login .then((res) => { //eslint-disable-line return request(app) .post('/api/auth/login') // THIS is an improperly formatted loginf ormat without an email field: .send(invalidEmailLogin) .expect(httpStatus.BAD_REQUEST); }) .then((res) => { expect(res.body.message).to.equal('"username" is required'); done(); }) .catch(done); }); }); // -------- regular register + login unit tests describe('# POST /api/auth/register', () => { it('should return bad request error', (done) => { request(app) .post('/api/auth/register') .send(invalidUserCredentials) .expect(httpStatus.BAD_REQUEST) .then((res) => { expect(res.body.message).to.equal('"password" is required'); done(); }) .catch(done); }); it('should get valid JWT token', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentials) .expect(httpStatus.CREATED) .then((res) => { expect(res.body).to.have.property('token'); jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => { expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions expect(decoded.username).to.equal(validUserCredentials.username); jwtToken = `Bearer ${res.body.token}`; done(); }); }) .catch(done); }); }); describe('# POST /api/auth/login', () => { it('should return not found with unkown user', (done) => { request(app) .post('/api/auth/login') .send(invalidLogin) .expect(httpStatus.NOT_FOUND) .then((res) => { expect(res.body.message).to.equal('User not found.'); done(); }) .catch(done); }); it('should return Authentication error', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentials) .expect(httpStatus.CREATED) .then((res) => { //eslint-disable-line return request(app) .post('/api/auth/login') .send(invalidLogin) .expect(httpStatus.UNAUTHORIZED); }) .then((res) => { expect(res.body.message).to.equal('Password is incorrect.'); done(); }) .catch(done); }); it('should get valid JWT token', (done) => { request(app) .post('/api/auth/register') .send(validUserCredentials) .expect(httpStatus.CREATED) .then((res) => { //eslint-disable-line return request(app) .post('/api/auth/login') .send(validUserCredentials) .expect(httpStatus.OK); }) .then((res) => { expect(res.body).to.have.property('token'); jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => { expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions expect(decoded.username).to.equal(validUserCredentials.username); jwtToken = `Bearer ${res.body.token}`; done(); }); }) .catch(done); }); }); describe('# GET /api/auth/random-number', () => { it('should fail to get random number because of missing Authorization', (done) => { request(app) .get('/api/auth/random-number') .expect(httpStatus.UNAUTHORIZED) .then((res) => { expect(res.body.message).to.equal('Unauthorized'); done(); }) .catch(done); }); it('should fail to get random number because of wrong token', (done) => { request(app) .get('/api/auth/random-number') .set('Authorization', 'Bearer inValidToken') .expect(httpStatus.UNAUTHORIZED) .then((res) => { expect(res.body.message).to.equal('Unauthorized'); done(); }) .catch(done); }); it('should get a random number', (done) => { request(app) .get('/api/auth/random-number') .set('Authorization', jwtToken) .expect(httpStatus.OK) .then((res) => { expect(res.body.num).to.be.a('number'); done(); }) .catch(done); }); }); xdescribe('# GET /api/auth/:socialNetwork', () => { it('should return bad request error', () => { // call /api/auth/twitter }); it('should get valid JWT token', () => { // call /api/auth/facebook // call /api/auth/google }); }); });
/** * Internal dependencies */ import Card from '../index'; import CardBody from '../body'; import CardDivider from '../divider'; import { getCardStoryProps } from './_utils'; export default { title: 'Components/Card/Divider', component: CardDivider }; export const _default = () => { const props = getCardStoryProps(); return ( <Card { ...props }> <CardBody>...</CardBody> <CardDivider /> <CardBody>...</CardBody> </Card> ); };
module.exports = { type: "object", description: "Task meta-data.", properties: { id: { type: "string", description: "Unique identifier for the task; we generally use the path in the SVN.", title: "id", minLength: "5", options: { value_source: 'svn.path' } }, license: { type: "string", title: "License", enum: ["", "CC-BY-SA", "CC-BY-NC"] }, authors: { type: "array", title: "Authors", items: { type: "string" } }, language: { type: "string", description: 'Language for the task. If you want to have this task in multiple languages, copy the "index.html" file generated by this editor to another file "index_en.html" (for instance), and edit it manually.', enum: ["fr", "en", "de"] }, version: { type: "string", title: "Version" }, translators: { type: "array", title: "Translators", items: { type: "string" } } }, required: ["id", "authors", "language"], generator: [ { output: { inject: { template: "index.html", selector: "$json" } } } ] };
const ObjectId = require('mongodb').ObjectID; const _ = require('lodash'); const restrictedRoutes = [ { route: '/admin/product/new', response: 'redirect' }, { route: '/admin/product/insert', response: 'redirect' }, { route: '/admin/product/edit/:id', response: 'redirect' }, { route: '/admin/product/update', response: 'redirect' }, { route: '/admin/product/delete/:id', response: 'redirect' }, { route: '/admin/product/publishedState', response: 'json' }, { route: '/admin/product/setasmainimage', response: 'json' }, { route: '/admin/product/deleteimage', response: 'json' }, { route: '/admin/product/removeoption', response: 'json' }, { route: '/admin/order/statusupdate', response: 'json' }, { route: '/admin/settings/update', response: 'json' }, { route: '/admin/settings/pages/new', response: 'redirect' }, { route: '/admin/settings/pages/edit/:page', response: 'redirect' }, { route: '/admin/settings/pages', response: 'json' }, { route: '/admin/settings/page/delete/:page', response: 'json' }, { route: '/admin/settings/menu/new', response: 'json' }, { route: '/admin/settings/menu/update', response: 'json' }, { route: '/admin/settings/menu/delete', response: 'json' }, { route: '/admin/settings/menu/saveOrder', response: 'json' }, { route: '/admin/file/upload', response: 'json' }, ]; const restrict = (req, res, next) => { checkLogin(req, res, next); }; const checkCustomerPresent = (req, res, next) => { if (!req.session.customerPresent) { res.redirect('/customer/login'); } else { next(); } }; const checkLogin = async (req, res, next) => { const db = req.app.db; // if not protecting we check for public pages and don't checkLogin if (req.session.needsSetup === true) { res.redirect('/admin/setup'); return; } // If API key, check for a user if (req.headers.apikey) { try { const user = await db.users.findOne({ apiKey: ObjectId(req.headers.apikey), isAdmin: true, }); if (!user) { res.status(400).json({ message: 'Access denied' }); return; } // Set API authenticated in the req req.apiAuthenticated = true; next(); return; } catch (ex) { res.status(400).json({ message: 'Access denied' }); return; } } if (req.session.user) { next(); return; } res.redirect('/admin/login'); }; // Middleware to check for admin access for certain route const checkAccess = (req, res, next) => { const routeCheck = _.find(restrictedRoutes, { route: req.route.path }); // If the user is not an admin and route is restricted, show message and redirect to /admin if (req.session.isAdmin === false && routeCheck) { if (routeCheck.response === 'redirect') { req.session.message = 'Unauthorised. Please refer to administrator.'; req.session.messageType = 'danger'; res.redirect('/admin'); return; } if (routeCheck.response === 'json') { res.status(400).json({ message: 'Unauthorised. Please refer to administrator.', }); } } else { next(); } }; module.exports = { restrict, checkLogin, checkAccess, checkCustomerPresent, };
'use strict'; var should = require('should'); var sinon = require('sinon'); var bitcore = require('bitcore-lib'); var TxController = require('../lib/transactions'); var _ = require('lodash'); describe('Transactions', function() { describe('/tx/:txid', function() { it('should have correct data', function(done) { var insight = { 'txid': 'b85334bf2df35c6dd5b294efe92ffc793a78edff75a2ca666fc296ffb04bbba0', 'version': 1, 'locktime': 0, 'vin': [ { 'txid': '87c9b0f27571fff14b8c2d69e55614eacedd0f59fcc490b721320f9dae145aad', 'vout': 0, 'scriptSig': { 'asm': '30450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c01 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', 'hex': '4830450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307' }, 'sequence': 4294967295, 'n': 0, 'addr': 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', 'valueSat': 18535505, 'value': 0.18535505, 'doubleSpentTxID': null, 'isConfirmed': true, 'confirmations': 242, 'unconfirmedInput': false }, { 'txid': 'd8a10aaedf3dd33b5ddf8979273f3dbf61e4638d1aa6a93c59ea22bc65ac2196', 'vout': 0, 'scriptSig': { 'asm': '30440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb3101 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', 'hex': '4730440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb31014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307' }, 'sequence': 4294967295, 'n': 1, 'addr': 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', 'valueSat': 16419885, 'value': 0.16419885, 'doubleSpentTxID': null, 'isConfirmed': true, 'confirmations': 242, 'unconfirmedInput': false } ], 'vout': [ { 'value': '0.21247964', 'n': 0, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 4b7b335f978f130269fe661423258ae9642df8a1 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9144b7b335f978f130269fe661423258ae9642df8a188ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mnQ4ZaGessNgdxmWPxbTHcfx4b8R6eUr1X' ] }, 'spentTxId': null, 'spentIndex': null, 'spentHeight': null }, { 'value': '0.13677426', 'n': 1, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 6efcf883b4b6f9997be9a0600f6c095fe2bd2d92 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9146efcf883b4b6f9997be9a0600f6c095fe2bd2d9288ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f' ] }, 'spentTxId': '614fe1708825f9c21732394e4784cc6808ac1d8b939736bfdead970567561eec', 'spentIndex': 1, 'spentHeight': 10, 'spentTs': 1440997099 } ], 'blockhash': '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', 'blockheight': 533974, 'confirmations': 230, 'time': 1440987503, 'blocktime': 1440987503, 'valueOut': 0.3492539, 'size': 437, 'valueIn': 0.3495539, 'fees': 0.0003 }; var spentTxId = '614fe1708825f9c21732394e4784cc6808ac1d8b939736bfdead970567561eec'; var spentIndex = 1; var detailedTransaction = { hex: '7b5485d3628922f004f470f497f6a83f6df4df347e1bce15831a964623f8072b565f7c7bc5dcbc717c6e2a2301a2f6b4a19e65042ad88c9f5d037628de38603c4f137f625e135691e2bd0169cab74e1368abe858f3c3d116e9d13c4c85ead129d9edf0245a3fb1b35561bd230607dca0dcaf3cffc735a3982d8384a1ecc5d622a7bb4db8b5d47d061701978b1f45e2e39946d66c3394f8a20b8ac8c931a6786f761da2d0f3fa2c7c93edee9f2a94de7c47510498767c3d87afe68815bd6058710bf5d8c850a5d20fc217943d9c00da58a4908d92a0912578247746f2086e54cb7b81b6a9e3cc1741457e956d41bdeaae06c441db96ec39a2d17147dd8f468eeaeaaa78dc2e53d66188a791c46b2a4965639ad72a2b90ee52786e36db1a8cf924346b105a40b41a3027dae657782ef7e8b56d6da86062184cb5366d4886cd2ce27471d9d62d1df447f2e5a9641e1f8d1f2b628054d3bd915bf7932bcec6f2dd4965e2406b1dba445b5493ee475757de332618220318dd806b880a7364370c5c0c3b736a653f97b2901fdb5cf4b5b2230b09b2d7bd324a392633d51c598765f9bd286421239a1f25db34a9a61f645eb601e59f10fc1b', hash: 'b85334bf2df35c6dd5b294efe92ffc793a78edff75a2ca666fc296ffb04bbba0', version: 1, blockHash: '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', height: 533974, blockTimestamp: 1440987503, inputSatoshis: 34955390, outputSatoshis: 34925390, feeSatoshis: 30000, inputs: [ { address: 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', prevTxId: '87c9b0f27571fff14b8c2d69e55614eacedd0f59fcc490b721320f9dae145aad', outputIndex: 0, sequence: 4294967295, script: '4830450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', scriptAsm: '30450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c01 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', satoshis: 18535505, }, { address: 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', prevTxId: 'd8a10aaedf3dd33b5ddf8979273f3dbf61e4638d1aa6a93c59ea22bc65ac2196', outputIndex: 0, sequence: 4294967295, script: '4730440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb31014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', scriptAsm: '30440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb3101 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', satoshis: 16419885, } ], outputs: [ { satoshis: 21247964, script: '76a9144b7b335f978f130269fe661423258ae9642df8a188ac', scriptAsm: 'OP_DUP OP_HASH160 4b7b335f978f130269fe661423258ae9642df8a1 OP_EQUALVERIFY OP_CHECKSIG', address: 'mnQ4ZaGessNgdxmWPxbTHcfx4b8R6eUr1X' }, { address: 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', satoshis: 13677426, scriptAsm: 'OP_DUP OP_HASH160 6efcf883b4b6f9997be9a0600f6c095fe2bd2d92 OP_EQUALVERIFY OP_CHECKSIG', script: '76a9146efcf883b4b6f9997be9a0600f6c095fe2bd2d9288ac', spentTxId: spentTxId, spentIndex: spentIndex, spentHeight: 10 } ], locktime: 0 }; var todos = { vin: [ { isConfirmed: true, confirmations: 242, unconfirmedInput: false }, { isConfirmed: true, confirmations: 242, unconfirmedInput: false } ], vout: [ { scriptPubKey: { reqSigs: 1 } }, { scriptPubKey: { reqSigs: 1 }, spentTs: 1440997099 } ] }; var node = { getDetailedTransaction: sinon.stub().callsArgWith(1, null, detailedTransaction), services: { bitcoind: { height: 534203 }, }, network: 'testnet' }; var transactions = new TxController(node); var txid = 'b85334bf2df35c6dd5b294efe92ffc793a78edff75a2ca666fc296ffb04bbba0'; var req = { params: { txid: txid } }; var res = {}; var next = function() { var merged = _.merge(req.transaction, todos); should(merged).eql(insight); done(); }; transactions.transaction(req, res, next); }); }); describe('/txs', function() { var sandbox = sinon.sandbox.create(); afterEach(function() { sandbox.restore(); }); it('by block hash', function(done) { var blockOverview = { hash: '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', height: 533974, chainWork: '0000000000000000000000000000000000000000000000054626b1839ade284a', prevHash: '00000000000001a55f3214e9172eb34b20e0bc5bd6b8007f3f149fca2c8991a4', txids: [ '25a988e54b02e0e5df146a0f8fa7b9db56210533a9f04bdfda5f4ceb6f77aadd', 'b85334bf2df35c6dd5b294efe92ffc793a78edff75a2ca666fc296ffb04bbba0', '2e01c7a4a0e335112236b711c4aaddd02e8dc59ba2cda416e8f80ff06dddd7e1' ] }; var transactionDetails = { '25a988e54b02e0e5df146a0f8fa7b9db56210533a9f04bdfda5f4ceb6f77aadd': { hex: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2303d6250800feb0aae355fe263600000963676d696e6572343208ae5800000000000000ffffffff01c018824a000000001976a91468bedce8982d25c3b6b03f6238cbad00378b8ead88ac00000000', coinbase: true, version: 1, blockTimestamp: 1440987503, blockHash: '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', height: 533974, inputSatoshis: 0, outputSatoshis: 1250040000, feeSatoshis: 0, locktime: 0, hash: '25a988e54b02e0e5df146a0f8fa7b9db56210533a9f04bdfda5f4ceb6f77aadd', inputs: [ { script: '03d6250800feb0aae355fe263600000963676d696e6572343208ae5800000000000000', sequence: 4294967295 } ], outputs: [ { address: 'mq4oDPjmNWnBxbzx7qouzhpCSTMePUtYDF', script: '76a91468bedce8982d25c3b6b03f6238cbad00378b8ead88ac', scriptAsm: 'OP_DUP OP_HASH160 68bedce8982d25c3b6b03f6238cbad00378b8ead OP_EQUALVERIFY OP_CHECKSIG', satoshis: 1250040000 } ] }, 'b85334bf2df35c6dd5b294efe92ffc793a78edff75a2ca666fc296ffb04bbba0': { hex: '0100000002ad5a14ae9d0f3221b790c4fc590fddceea1456e5692d8c4bf1ff7175f2b0c987000000008b4830450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307ffffffff9621ac65bc22ea593ca9a61a8d63e461bf3d3f277989df5d3bd33ddfae0aa1d8000000008a4730440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb31014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307ffffffff02dc374401000000001976a9144b7b335f978f130269fe661423258ae9642df8a188ac72b3d000000000001976a9146efcf883b4b6f9997be9a0600f6c095fe2bd2d9288ac00000000', inputSatoshis: 34955390, outputSatoshis: 34925390, feeSatoshis: 30000, version: 1, hash: 'b85334bf2df35c6dd5b294efe92ffc793a78edff75a2ca666fc296ffb04bbba0', blockTimestamp: 1440987503, height: 533974, blockHash: '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', locktime: 0, inputs: [ { satoshis: 18535505, address: 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', script: '4830450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', scriptAsm: '30450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c01 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', prevTxId: '87c9b0f27571fff14b8c2d69e55614eacedd0f59fcc490b721320f9dae145aad', outputIndex: 0, sequence: 4294967295 }, { address: 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', script: '4730440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb31014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', scriptAsm: '30440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb3101 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', satoshis: 16419885, sequence: 4294967295, prevTxId: 'd8a10aaedf3dd33b5ddf8979273f3dbf61e4638d1aa6a93c59ea22bc65ac2196', outputIndex: 0 } ], outputs: [ { address: 'mnQ4ZaGessNgdxmWPxbTHcfx4b8R6eUr1X', script: '76a9144b7b335f978f130269fe661423258ae9642df8a188ac', scriptAsm: 'OP_DUP OP_HASH160 4b7b335f978f130269fe661423258ae9642df8a1 OP_EQUALVERIFY OP_CHECKSIG', satoshis: 21247964 }, { script: '76a9146efcf883b4b6f9997be9a0600f6c095fe2bd2d9288ac', scriptAsm: 'OP_DUP OP_HASH160 6efcf883b4b6f9997be9a0600f6c095fe2bd2d92 OP_EQUALVERIFY OP_CHECKSIG', address: 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', satoshis: 13677426, spentTxId: '614fe1708825f9c21732394e4784cc6808ac1d8b939736bfdead970567561eec', spentIndex: 1, spentHeight: 200 } ] }, '2e01c7a4a0e335112236b711c4aaddd02e8dc59ba2cda416e8f80ff06dddd7e1': { hex: '0100000002060d3cb6dfb7ffe85e2908010fea63190c9707e96fc7448128eb895b5e222771030000006b483045022100f67cffc0ae23adb236ff3edb4a9736e277605db30cc7708dfab8cf1e1483bbce022052396aa5d664ec1cb65992c423fd9a17e94dc7af328d2d559e90746dd195ca5901210346134da14907581d8190d3980caaf46d95e4eb9c1ca8e70f1fc6007fefb1909dfeffffff7b2d8a8263cffbdb722e2a5c74166e6f2258634e277c0b08f51b578b667e2fba000000006a473044022077222a91cda23af69179377c62d84a176fb12caff6c5cbf6ae9e5957ff3b1afe0220768edead76819228dcba18cca3c9a5a5d4c32919720f21df21a297ba375bbe5c012103371ea5a4dfe356b3ea4042a537d7ab7ee0faabd43e21b6cc076fda2240629eeefeffffff02209a1d00000000001976a9148e451eec7ca0a1764b4ab119274efdd2727b3c8588ac40420f00000000001976a914d0fce8f064cd1059a6a11501dd66fe42368572b088accb250800', blockHash: '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', blockTimestamp: 1440987503, height: 533974, locktime: 533963, inputSatoshis: 2950000, outputSatoshis: 2940000, feeSatoshis: 10000, version: 1, hash: '2e01c7a4a0e335112236b711c4aaddd02e8dc59ba2cda416e8f80ff06dddd7e1', inputs: [ { address: 'mgZK8zpudWoAaAwpLQSgc9t9PJJyEBpBdJ', satoshis: 990000, script: '483045022100f67cffc0ae23adb236ff3edb4a9736e277605db30cc7708dfab8cf1e1483bbce022052396aa5d664ec1cb65992c423fd9a17e94dc7af328d2d559e90746dd195ca5901210346134da14907581d8190d3980caaf46d95e4eb9c1ca8e70f1fc6007fefb1909d', scriptAsm: '3045022100f67cffc0ae23adb236ff3edb4a9736e277605db30cc7708dfab8cf1e1483bbce022052396aa5d664ec1cb65992c423fd9a17e94dc7af328d2d559e90746dd195ca5901 0346134da14907581d8190d3980caaf46d95e4eb9c1ca8e70f1fc6007fefb1909d', sequence: 4294967294, outputIndex: 3, prevTxId: '7127225e5b89eb288144c76fe907970c1963ea0f0108295ee8ffb7dfb63c0d06' }, { address: 'n4oM7bPuC4ZPdCEDvtw9xGYQC7jmi5S6F4', satoshis: 1960000, script: '473044022077222a91cda23af69179377c62d84a176fb12caff6c5cbf6ae9e5957ff3b1afe0220768edead76819228dcba18cca3c9a5a5d4c32919720f21df21a297ba375bbe5c012103371ea5a4dfe356b3ea4042a537d7ab7ee0faabd43e21b6cc076fda2240629eee', scriptAsm: '3044022077222a91cda23af69179377c62d84a176fb12caff6c5cbf6ae9e5957ff3b1afe0220768edead76819228dcba18cca3c9a5a5d4c32919720f21df21a297ba375bbe5c01 03371ea5a4dfe356b3ea4042a537d7ab7ee0faabd43e21b6cc076fda2240629eee', prevTxId: 'ba2f7e668b571bf5080b7c274e6358226f6e16745c2a2e72dbfbcf63828a2d7b', sequence: 4294967294, outputIndex : 0 } ], outputs: [ { spentTxId: '9a213b879da9073a9a30606f9046f35f36f268cbf03f6242993a97c4c07c00b9', spentIndex: 1, spentHeight: 200, satoshis: 1940000, script: '76a9148e451eec7ca0a1764b4ab119274efdd2727b3c8588ac', scriptAsm: 'OP_DUP OP_HASH160 8e451eec7ca0a1764b4ab119274efdd2727b3c85 OP_EQUALVERIFY OP_CHECKSIG', address: 'mtVD3tdifBNujYzZ5N7PgXfKk4Bc85tDKA' }, { spentTxId: '418d3eb60275957b3456b96902e908abf962e71be4c4f09486564254664951bc', spentIndex: 34, spentHeight: 200, script: '76a914d0fce8f064cd1059a6a11501dd66fe42368572b088ac', scriptAsm: 'OP_DUP OP_HASH160 d0fce8f064cd1059a6a11501dd66fe42368572b0 OP_EQUALVERIFY OP_CHECKSIG', address: 'mzZypShcs1B35udnkqeYeJy8rUdgHDDvKG', satoshis: 1000000 } ] } }; var node = { getBlockOverview: sinon.stub().callsArgWith(1, null, blockOverview), getDetailedTransaction: function(txid, callback) { callback(null, transactionDetails[txid]); }, services: { bitcoind: { height: 534209 } }, network: 'testnet' }; var transactions = new TxController(node); var insight = { 'pagesTotal': 1, 'txs': [ { 'txid': '25a988e54b02e0e5df146a0f8fa7b9db56210533a9f04bdfda5f4ceb6f77aadd', 'version': 1, 'locktime': 0, 'vin': [ { 'coinbase': '03d6250800feb0aae355fe263600000963676d696e6572343208ae5800000000000000', 'sequence': 4294967295, 'n': 0 } ], 'vout': [ { 'value': '12.50040000', 'n': 0, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 68bedce8982d25c3b6b03f6238cbad00378b8ead OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a91468bedce8982d25c3b6b03f6238cbad00378b8ead88ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mq4oDPjmNWnBxbzx7qouzhpCSTMePUtYDF' ] }, 'spentTxId': null, 'spentIndex': null, 'spentHeight': null } ], 'blockhash': '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', 'blockheight': 533974, 'confirmations': 236, 'time': 1440987503, 'blocktime': 1440987503, 'isCoinBase': true, 'valueOut': 12.5004, 'size': 120 }, { 'txid': 'b85334bf2df35c6dd5b294efe92ffc793a78edff75a2ca666fc296ffb04bbba0', 'version': 1, 'locktime': 0, 'vin': [ { 'txid': '87c9b0f27571fff14b8c2d69e55614eacedd0f59fcc490b721320f9dae145aad', 'vout': 0, 'scriptSig': { 'asm': '30450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c01 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', 'hex': '4830450221008e5df62719cd92d7b137d00bbd27f153f2909bcad3a300960bc1020ec6d5e961022039df51600ff4fb5da5a794d1648c6b47c1f7d277fd5877fb5e52a730a3595f8c014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307' }, 'sequence': 4294967295, 'n': 0, 'addr': 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', 'valueSat': 18535505, 'value': 0.18535505, 'doubleSpentTxID': null }, { 'txid': 'd8a10aaedf3dd33b5ddf8979273f3dbf61e4638d1aa6a93c59ea22bc65ac2196', 'vout': 0, 'scriptSig': { 'asm': '30440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb3101 04eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307', 'hex': '4730440220761464d7bab9515d92260762a97af82a9b25d202d8f7197b1aaec81b6fed541f022059f99606de6b06e17b2cd102dceb3807ebdd9e777a5b77c9a0b3672f5eabcb31014104eb1e0ccd9afcac42229348dd776e991c69551ae3474340fada12e787e51758397e1d3afdba360d6374261125ea3b6ea079a5f202c150dfd729e1062d9176a307' }, 'sequence': 4294967295, 'n': 1, 'addr': 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f', 'valueSat': 16419885, 'value': 0.16419885, 'doubleSpentTxID': null } ], 'vout': [ { 'value': '0.21247964', 'n': 0, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 4b7b335f978f130269fe661423258ae9642df8a1 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9144b7b335f978f130269fe661423258ae9642df8a188ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mnQ4ZaGessNgdxmWPxbTHcfx4b8R6eUr1X' ] }, 'spentTxId': null, 'spentIndex': null, 'spentHeight': null }, { 'value': '0.13677426', 'n': 1, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 6efcf883b4b6f9997be9a0600f6c095fe2bd2d92 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9146efcf883b4b6f9997be9a0600f6c095fe2bd2d9288ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f' ] }, 'spentTxId': '614fe1708825f9c21732394e4784cc6808ac1d8b939736bfdead970567561eec', 'spentIndex': 1, 'spentHeight': 200, 'spentTs': 1440997099 } ], 'blockhash': '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', 'blockheight': 533974, 'confirmations': 236, 'time': 1440987503, 'blocktime': 1440987503, 'valueOut': 0.3492539, 'size': 437, 'valueIn': 0.3495539, 'fees': 0.0003 }, { 'txid': '2e01c7a4a0e335112236b711c4aaddd02e8dc59ba2cda416e8f80ff06dddd7e1', 'version': 1, 'locktime': 533963, 'vin': [ { 'txid': '7127225e5b89eb288144c76fe907970c1963ea0f0108295ee8ffb7dfb63c0d06', 'vout': 3, 'scriptSig': { 'asm': '3045022100f67cffc0ae23adb236ff3edb4a9736e277605db30cc7708dfab8cf1e1483bbce022052396aa5d664ec1cb65992c423fd9a17e94dc7af328d2d559e90746dd195ca5901 0346134da14907581d8190d3980caaf46d95e4eb9c1ca8e70f1fc6007fefb1909d', 'hex': '483045022100f67cffc0ae23adb236ff3edb4a9736e277605db30cc7708dfab8cf1e1483bbce022052396aa5d664ec1cb65992c423fd9a17e94dc7af328d2d559e90746dd195ca5901210346134da14907581d8190d3980caaf46d95e4eb9c1ca8e70f1fc6007fefb1909d' }, 'sequence': 4294967294, 'n': 0, 'addr': 'mgZK8zpudWoAaAwpLQSgc9t9PJJyEBpBdJ', 'valueSat': 990000, 'value': 0.0099, 'doubleSpentTxID': null }, { 'txid': 'ba2f7e668b571bf5080b7c274e6358226f6e16745c2a2e72dbfbcf63828a2d7b', 'vout': 0, 'scriptSig': { 'asm': '3044022077222a91cda23af69179377c62d84a176fb12caff6c5cbf6ae9e5957ff3b1afe0220768edead76819228dcba18cca3c9a5a5d4c32919720f21df21a297ba375bbe5c01 03371ea5a4dfe356b3ea4042a537d7ab7ee0faabd43e21b6cc076fda2240629eee', 'hex': '473044022077222a91cda23af69179377c62d84a176fb12caff6c5cbf6ae9e5957ff3b1afe0220768edead76819228dcba18cca3c9a5a5d4c32919720f21df21a297ba375bbe5c012103371ea5a4dfe356b3ea4042a537d7ab7ee0faabd43e21b6cc076fda2240629eee' }, 'sequence': 4294967294, 'n': 1, 'addr': 'n4oM7bPuC4ZPdCEDvtw9xGYQC7jmi5S6F4', 'valueSat': 1960000, 'value': 0.0196, 'doubleSpentTxID': null } ], 'vout': [ { 'value': '0.01940000', 'n': 0, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 8e451eec7ca0a1764b4ab119274efdd2727b3c85 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9148e451eec7ca0a1764b4ab119274efdd2727b3c8588ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mtVD3tdifBNujYzZ5N7PgXfKk4Bc85tDKA' ] }, 'spentTxId': '9a213b879da9073a9a30606f9046f35f36f268cbf03f6242993a97c4c07c00b9', 'spentIndex': 1, 'spentHeight': 200, 'spentTs': 1440992946 }, { 'value': '0.01000000', 'n': 1, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 d0fce8f064cd1059a6a11501dd66fe42368572b0 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a914d0fce8f064cd1059a6a11501dd66fe42368572b088ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mzZypShcs1B35udnkqeYeJy8rUdgHDDvKG' ] }, 'spentTxId': '418d3eb60275957b3456b96902e908abf962e71be4c4f09486564254664951bc', 'spentIndex': 34, 'spentHeight': 200, 'spentTs': 1440999118 } ], 'blockhash': '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7', 'blockheight': 533974, 'confirmations': 236, 'time': 1440987503, 'blocktime': 1440987503, 'valueOut': 0.0294, 'size': 373, 'valueIn': 0.0295, 'fees': 0.0001 } ] }; var todos = { txs: [ { vout: [ { scriptPubKey: { reqSigs: 1 } } ] }, { vin: [ ], vout: [ { scriptPubKey: { reqSigs: 1 } }, { scriptPubKey: { reqSigs: 1 }, spentTs: 1440997099 } ] }, { vin: [ ], vout: [ { scriptPubKey: { reqSigs: 1 }, spentTs: 1440992946 }, { scriptPubKey: { reqSigs: 1 }, spentTs: 1440999118 } ] } ] }; var req = { query: { block: '0000000000000afa0c3c0afd450c793a1e300ec84cbe9555166e06132f19a8f7' } }; var res = { jsonp: function(data) { _.merge(data, todos); should(data).eql(insight); done(); } }; transactions.list(req, res); }); it('by address', function(done) { var txinfos = [ { tx: { hex: '010000000125c46caa6d839435b43c20d6d48978e677841244b37a09f6f6cd29bfaf5b5eea010000006b483045022100f4d169783bef70e3943d2a617cce55d9fe4e33fc6f9880b8277265e2f619a97002201238648abcdf52960500664e969046d41755f7fc371971ebc78002fc418465a6012103acdcd31d51272403ce0829447e59e2ac9e08ed0bf92011cbf7420addf24534e6feffffff02a913dda5000000001976a9143583efb5e64a4668c6c54bb5fcc30af4417b4f2d88ac809fd500000000001976a9149713201957f42379e574d7c70d506ee49c2c8ad688ac49260800', hash: 'bb0ec3b96209fac9529570ea6f83a86af2cceedde4aaf2bfcc4796680d23f1c7', version: 1, inputs: [ { prevTxId: 'ea5e5bafbf29cdf6f6097ab344128477e67889d4d6203cb43594836daa6cc425', outputIndex: 1, sequence: 4294967294, script: '483045022100f4d169783bef70e3943d2a617cce55d9fe4e33fc6f9880b8277265e2f619a97002201238648abcdf52960500664e969046d41755f7fc371971ebc78002fc418465a6012103acdcd31d51272403ce0829447e59e2ac9e08ed0bf92011cbf7420addf24534e6', scriptAsm: '3045022100f4d169783bef70e3943d2a617cce55d9fe4e33fc6f9880b8277265e2f619a97002201238648abcdf52960500664e969046d41755f7fc371971ebc78002fc418465a601 03acdcd31d51272403ce0829447e59e2ac9e08ed0bf92011cbf7420addf24534e6', satoshis: 2796764565, address: 'msyjRQQ88MabQmyafpKCjBHUwuJ49tVjcb' } ], outputs: [ { satoshis: 2782729129, address: 'mkPvAKZ2rar6qeG3KjBtJHHMSP1wFZH7Er', script: '76a9143583efb5e64a4668c6c54bb5fcc30af4417b4f2d88ac', scriptAsm: 'OP_DUP OP_HASH160 3583efb5e64a4668c6c54bb5fcc30af4417b4f2d OP_EQUALVERIFY OP_CHECKSIG' }, { satoshis: 14000000, address: 'muHmEsjhjmATf9i3T9gHyeQoce9LXe2dWz', script: '76a9149713201957f42379e574d7c70d506ee49c2c8ad688ac', scriptAsm: 'OP_DUP OP_HASH160 9713201957f42379e574d7c70d506ee49c2c8ad6 OP_EQUALVERIFY OP_CHECKSIG' } ], inputSatoshis: 2796764565, outputSatoshis: 2796729129, feeSatoshis: 35436, locktime: 534089 } }, { tx: { hex: '0100000001c7f1230d689647ccbff2aae4ddeeccf26aa8836fea709552c9fa0962b9c30ebb000000006a47304402201ee69281db6b95bb1aa3074059b67581635b719e8f64e4c2694db6ec56ad9447022011e91528996ea459b1fb2c0b59363fecbefe4bc2ca90f7b2382bdaa358f2d5640121034cc057b12a68ee79df998004b9a1341bbb18b17ea4939bebaa3bac001e940f24feffffff02bce0c9a4000000001976a91456e446bc3489543d8324c6d0271524c0bd0506dd88ac80a81201000000001976a914011d2963b619186a318f768dddfd98cd553912a088ac53260800', hash: '01f700df84c466f2a389440e5eeacdc47d04f380c39e5d19dce2ce91a11ecba3', version: 1, inputs: [ { prevTxId: 'bb0ec3b96209fac9529570ea6f83a86af2cceedde4aaf2bfcc4796680d23f1c7', outputIndex: 0, sequence: 4294967294, script: '47304402201ee69281db6b95bb1aa3074059b67581635b719e8f64e4c2694db6ec56ad9447022011e91528996ea459b1fb2c0b59363fecbefe4bc2ca90f7b2382bdaa358f2d5640121034cc057b12a68ee79df998004b9a1341bbb18b17ea4939bebaa3bac001e940f24', scriptAsm: '304402201ee69281db6b95bb1aa3074059b67581635b719e8f64e4c2694db6ec56ad9447022011e91528996ea459b1fb2c0b59363fecbefe4bc2ca90f7b2382bdaa358f2d56401 034cc057b12a68ee79df998004b9a1341bbb18b17ea4939bebaa3bac001e940f24', satoshis: 2782729129, address: 'mkPvAKZ2rar6qeG3KjBtJHHMSP1wFZH7Er' } ], outputs: [ { satoshis: 2764693692, address: 'moSPsU4p2C2gssiniJ1JNH4fB9xs633tLv', script: '76a91456e446bc3489543d8324c6d0271524c0bd0506dd88ac', scriptAsm: 'OP_DUP OP_HASH160 56e446bc3489543d8324c6d0271524c0bd0506dd OP_EQUALVERIFY OP_CHECKSIG' }, { satoshis: 18000000, scriptAsm: 'OP_DUP OP_HASH160 011d2963b619186a318f768dddfd98cd553912a0 OP_EQUALVERIFY OP_CHECKSIG', script: '76a914011d2963b619186a318f768dddfd98cd553912a088ac', address: 'mfcquSAitCkUKXaYRZTRZQDfUegnL3kDew', spentTxId: '71a9e60c0341c9c258367f1a6d4253276f16e207bf84f41ff7412d8958a81bed' } ], inputSatoshis: 2782729129, outputSatoshis: 2782693692, feeSatoshis: 35437, locktime: 534099 } } ]; var historyResult = { totalCount: txinfos.length, items: txinfos }; txinfos[0].tx.blockHash = '00000000000001001aba15de213648f370607fb048288dd27b96f7e833a73520'; txinfos[0].tx.blockTimestamp = 1441068774; txinfos[0].tx.height = 534105; txinfos[1].tx.blockHash = '0000000000000a3acc1f7fe72917eb48bb319ed96c125a6dfcc0ba6acab3c4d0'; txinfos[1].tx.blockTimestamp = 1441072817; txinfos[1].tx.height = 534110; txinfos[0].tx.outputs[0].spentTxId = '01f700df84c466f2a389440e5eeacdc47d04f380c39e5d19dce2ce91a11ecba3'; txinfos[0].tx.outputs[0].spentIndex = 0; txinfos[0].tx.outputs[0].spentHeight = 199; txinfos[1].tx.outputs[0].spentTxId = '661194e5533a395ce9076f292b7e0fb28fe94cd8832a81b4aa0517ff58c1ddd2'; txinfos[1].tx.outputs[0].spentIndex = 0; txinfos[1].tx.outputs[0].spentHeight = 134; txinfos[1].tx.outputs[1].spentTxId = '71a9e60c0341c9c258367f1a6d4253276f16e207bf84f41ff7412d8958a81bed'; txinfos[1].tx.outputs[1].spentIndex = 0; txinfos[1].tx.outputs[1].spentHeight = 112; var node = { getAddressHistory: sinon.stub().callsArgWith(2, null, historyResult), services: { bitcoind: { height: 534223 } }, network: 'testnet' }; var insight = { 'pagesTotal': 1, 'txs': [ { 'txid': 'bb0ec3b96209fac9529570ea6f83a86af2cceedde4aaf2bfcc4796680d23f1c7', 'version': 1, 'locktime': 534089, 'vin': [ { 'txid': 'ea5e5bafbf29cdf6f6097ab344128477e67889d4d6203cb43594836daa6cc425', 'vout': 1, 'scriptSig': { 'asm': '3045022100f4d169783bef70e3943d2a617cce55d9fe4e33fc6f9880b8277265e2f619a97002201238648abcdf52960500664e969046d41755f7fc371971ebc78002fc418465a601 03acdcd31d51272403ce0829447e59e2ac9e08ed0bf92011cbf7420addf24534e6', 'hex': '483045022100f4d169783bef70e3943d2a617cce55d9fe4e33fc6f9880b8277265e2f619a97002201238648abcdf52960500664e969046d41755f7fc371971ebc78002fc418465a6012103acdcd31d51272403ce0829447e59e2ac9e08ed0bf92011cbf7420addf24534e6' }, 'sequence': 4294967294, 'n': 0, 'addr': 'msyjRQQ88MabQmyafpKCjBHUwuJ49tVjcb', 'valueSat': 2796764565, 'value': 27.96764565, 'doubleSpentTxID': null } ], 'vout': [ { 'value': '27.82729129', 'n': 0, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 3583efb5e64a4668c6c54bb5fcc30af4417b4f2d OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9143583efb5e64a4668c6c54bb5fcc30af4417b4f2d88ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mkPvAKZ2rar6qeG3KjBtJHHMSP1wFZH7Er' ] }, 'spentTxId': '01f700df84c466f2a389440e5eeacdc47d04f380c39e5d19dce2ce91a11ecba3', 'spentIndex': 0, 'spentHeight': 199, 'spentTs': 1441072817 }, { 'value': '0.14000000', 'n': 1, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 9713201957f42379e574d7c70d506ee49c2c8ad6 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9149713201957f42379e574d7c70d506ee49c2c8ad688ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'muHmEsjhjmATf9i3T9gHyeQoce9LXe2dWz' ] }, 'spentTxId': null, 'spentIndex': null, 'spentHeight': null } ], 'blockhash': '00000000000001001aba15de213648f370607fb048288dd27b96f7e833a73520', 'blockheight': 534105, 'confirmations': 119, 'time': 1441068774, 'blocktime': 1441068774, 'valueOut': 27.96729129, 'size': 226, 'valueIn': 27.96764565, 'fees': 0.00035436 }, { 'txid': '01f700df84c466f2a389440e5eeacdc47d04f380c39e5d19dce2ce91a11ecba3', 'version': 1, 'locktime': 534099, 'vin': [ { 'txid': 'bb0ec3b96209fac9529570ea6f83a86af2cceedde4aaf2bfcc4796680d23f1c7', 'vout': 0, 'scriptSig': { 'asm': '304402201ee69281db6b95bb1aa3074059b67581635b719e8f64e4c2694db6ec56ad9447022011e91528996ea459b1fb2c0b59363fecbefe4bc2ca90f7b2382bdaa358f2d56401 034cc057b12a68ee79df998004b9a1341bbb18b17ea4939bebaa3bac001e940f24', 'hex': '47304402201ee69281db6b95bb1aa3074059b67581635b719e8f64e4c2694db6ec56ad9447022011e91528996ea459b1fb2c0b59363fecbefe4bc2ca90f7b2382bdaa358f2d5640121034cc057b12a68ee79df998004b9a1341bbb18b17ea4939bebaa3bac001e940f24' }, 'sequence': 4294967294, 'n': 0, 'addr': 'mkPvAKZ2rar6qeG3KjBtJHHMSP1wFZH7Er', 'valueSat': 2782729129, 'value': 27.82729129, 'doubleSpentTxID': null } ], 'vout': [ { 'value': '27.64693692', 'n': 0, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 56e446bc3489543d8324c6d0271524c0bd0506dd OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a91456e446bc3489543d8324c6d0271524c0bd0506dd88ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'moSPsU4p2C2gssiniJ1JNH4fB9xs633tLv' ] }, 'spentTxId': '661194e5533a395ce9076f292b7e0fb28fe94cd8832a81b4aa0517ff58c1ddd2', 'spentIndex': 0, 'spentHeight': 134, 'spentTs': 1441077236 }, { 'value': '0.18000000', 'n': 1, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 011d2963b619186a318f768dddfd98cd553912a0 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a914011d2963b619186a318f768dddfd98cd553912a088ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': [ 'mfcquSAitCkUKXaYRZTRZQDfUegnL3kDew' ] }, 'spentTxId': '71a9e60c0341c9c258367f1a6d4253276f16e207bf84f41ff7412d8958a81bed', 'spentIndex': 0, 'spentHeight': 112, 'spentTs': 1441069523 } ], 'blockhash': '0000000000000a3acc1f7fe72917eb48bb319ed96c125a6dfcc0ba6acab3c4d0', 'blockheight': 534110, 'confirmations': 114, 'time': 1441072817, 'blocktime': 1441072817, 'valueOut': 27.82693692, 'size': 225, 'valueIn': 27.82729129, 'fees': 0.00035437 } ] }; var todos = { 'txs': [ { 'vin': [ ], 'vout': [ { 'scriptPubKey': { 'reqSigs': 1 }, 'spentTs': 1441072817 }, { 'scriptPubKey': { 'reqSigs': 1 } } ] }, { 'vin': [ ], 'vout': [ { 'scriptPubKey': { 'reqSigs': 1 }, 'spentTs': 1441077236 }, { 'scriptPubKey': { 'reqSigs': 1 }, 'spentTs': 1441069523 } ] } ] }; var req = { query: { address: 'mkPvAKZ2rar6qeG3KjBtJHHMSP1wFZH7Er' } }; var res = { jsonp: function(data) { var merged = _.merge(data, todos); should(merged).eql(insight); done(); } }; var transactions = new TxController(node); transactions.list(req, res); }); }); describe('/rawtx/:txid', function() { it('should give the correct data', function(done) { var hex = '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2303d6250800feb0aae355fe263600000963676d696e6572343208ae5800000000000000ffffffff01c018824a000000001976a91468bedce8982d25c3b6b03f6238cbad00378b8ead88ac00000000'; var node = { getTransaction: sinon.stub().callsArgWith(1, null, bitcore.Transaction().fromBuffer(new Buffer(hex, 'hex'))) }; var transactions = new TxController(node); var res = {}; var req = { params: { txid: txid } }; var next = function() { should(req.rawTransaction.rawtx).eql(hex); done(); }; var txid = '25a988e54b02e0e5df146a0f8fa7b9db56210533a9f04bdfda5f4ceb6f77aadd'; transactions.rawTransaction(req, res, next); }); }); describe('#transformInvTransaction', function() { it('should give the correct data', function() { var insight = { 'txid': 'a15a7c257af596704390d345ff3ea2eed4cd02ce8bfb8afb700bff82257e49fb', 'valueOut': 0.02038504, 'vout': [ { '3DQYCLG6rZdtV2Xw8y4YtozZjNHYoKsLuo': 45000 }, { '12WvZmssxT85f81dD6wcmWznxbnFkEpNMS': 1993504 } ], 'isRBF': false }; var rawTx = '01000000011760bc271a397bfb65b7506d430d96ebb1faff467ed957516238a9670e806a86010000006b483045022100f0056ae68a34cdb4194d424bd727c18f82653bca2a198e0d55ab6b4ee88bbdb902202a5745af4f72a5dbdca1e3d683af4667728a8b20e8001e0f8308a4d329ce3f96012102f3af6e66b61c9d99c74d9a9c3c1bec014a8c05d28bf339c8f5f395b5ce319e7dffffffff02c8af00000000000017a9148083b541ea15f1d18c5ca5e1fd47f9035cce24ed87206b1e00000000001976a91410a0e70cd91a45e0e6e409e227ab285bd61592b188ac00000000'; var tx = bitcore.Transaction().fromBuffer(new Buffer(rawTx, 'hex')); var node = { network: bitcore.Networks.livenet }; var transactions = new TxController(node); var result = transactions.transformInvTransaction(tx); should(result).eql(insight); }); it('will not include null values in vout array', function() { var insight = { 'txid': '716d54157c31e52c820494c6c2b8af1b64352049f4dcc80632aa15742a7f82c4', 'valueOut': 12.5002, 'vout': [ { 'n4eY3qiP9pi32MWC6FcJFHciSsfNiYFYgR': 12.5002 * 1e8 } ], 'isRBF': false }; var rawTx = '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0403ebc108ffffffff04a0ca814a000000001976a914fdb9fb622b0db8d9121475a983288a0876f4de4888ac0000000000000000226a200000000000000000000000000000000000000000000000000000ffff0000000000000000000000001b6a1976a914fdb9fb622b0db8d9121475a983288a0876f4de4888ac0000000000000000326a303a791c8e85200500d89769b4f958e4db6b3ec388ddaa30233c4517d942d440c24ae903bff40d97ca06465fcf2714000000000000'; var tx = bitcore.Transaction().fromBuffer(new Buffer(rawTx, 'hex')); var node = { network: bitcore.Networks.testnet }; var transactions = new TxController(node); var result = transactions.transformInvTransaction(tx); should(result).eql(insight); }); it('should detect RBF txs', function() { var testCases = [ { rawTx: '01000000017fa897c3556271c34cb28c03c196c2d912093264c9d293cb4980a2635474467d010000000f5355540b6f93598893578893588851ffffffff01501e0000000000001976a914aa2482ce71d219018ef334f6cc551ee88abd920888ac00000000', expected: false, }, { rawTx: '01000000017fa897c3556271c34cb28c03c196c2d912093264c9d293cb4980a2635474467d010000000f5355540b6f935988935788935888510000000001501e0000000000001976a914aa2482ce71d219018ef334f6cc551ee88abd920888ac00000000', expected: true, }, ]; var node = { network: bitcore.Networks.livenet }; var transactions = new TxController(node); _.each(testCases, function(tc) { var tx = bitcore.Transaction().fromBuffer(new Buffer(tc.rawTx, 'hex')); var result = transactions.transformInvTransaction(tx); should.exist(result.isRBF); result.isRBF.should.equal(tc.expected); }); }); }); });
import ray.cloudpickle as cloudpickle import copy from datetime import datetime import logging import shutil import uuid import time import tempfile import os from numbers import Number from ray.tune import TuneError from ray.tune.checkpoint_manager import Checkpoint, CheckpointManager from ray.tune.durable_trainable import DurableTrainable from ray.tune.logger import pretty_print, UnifiedLogger # NOTE(rkn): We import ray.tune.registry here instead of importing the names we # need because there are cyclic imports that may cause specific names to not # have been defined yet. See https://github.com/ray-project/ray/issues/1716. from ray.tune.registry import get_trainable_cls, validate_trainable from ray.tune.result import DEFAULT_RESULTS_DIR, DONE, TRAINING_ITERATION from ray.tune.resources import Resources, json_to_resources, resources_to_json from ray.tune.trainable import TrainableUtil from ray.tune.utils import flatten_dict from ray.utils import binary_to_hex, hex_to_binary DEBUG_PRINT_INTERVAL = 5 MAX_LEN_IDENTIFIER = int(os.environ.get("MAX_LEN_IDENTIFIER", 130)) logger = logging.getLogger(__name__) def date_str(): return datetime.today().strftime("%Y-%m-%d_%H-%M-%S") class Location: """Describes the location at which Trial is placed to run.""" def __init__(self, hostname=None, pid=None): self.hostname = hostname self.pid = pid def __str__(self): if not self.pid: return "" elif self.hostname == os.uname()[1]: return "pid={}".format(self.pid) else: return "{}:{}".format(self.hostname, self.pid) class ExportFormat: """Describes the format to export the trial Trainable. This may correspond to different file formats based on the Trainable implementation. """ CHECKPOINT = "checkpoint" MODEL = "model" @staticmethod def validate(export_formats): """Validates export_formats. Raises: ValueError if the format is unknown. """ for i in range(len(export_formats)): export_formats[i] = export_formats[i].strip().lower() if export_formats[i] not in [ ExportFormat.CHECKPOINT, ExportFormat.MODEL ]: raise TuneError("Unsupported export format: " + export_formats[i]) def checkpoint_deleter(trial_id, runner): """Returns a checkpoint deleter callback for a runner.""" if not runner: return lambda checkpoint: None def delete(checkpoint): """Requests checkpoint deletion asynchronously. Args: checkpoint (Checkpoint): Checkpoint to delete. """ if checkpoint.storage == Checkpoint.PERSISTENT and checkpoint.value: logger.debug("Trial %s: Deleting checkpoint %s", trial_id, checkpoint.value) checkpoint_path = checkpoint.value # Delete local copy, if any exists. if os.path.exists(checkpoint_path): try: checkpoint_dir = TrainableUtil.find_checkpoint_dir( checkpoint_path) shutil.rmtree(checkpoint_dir) except FileNotFoundError: logger.warning("Checkpoint dir not found during deletion.") # TODO(ujvl): Batch remote deletes. runner.delete_checkpoint.remote(checkpoint.value) return delete class Trial: """A trial object holds the state for one model training run. Trials are themselves managed by the TrialRunner class, which implements the event loop for submitting trial runs to a Ray cluster. Trials start in the PENDING state, and transition to RUNNING once started. On error it transitions to ERROR, otherwise TERMINATED on success. """ PENDING = "PENDING" RUNNING = "RUNNING" PAUSED = "PAUSED" TERMINATED = "TERMINATED" ERROR = "ERROR" def __init__(self, trainable_name, config=None, trial_id=None, local_dir=DEFAULT_RESULTS_DIR, evaluated_params=None, experiment_tag="", resources=None, stopping_criterion=None, remote_checkpoint_dir=None, checkpoint_freq=0, checkpoint_at_end=False, sync_on_checkpoint=True, keep_checkpoints_num=None, checkpoint_score_attr=TRAINING_ITERATION, export_formats=None, restore_path=None, trial_name_creator=None, loggers=None, sync_to_driver_fn=None, max_failures=0): """Initialize a new trial. The args here take the same meaning as the command line flags defined in ray.tune.config_parser. """ validate_trainable(trainable_name) # Trial config self.trainable_name = trainable_name self.trial_id = Trial.generate_id() if trial_id is None else trial_id self.config = config or {} self.local_dir = local_dir # This remains unexpanded for syncing. #: Parameters that Tune varies across searches. self.evaluated_params = evaluated_params or {} self.experiment_tag = experiment_tag trainable_cls = self.get_trainable_cls() if trainable_cls and hasattr(trainable_cls, "default_resource_request"): default_resources = trainable_cls.default_resource_request( self.config) if default_resources: if resources: raise ValueError( "Resources for {} have been automatically set to {} " "by its `default_resource_request()` method. Please " "clear the `resources_per_trial` option.".format( trainable_cls, default_resources)) resources = default_resources self.location = Location() self.resources = resources or Resources(cpu=1, gpu=0) self.stopping_criterion = stopping_criterion or {} self.loggers = loggers self.sync_to_driver_fn = sync_to_driver_fn self.verbose = True self.max_failures = max_failures # Local trial state that is updated during the run self.last_result = {} self.last_update_time = -float("inf") # stores in memory max/min/last result for each metric by trial self.metric_analysis = {} self.export_formats = export_formats self.status = Trial.PENDING self.start_time = None self.logdir = None self.runner = None self.result_logger = None self.last_debug = 0 self.error_file = None self.error_msg = None self.custom_trial_name = None # Checkpointing fields self.saving_to = None if remote_checkpoint_dir: self.remote_checkpoint_dir_prefix = remote_checkpoint_dir else: self.remote_checkpoint_dir_prefix = None self.checkpoint_freq = checkpoint_freq self.checkpoint_at_end = checkpoint_at_end self.sync_on_checkpoint = sync_on_checkpoint self.checkpoint_manager = CheckpointManager( keep_checkpoints_num, checkpoint_score_attr, checkpoint_deleter(self._trainable_name(), self.runner)) checkpoint = Checkpoint(Checkpoint.PERSISTENT, restore_path) self.checkpoint_manager.newest_persistent_checkpoint = checkpoint # Restoration fields self.restoring_from = None self.num_failures = 0 # AutoML fields self.results = None self.best_result = None self.param_config = None self.extra_arg = None self._nonjson_fields = [ "loggers", "sync_to_driver_fn", "results", "best_result", "param_config", "extra_arg", ] if trial_name_creator: self.custom_trial_name = trial_name_creator(self) @property def node_ip(self): return self.location.hostname @property def checkpoint(self): """Returns the most recent checkpoint. If the trial is PAUSED, this is the most recent MEMORY checkpoint. Otherwise, it is the most recent PERSISTENT checkpoint. """ if self.status == Trial.PAUSED: assert self.checkpoint_manager.newest_memory_checkpoint.value return self.checkpoint_manager.newest_memory_checkpoint else: return self.checkpoint_manager.newest_persistent_checkpoint @classmethod def generate_id(cls): return str(uuid.uuid1().hex)[:8] @property def remote_checkpoint_dir(self): assert self.logdir, "Trial {}: logdir not initialized.".format(self) if not self.remote_checkpoint_dir_prefix: return None logdir_name = os.path.basename(self.logdir) return os.path.join(self.remote_checkpoint_dir_prefix, logdir_name) @classmethod def create_logdir(cls, identifier, local_dir): local_dir = os.path.expanduser(local_dir) os.makedirs(local_dir, exist_ok=True) return tempfile.mkdtemp( prefix="{}_{}".format(identifier[:MAX_LEN_IDENTIFIER], date_str()), dir=local_dir) def init_logger(self): """Init logger.""" if not self.result_logger: if not self.logdir: self.logdir = Trial.create_logdir( self._trainable_name() + "_" + self.experiment_tag, self.local_dir) else: os.makedirs(self.logdir, exist_ok=True) self.result_logger = UnifiedLogger( self.config, self.logdir, trial=self, loggers=self.loggers, sync_function=self.sync_to_driver_fn) def update_resources(self, cpu, gpu, **kwargs): """EXPERIMENTAL: Updates the resource requirements. Should only be called when the trial is not running. Raises: ValueError if trial status is running. """ if self.status is Trial.RUNNING: raise ValueError("Cannot update resources while Trial is running.") self.resources = Resources(cpu, gpu, **kwargs) def set_runner(self, runner): self.runner = runner self.checkpoint_manager.delete = checkpoint_deleter( self._trainable_name(), runner) def set_location(self, location): """Sets the location of the trial.""" self.location = location def set_status(self, status): """Sets the status of the trial.""" self.status = status if status == Trial.RUNNING: if self.start_time is None: self.start_time = time.time() def close_logger(self): """Closes logger.""" if self.result_logger: self.result_logger.close() self.result_logger = None def write_error_log(self, error_msg): if error_msg and self.logdir: self.num_failures += 1 self.error_file = os.path.join(self.logdir, "error.txt") with open(self.error_file, "a+") as f: f.write("Failure # {} (occurred at {})\n".format( self.num_failures, date_str())) f.write(error_msg + "\n") self.error_msg = error_msg def should_stop(self, result): """Whether the given result meets this trial's stopping criteria.""" if result.get(DONE): return True for criteria, stop_value in self.stopping_criterion.items(): if criteria not in result: raise TuneError( "Stopping criteria {} not provided in result {}.".format( criteria, result)) elif isinstance(criteria, dict): raise ValueError( "Stopping criteria is now flattened by default. " "Use forward slashes to nest values `key1/key2/key3`.") elif result[criteria] >= stop_value: return True return False def should_checkpoint(self): """Whether this trial is due for checkpointing.""" result = self.last_result or {} if result.get(DONE) and self.checkpoint_at_end: return True return (self.checkpoint_freq and result.get(TRAINING_ITERATION, 0) % self.checkpoint_freq == 0) def has_checkpoint(self): return self.checkpoint.value is not None def clear_checkpoint(self): self.checkpoint.value = None self.restoring_from = None def on_checkpoint(self, checkpoint): """Hook for handling checkpoints taken by the Trainable. Args: checkpoint (Checkpoint): Checkpoint taken. """ if checkpoint.storage == Checkpoint.MEMORY: self.checkpoint_manager.on_checkpoint(checkpoint) return if self.sync_on_checkpoint: try: # Wait for any other syncs to finish. We need to sync again # after this to handle checkpoints taken mid-sync. self.result_logger.wait() except TuneError as e: # Errors occurring during this wait are not fatal for this # checkpoint, so it should just be logged. logger.error( "Trial %s: An error occurred during the " "checkpoint pre-sync wait - %s", self, str(e)) # Force sync down and wait before tracking the new checkpoint. try: if self.result_logger.sync_down(): self.result_logger.wait() else: logger.error( "Trial %s: Checkpoint sync skipped. " "This should not happen.", self) except TuneError as e: if issubclass(self.get_trainable_cls(), DurableTrainable): # Even though rsync failed the trainable can restore # from remote durable storage. logger.error("Trial %s: Sync error - %s", self, str(e)) else: # If the trainable didn't have remote storage to upload # to then this checkpoint may have been lost, so we # shouldn't track it with the checkpoint_manager. raise e if not issubclass(self.get_trainable_cls(), DurableTrainable): if not os.path.exists(checkpoint.value): raise TuneError("Trial {}: Checkpoint path {} not " "found after successful sync down.".format( self, checkpoint.value)) self.checkpoint_manager.on_checkpoint(checkpoint) def on_restore(self): """Handles restoration completion.""" assert self.is_restoring self.last_result = self.restoring_from.result self.restoring_from = None def should_recover(self): """Returns whether the trial qualifies for retrying. This is if the trial has not failed more than max_failures. Note this may return true even when there is no checkpoint, either because `self.checkpoint_freq` is `0` or because the trial failed before a checkpoint has been made. """ return self.num_failures < self.max_failures or self.max_failures < 0 def update_last_result(self, result, terminate=False): result.update(trial_id=self.trial_id, done=terminate) if self.experiment_tag: result.update(experiment_tag=self.experiment_tag) if self.verbose and (terminate or time.time() - self.last_debug > DEBUG_PRINT_INTERVAL): print("Result for {}:".format(self)) print(" {}".format(pretty_print(result).replace("\n", "\n "))) self.last_debug = time.time() self.set_location(Location(result.get("node_ip"), result.get("pid"))) self.last_result = result self.last_update_time = time.time() self.result_logger.on_result(self.last_result) for metric, value in flatten_dict(result).items(): if isinstance(value, Number): if metric not in self.metric_analysis: self.metric_analysis[metric] = { "max": value, "min": value, "last": value } else: self.metric_analysis[metric]["max"] = max( value, self.metric_analysis[metric]["max"]) self.metric_analysis[metric]["min"] = min( value, self.metric_analysis[metric]["min"]) self.metric_analysis[metric]["last"] = value def get_trainable_cls(self): return get_trainable_cls(self.trainable_name) def set_verbose(self, verbose): self.verbose = verbose def is_finished(self): return self.status in [Trial.ERROR, Trial.TERMINATED] @property def is_restoring(self): return self.restoring_from is not None @property def is_saving(self): return self.saving_to is not None def __repr__(self): return self._trainable_name(include_trial_id=True) def __str__(self): return self._trainable_name(include_trial_id=True) def _trainable_name(self, include_trial_id=False): """Combines ``env`` with ``trainable_name`` and ``trial_id``. Can be overridden with a custom string creator. """ if self.custom_trial_name: return self.custom_trial_name if "env" in self.config: env = self.config["env"] if isinstance(env, type): env = env.__name__ identifier = "{}_{}".format(self.trainable_name, env) else: identifier = self.trainable_name if include_trial_id: identifier += "_" + self.trial_id return identifier.replace("/", "_") def __getstate__(self): """Memento generator for Trial. Sets RUNNING trials to PENDING, and flushes the result logger. Note this can only occur if the trial holds a PERSISTENT checkpoint. """ assert self.checkpoint.storage == Checkpoint.PERSISTENT, ( "Checkpoint must not be in-memory.") state = self.__dict__.copy() state["resources"] = resources_to_json(self.resources) for key in self._nonjson_fields: state[key] = binary_to_hex(cloudpickle.dumps(state.get(key))) state["runner"] = None state["result_logger"] = None # Avoid waiting for events that will never occur on resume. state["resuming_from"] = None state["saving_to"] = None if self.result_logger: self.result_logger.flush(sync_down=False) state["__logger_started__"] = True else: state["__logger_started__"] = False return copy.deepcopy(state) def __setstate__(self, state): logger_started = state.pop("__logger_started__") state["resources"] = json_to_resources(state["resources"]) if state["status"] == Trial.RUNNING: state["status"] = Trial.PENDING for key in self._nonjson_fields: state[key] = cloudpickle.loads(hex_to_binary(state[key])) self.__dict__.update(state) validate_trainable(self.trainable_name) if logger_started: self.init_logger()
""" sdt.py: Scripted Display Tool (SDT3D) helper """ import logging import socket from typing import IO, TYPE_CHECKING, Dict, List, Optional, Set, Tuple from urllib.parse import urlparse from core.constants import CORE_CONF_DIR, CORE_DATA_DIR from core.emane.nodes import EmaneNet from core.emulator.data import LinkData, NodeData from core.emulator.enumerations import EventTypes, MessageFlags from core.errors import CoreError from core.nodes.base import CoreNetworkBase, NodeBase from core.nodes.network import WlanNode logger = logging.getLogger(__name__) if TYPE_CHECKING: from core.emulator.session import Session def get_link_id(node1_id: int, node2_id: int, network_id: int) -> str: link_id = f"{node1_id}-{node2_id}" if network_id is not None: link_id = f"{link_id}-{network_id}" return link_id CORE_LAYER: str = "CORE" NODE_LAYER: str = "CORE::Nodes" LINK_LAYER: str = "CORE::Links" WIRED_LINK_LAYER: str = f"{LINK_LAYER}::wired" CORE_LAYERS: List[str] = [CORE_LAYER, LINK_LAYER, NODE_LAYER, WIRED_LINK_LAYER] DEFAULT_LINK_COLOR: str = "red" class Sdt: """ Helper class for exporting session objects to NRL"s SDT3D. The connect() method initializes the display, and can be invoked when a node position or link has changed. """ DEFAULT_SDT_URL: str = "tcp://127.0.0.1:50000/" # default altitude (in meters) for flyto view DEFAULT_ALT: int = 2500 # TODO: read in user"s nodes.conf here; below are default node types from the GUI DEFAULT_SPRITES: Dict[str, str] = [ ("router", "router.gif"), ("host", "host.gif"), ("PC", "pc.gif"), ("mdr", "mdr.gif"), ("prouter", "router_green.gif"), ("hub", "hub.gif"), ("lanswitch", "lanswitch.gif"), ("wlan", "wlan.gif"), ("rj45", "rj45.gif"), ("tunnel", "tunnel.gif"), ] def __init__(self, session: "Session") -> None: """ Creates a Sdt instance. :param session: session this manager is tied to """ self.session: "Session" = session self.sock: Optional[IO] = None self.connected: bool = False self.url: str = self.DEFAULT_SDT_URL self.address: Optional[Tuple[Optional[str], Optional[int]]] = None self.protocol: Optional[str] = None self.network_layers: Set[str] = set() self.session.node_handlers.append(self.handle_node_update) self.session.link_handlers.append(self.handle_link_update) def is_enabled(self) -> bool: """ Check for "enablesdt" session option. Return False by default if the option is missing. :return: True if enabled, False otherwise """ return self.session.options.get_config("enablesdt") == "1" def seturl(self) -> None: """ Read "sdturl" from session options, or use the default value. Set self.url, self.address, self.protocol :return: nothing """ url = self.session.options.get_config("stdurl", default=self.DEFAULT_SDT_URL) self.url = urlparse(url) self.address = (self.url.hostname, self.url.port) self.protocol = self.url.scheme def connect(self) -> bool: """ Connect to the SDT address/port if enabled. :return: True if connected, False otherwise """ if not self.is_enabled(): return False if self.connected: return True if self.session.state == EventTypes.SHUTDOWN_STATE: return False self.seturl() logger.info("connecting to SDT at %s://%s", self.protocol, self.address) if self.sock is None: try: if self.protocol.lower() == "udp": self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.connect(self.address) else: # Default to tcp self.sock = socket.create_connection(self.address, 5) except IOError: logger.exception("SDT socket connect error") return False if not self.initialize(): return False self.connected = True # refresh all objects in SDT3D when connecting after session start if not self.sendobjs(): return False return True def initialize(self) -> bool: """ Load icon sprites, and fly to the reference point location on the virtual globe. :return: initialize command status """ if not self.cmd(f'path "{CORE_DATA_DIR}/icons/normal"'): return False # send node type to icon mappings for node_type, icon in self.DEFAULT_SPRITES: if not self.cmd(f"sprite {node_type} image {icon}"): return False lat, long = self.session.location.refgeo[:2] return self.cmd(f"flyto {long:.6f},{lat:.6f},{self.DEFAULT_ALT}") def disconnect(self) -> None: """ Disconnect from SDT. :return: nothing """ if self.sock: try: self.sock.close() except IOError: logger.error("error closing socket") finally: self.sock = None self.connected = False def shutdown(self) -> None: """ Invoked from Session.shutdown() and Session.checkshutdown(). :return: nothing """ self.cmd("clear all") for layer in self.network_layers: self.cmd(f"delete layer,{layer}") for layer in CORE_LAYERS[::-1]: self.cmd(f"delete layer,{layer}") self.disconnect() self.network_layers.clear() def cmd(self, cmdstr: str) -> bool: """ Send an SDT command over a UDP socket. socket.sendall() is used as opposed to socket.sendto() because an exception is raised when there is no socket listener. :param cmdstr: command to send :return: True if command was successful, False otherwise """ if self.sock is None: return False try: cmd = f"{cmdstr}\n".encode() logger.debug("sdt cmd: %s", cmd) self.sock.sendall(cmd) return True except IOError: logger.exception("SDT connection error") self.sock = None self.connected = False return False def sendobjs(self) -> None: """ Session has already started, and the SDT3D GUI later connects. Send all node and link objects for display. Otherwise, nodes and links will only be drawn when they have been updated (e.g. moved). :return: nothing """ nets = [] # create layers for layer in CORE_LAYERS: self.cmd(f"layer {layer}") with self.session.nodes_lock: for node_id in self.session.nodes: node = self.session.nodes[node_id] if isinstance(node, CoreNetworkBase): nets.append(node) if not isinstance(node, NodeBase): continue self.add_node(node) for net in nets: all_links = net.links(flags=MessageFlags.ADD) for link_data in all_links: is_wireless = isinstance(net, (WlanNode, EmaneNet)) if is_wireless and link_data.node1_id == net.id: continue self.handle_link_update(link_data) def get_node_position(self, node: NodeBase) -> Optional[str]: """ Convenience to generate an SDT position string, given a node. :param node: :return: """ x, y, z = node.position.get() if x is None or y is None: return None lat, lon, alt = self.session.location.getgeo(x, y, z) return f"pos {lon:.6f},{lat:.6f},{alt:.6f}" def add_node(self, node: NodeBase) -> None: """ Handle adding a node in SDT. :param node: node to add :return: nothing """ logger.debug("sdt add node: %s - %s", node.id, node.name) if not self.connect(): return pos = self.get_node_position(node) if not pos: return node_type = node.type if node_type is None: node_type = type(node).type icon = node.icon if icon: node_type = node.name icon = icon.replace("$CORE_DATA_DIR", str(CORE_DATA_DIR)) icon = icon.replace("$CORE_CONF_DIR", str(CORE_CONF_DIR)) self.cmd(f"sprite {node_type} image {icon}") self.cmd( f'node {node.id} nodeLayer "{NODE_LAYER}" ' f'type {node_type} label on,"{node.name}" {pos}' ) def edit_node(self, node: NodeBase, lon: float, lat: float, alt: float) -> None: """ Handle updating a node in SDT. :param node: node to update :param lon: node longitude :param lat: node latitude :param alt: node altitude :return: nothing """ logger.debug("sdt update node: %s - %s", node.id, node.name) if not self.connect(): return if all([lat is not None, lon is not None, alt is not None]): pos = f"pos {lon:.6f},{lat:.6f},{alt:.6f}" self.cmd(f"node {node.id} {pos}") else: pos = self.get_node_position(node) if not pos: return self.cmd(f"node {node.id} {pos}") def delete_node(self, node_id: int) -> None: """ Handle deleting a node in SDT. :param node_id: node id to delete :return: nothing """ logger.debug("sdt delete node: %s", node_id) if not self.connect(): return self.cmd(f"delete node,{node_id}") def handle_node_update(self, node_data: NodeData) -> None: """ Handler for node updates, specifically for updating their location. :param node_data: node data being updated :return: nothing """ if not self.connect(): return node = node_data.node logger.debug("sdt handle node update: %s - %s", node.id, node.name) if node_data.message_type == MessageFlags.DELETE: self.cmd(f"delete node,{node.id}") else: x, y, _ = node.position.get() lon, lat, alt = node.position.get_geo() if all([lat is not None, lon is not None, alt is not None]): pos = f"pos {lon:.6f},{lat:.6f},{alt:.6f}" self.cmd(f"node {node.id} {pos}") elif node_data.message_type == MessageFlags.NONE: lat, lon, alt = self.session.location.getgeo(x, y, 0) pos = f"pos {lon:.6f},{lat:.6f},{alt:.6f}" self.cmd(f"node {node.id} {pos}") def wireless_net_check(self, node_id: int) -> bool: """ Determines if a node is either a wireless node type. :param node_id: node id to check :return: True is a wireless node type, False otherwise """ result = False try: node = self.session.get_node(node_id, NodeBase) result = isinstance(node, (WlanNode, EmaneNet)) except CoreError: pass return result def add_link( self, node1_id: int, node2_id: int, network_id: int = None, label: str = None ) -> None: """ Handle adding a link in SDT. :param node1_id: node one id :param node2_id: node two id :param network_id: network link is associated with, None otherwise :param label: label for link :return: nothing """ logger.debug("sdt add link: %s, %s, %s", node1_id, node2_id, network_id) if not self.connect(): return if self.wireless_net_check(node1_id) or self.wireless_net_check(node2_id): return color = DEFAULT_LINK_COLOR if network_id: color = self.session.get_link_color(network_id) line = f"{color},2" link_id = get_link_id(node1_id, node2_id, network_id) if network_id: layer = self.get_network_layer(network_id) else: layer = WIRED_LINK_LAYER link_label = "" if label: link_label = f'linklabel on,"{label}"' self.cmd( f"link {node1_id},{node2_id},{link_id} linkLayer {layer} line {line} " f"{link_label}" ) def get_network_layer(self, network_id: int) -> str: node = self.session.nodes.get(network_id) if node: layer = f"{LINK_LAYER}::{node.name}" self.network_layers.add(layer) else: layer = WIRED_LINK_LAYER return layer def delete_link(self, node1_id: int, node2_id: int, network_id: int = None) -> None: """ Handle deleting a link in SDT. :param node1_id: node one id :param node2_id: node two id :param network_id: network link is associated with, None otherwise :return: nothing """ logger.debug("sdt delete link: %s, %s, %s", node1_id, node2_id, network_id) if not self.connect(): return if self.wireless_net_check(node1_id) or self.wireless_net_check(node2_id): return link_id = get_link_id(node1_id, node2_id, network_id) self.cmd(f"delete link,{node1_id},{node2_id},{link_id}") def edit_link( self, node1_id: int, node2_id: int, network_id: int, label: str ) -> None: """ Handle editing a link in SDT. :param node1_id: node one id :param node2_id: node two id :param network_id: network link is associated with, None otherwise :param label: label to update :return: nothing """ logger.debug("sdt edit link: %s, %s, %s", node1_id, node2_id, network_id) if not self.connect(): return if self.wireless_net_check(node1_id) or self.wireless_net_check(node2_id): return link_id = get_link_id(node1_id, node2_id, network_id) link_label = f'linklabel on,"{label}"' self.cmd(f"link {node1_id},{node2_id},{link_id} {link_label}") def handle_link_update(self, link_data: LinkData) -> None: """ Handle link broadcast messages and push changes to SDT. :param link_data: link data to handle :return: nothing """ node1_id = link_data.node1_id node2_id = link_data.node2_id network_id = link_data.network_id label = link_data.label if link_data.message_type == MessageFlags.ADD: self.add_link(node1_id, node2_id, network_id, label) elif link_data.message_type == MessageFlags.DELETE: self.delete_link(node1_id, node2_id, network_id) elif link_data.message_type == MessageFlags.NONE and label: self.edit_link(node1_id, node2_id, network_id, label)
import React from 'react' import { navigate } from 'gatsby-link' import Layout from '../../components/Layout' function encode(data) { return Object.keys(data) .map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])) .join('&') } export default class Index extends React.Component { constructor(props) { super(props) this.state = { isValidated: false } } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } handleSubmit = (e) => { e.preventDefault() const form = e.target fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: encode({ 'form-name': form.getAttribute('name'), ...this.state, }), }) .then(() => navigate(form.getAttribute('action'))) .catch((error) => alert(error)) } render() { return ( <Layout> <section className="section"> <div className="container"> <div className="content"> <h1>Contact</h1> <h4>...Yeah this form doesn't send us anything, but knock yourself out.</h4> <form name="contact" method="post" action="/contact/thanks/" data-netlify="true" data-netlify-honeypot="bot-field" onSubmit={this.handleSubmit} > {/* The `form-name` hidden field is required to support form submissions without JavaScript */} <input type="hidden" name="form-name" value="contact" /> <div hidden> <label> Don’t fill this out:{' '} <input name="bot-field" onChange={this.handleChange} /> </label> </div> <div className="field"> <label className="label" htmlFor={'name'}> Your name </label> <div className="control"> <input className="input" type={'text'} name={'name'} onChange={this.handleChange} id={'name'} required={true} /> </div> </div> <div className="field"> <label className="label" htmlFor={'email'}> Email </label> <div className="control"> <input className="input" type={'email'} name={'email'} onChange={this.handleChange} id={'email'} required={true} /> </div> </div> <div className="field"> <label className="label" htmlFor={'message'}> Message </label> <div className="control"> <textarea className="textarea" name={'message'} onChange={this.handleChange} id={'message'} required={true} /> </div> </div> <div className="field"> <button className="button is-link" type="submit"> Send </button> </div> </form> </div> </div> </section> </Layout> ) } }
(function() { "use strict"; var app = require("electron").app; var BrowserWindow = require("electron").BrowserWindow; var Menu = require("electron").Menu; var env = require("./env_config"); var devHelper = require("./dev_helper"); var windowStateKeeper = require("./window_state"); var fs = require("fs"); require("./electron_context_menu")({ prepend: (params, browserWindow) => [ { label: "RuDEX" } ] }); var mainWindow; // Preserver of the window size and position between app launches. var mainWindowState = windowStateKeeper("main", { width: 1000, height: 800 }); global.guid = mainWindowState.guid; // global.version = JSON.stringify(git.tag()); app.on("ready", function() { mainWindow = new BrowserWindow({ x: mainWindowState.x, y: mainWindowState.y, width: mainWindowState.width, height: mainWindowState.height }); if (mainWindowState.isMaximized) { mainWindow.maximize(); } mainWindow.loadURL("file://" + __dirname + "/index.html"); //if (env.name !== 'production') { //devHelper.setDevMenu(); //mainWindow.openDevTools(); //} mainWindow.on("close", function() { mainWindowState.saveState(mainWindow); }); mainWindow.webContents.on("new-window", function(e, url) { e.preventDefault(); require("electron").shell.openExternal(url); }); // Create the Application's main menu var app_menu = process.platform === "darwin" ? { label: "Application", submenu: [ { label: "About Application", selector: "orderFrontStandardAboutPanel:" }, {type: "separator"}, { label: "Quit", accelerator: "CmdOrCtrl+Q", click: function() { app.quit(); } } ] } : { label: "File", submenu: [ { label: "Quit", accelerator: "CmdOrCtrl+Q", click: function() { app.quit(); } } ] }; var template = [ app_menu, { label: "Edit", submenu: [ { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" }, {type: "separator"}, { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" }, { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" }, { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" }, { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" } ] }, { label: "View", submenu: [ { label: "Reload", accelerator: "CmdOrCtrl+R", click: function() { BrowserWindow.getFocusedWindow().reload(); } }, { label: "Toggle DevTools", accelerator: "Alt+CmdOrCtrl+I", click: function() { BrowserWindow.getFocusedWindow().toggleDevTools(); } } ] } ]; Menu.setApplicationMenu(Menu.buildFromTemplate(template)); }); app.on("window-all-closed", function() { app.quit(); }); })(); //# sourceMappingURL=background.js.map
'use strict'; module.exports = { responses: { myorg: { myrepo: { "data": { "repository": { "name": "myrepo", "url": "https://github.com/myorg/myrepo", "pullRequests": { "nodes": [ { "title": "Add README & LICENSE", "state": "MERGED", "id": "567", "number": 1, "url": "https://github.com/myorg/myrepo/pull/1", "bodyText": "", "createdAt": "2017-10-02T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-10-02T06:55:53Z", "closedAt": "2017-10-02T14:02:14Z", "mergedAt": "2017-10-02T14:02:14Z", "merged": true, "closed": true, "changedFiles": 2, "additions": 10, "deletions": 12, "author": { "login": "notabot", "url": "https://github.com/notabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-10-02T04:01:30Z", "message": "My commit", "author": { "user": { "login": "notabot", "url": "https://github.com/notabot" } } } } ] } }, ], "pageInfo": { "hasNextPage": false, "startCursor": "Y3Vyc29yOnYyOpHOBFTBQA==", "hasPreviousPage": false, "endCursor": "Y3Vyc29yOnYyOpHOBg+zyQ==" } } } } }, 'my-better-repo': { "data": { "repository": { "name": "my-better-repo", "url": "https://github.com/myorg/my-better-repo", "pullRequests": { "nodes": [ { "title": "Add README & LICENSE", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-better-repo/pull/1", "bodyText": "", "createdAt": "2017-10-02T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-10-02T06:55:53Z", "closedAt": "2017-10-02T14:02:14Z", "mergedAt": "2017-10-02T14:02:14Z", "merged": true, "closed": true, "changedFiles": 3, "additions": 20, "deletions": 3, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-10-02T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-10-02T03:51:45Z", "message": "My cool commit #2", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-10-02T03:59:00Z", "message": "My cool commit #3", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } } ] } }, { "title": "Add README & LICENSE... again.", "state": "MERGED", "id": "4343", "number": 2, "url": "https://github.com/myorg/my-better-repo/pull/2", "bodyText": "", "createdAt": "2017-10-02T06:59:33Z", "lastEditedAt": null, "publishedAt": "2017-10-02T06:59:33Z", "closedAt": "2017-10-03T11:33:22Z", "mergedAt": "2017-10-03T11:33:22Z", "merged": true, "closed": true, "changedFiles": 7, "additions": 4, "deletions": 9, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-10-03T05:01:21Z", "message": "My bad commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-10-03T05:42:48Z", "message": "My awesome commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } } ] } }, ], "pageInfo": { "hasNextPage": false, "startCursor": "Y3Vyc29yOnYyOpHOBFTBQA==", "hasPreviousPage": false, "endCursor": "Y3Vyc29yOnYyOpHOBg+zyQ==" } } } } }, 'my-beta-repo': { "data": { "repository": { "name": "my-beta-repo", "url": "https://github.com/myorg/my-beta-repo", "pullRequests": { "nodes": [ { "title": "Add a Cool Feature", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/1", "bodyText": "", "createdAt": "2017-11-18T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-11-18T06:55:53Z", "closedAt": "2017-11-18T14:02:14Z", "mergedAt": "2017-11-18T14:02:14Z", "merged": true, "closed": true, "changedFiles": 30, "additions": 30, "deletions": 4, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-11-18T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-11-18T03:51:45Z", "message": "My cool commit #2", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-11-18T04:01:25Z", "message": "My cool commit #3", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-11-18T04:12:00Z", "message": "My cool commit #4", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } } ] } }, { "title": "Add a feature that we no longer wanted", "state": "CLOSED", "id": "4343", "number": 2, "url": "https://github.com/myorg/my-beta-repo/pull/2", "bodyText": "", "createdAt": "2017-11-25T20:01:33Z", "lastEditedAt": null, "publishedAt": "2017-11-25T20:01:33Z", "closedAt": "2017-12-10T11:33:22Z", "mergedAt": null, "merged": false, "closed": true, "changedFiles": 7, "additions": 4, "deletions": 9, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-11-20T15:01:21Z", "message": "My bad commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-11-20T15:42:48Z", "message": "My awesome commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } } ] } }, { "title": "Add Another Cool Feature", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/3", "bodyText": "", "createdAt": "2017-12-18T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-12-18T06:55:53Z", "closedAt": "2017-12-18T14:02:14Z", "mergedAt": "2017-12-18T14:02:14Z", "merged": true, "closed": true, "changedFiles": 15, "additions": 23, "deletions": 25, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-12-18T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-12-18T03:51:45Z", "message": "My cool commit #2", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-12-18T04:01:25Z", "message": "My cool commit #3", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } }, { "commit": { "committedDate": "2017-12-18T04:12:00Z", "message": "My cool commit #4", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } } ] } }, { "title": "Tweaking a Weird Component", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/4", "bodyText": "", "createdAt": "2017-12-20T22:02:23Z", "lastEditedAt": null, "publishedAt": "2017-12-20T22:02:23Z", "closedAt": "2017-12-22T14:02:14Z", "mergedAt": "2017-12-22T14:02:14Z", "merged": true, "closed": true, "changedFiles": 3, "additions": 8, "deletions": 12, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-12-20T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } } ] } }, { "title": "Tweaking Other Weird Component", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/5", "bodyText": "", "createdAt": "2017-12-20T23:22:23Z", "lastEditedAt": null, "publishedAt": "2017-12-20T23:22:23Z", "closedAt": "2017-12-22T10:02:14Z", "mergedAt": "2017-12-22T10:02:14Z", "merged": true, "closed": true, "changedFiles": 4, "additions": 3, "deletions": 10, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": { "nodes": [ { "commit": { "committedDate": "2017-12-20T01:59:01Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, } } ] }, }, { "title": "Refactoring Frenzy", "state": "OPEN", "id": "4343", "number": 6, "url": "https://github.com/myorg/my-beta-repo/pull/6", "bodyText": "", "createdAt": "2017-12-21T19:34:59Z", "lastEditedAt": "2017-12-21T21:23:17Z", "publishedAt": "2017-12-21T19:34:59Z", "closedAt": null, "mergedAt": null, "merged": false, "closed": false, "changedFiles": 2, "additions": 54, "deletions": 4, "commits": { "nodes": [ { "commit": { "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, "message": "abc 123", "committedDate": "2017-12-21T19:32:07Z" } }, { "commit": { "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, "message": "bcd 234", "committedDate": "2017-12-21T19:51:21Z" } }, { "commit": { "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, "message": "cde 345", "committedDate": "2017-12-21T19:53:01Z" } } ] }, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, ], "pageInfo": { "hasNextPage": false, "startCursor": "Y3Vyc29yOnYyOpHOBFTBQA==", "hasPreviousPage": false, "endCursor": "Y3Vyc29yOnYyOpHOBg+zyQ==" } } } } }, }, }, expected: { orgs: { myorg: { myrepo: { "repository": { "name": "myrepo", "url": "https://github.com/myorg/myrepo", "pullRequests": [ { "title": "Add README & LICENSE", "state": "MERGED", "id": "567", "number": 1, "url": "https://github.com/myorg/myrepo/pull/1", "bodyText": "", "createdAt": "2017-10-02T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-10-02T06:55:53Z", "closedAt": "2017-10-02T14:02:14Z", "mergedAt": "2017-10-02T14:02:14Z", "merged": true, "closed": true, "changedFiles": 2, "additions": 10, "deletions": 12, "author": { "login": "notabot", "url": "https://github.com/notabot" }, "commits": [ { "committedDate": "2017-10-02T04:01:30Z", "message": "My commit", "author": { "user": { "login": "notabot", "url": "https://github.com/notabot" } } } ] } ], "pageInfo": { "hasNextPage": false, "startCursor": "Y3Vyc29yOnYyOpHOBFTBQA==", "hasPreviousPage": false, "endCursor": "Y3Vyc29yOnYyOpHOBg+zyQ==" } }, }, 'my-better-repo': { "repository": { "name": "my-better-repo", "url": "https://github.com/myorg/my-better-repo", "pullRequests": [ { "title": "Add README & LICENSE", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-better-repo/pull/1", "bodyText": "", "createdAt": "2017-10-02T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-10-02T06:55:53Z", "closedAt": "2017-10-02T14:02:14Z", "mergedAt": "2017-10-02T14:02:14Z", "merged": true, "closed": true, "changedFiles": 3, "additions": 20, "deletions": 3, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": [ { "committedDate": "2017-10-02T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-10-02T03:51:45Z", "message": "My cool commit #2", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-10-02T03:59:00Z", "message": "My cool commit #3", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } ] }, { "title": "Add README & LICENSE... again.", "state": "MERGED", "id": "4343", "number": 2, "url": "https://github.com/myorg/my-better-repo/pull/2", "bodyText": "", "createdAt": "2017-10-02T06:59:33Z", "lastEditedAt": null, "publishedAt": "2017-10-02T06:59:33Z", "closedAt": "2017-10-03T11:33:22Z", "mergedAt": "2017-10-03T11:33:22Z", "merged": true, "closed": true, "changedFiles": 7, "additions": 4, "deletions": 9, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": [ { "committedDate": "2017-10-03T05:01:21Z", "message": "My bad commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-10-03T05:42:48Z", "message": "My awesome commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } ] } ], "pageInfo": { "hasNextPage": false, "startCursor": "Y3Vyc29yOnYyOpHOBFTBQA==", "hasPreviousPage": false, "endCursor": "Y3Vyc29yOnYyOpHOBg+zyQ==" } } }, 'my-beta-repo': { "repository": { "name": "my-beta-repo", "url": "https://github.com/myorg/my-beta-repo", "pullRequests": [ { "title": "Add a Cool Feature", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/1", "bodyText": "", "createdAt": "2017-11-18T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-11-18T06:55:53Z", "closedAt": "2017-11-18T14:02:14Z", "mergedAt": "2017-11-18T14:02:14Z", "merged": true, "closed": true, "changedFiles": 30, "additions": 30, "deletions": 4, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": [ { "committedDate": "2017-11-18T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-11-18T03:51:45Z", "message": "My cool commit #2", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-11-18T04:01:25Z", "message": "My cool commit #3", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-11-18T04:12:00Z", "message": "My cool commit #4", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } ], }, { "title": "Add a feature that we no longer wanted", "state": "CLOSED", "id": "4343", "number": 2, "url": "https://github.com/myorg/my-beta-repo/pull/2", "bodyText": "", "createdAt": "2017-11-25T20:01:33Z", "lastEditedAt": null, "publishedAt": "2017-11-25T20:01:33Z", "closedAt": "2017-12-10T11:33:22Z", "mergedAt": null, "merged": false, "closed": true, "changedFiles": 7, "additions": 4, "deletions": 9, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": [ { "committedDate": "2017-11-20T15:01:21Z", "message": "My bad commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-11-20T15:42:48Z", "message": "My awesome commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } ] }, { "title": "Add Another Cool Feature", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/3", "bodyText": "", "createdAt": "2017-12-18T06:55:53Z", "lastEditedAt": null, "publishedAt": "2017-12-18T06:55:53Z", "closedAt": "2017-12-18T14:02:14Z", "mergedAt": "2017-12-18T14:02:14Z", "merged": true, "closed": true, "changedFiles": 15, "additions": 23, "deletions": 25, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": [ { "committedDate": "2017-12-18T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-12-18T03:51:45Z", "message": "My cool commit #2", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-12-18T04:01:25Z", "message": "My cool commit #3", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } }, { "committedDate": "2017-12-18T04:12:00Z", "message": "My cool commit #4", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } ] }, { "title": "Tweaking a Weird Component", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/4", "bodyText": "", "createdAt": "2017-12-20T22:02:23Z", "lastEditedAt": null, "publishedAt": "2017-12-20T22:02:23Z", "closedAt": "2017-12-22T14:02:14Z", "mergedAt": "2017-12-22T14:02:14Z", "merged": true, "closed": true, "changedFiles": 3, "additions": 8, "deletions": 12, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": [ { "committedDate": "2017-12-20T03:31:11Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } ], }, { "title": "Tweaking Other Weird Component", "state": "MERGED", "id": "4343", "number": 1, "url": "https://github.com/myorg/my-beta-repo/pull/5", "bodyText": "", "createdAt": "2017-12-20T23:22:23Z", "lastEditedAt": null, "publishedAt": "2017-12-20T23:22:23Z", "closedAt": "2017-12-22T10:02:14Z", "mergedAt": "2017-12-22T10:02:14Z", "merged": true, "closed": true, "changedFiles": 4, "additions": 3, "deletions": 10, "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" }, "commits": [ { "committedDate": "2017-12-20T01:59:01Z", "message": "My cool commit", "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } } } ], }, { "title": "Refactoring Frenzy", "state": "OPEN", "id": "4343", "number": 6, "url": "https://github.com/myorg/my-beta-repo/pull/6", "bodyText": "", "createdAt": "2017-12-21T19:34:59Z", "lastEditedAt": "2017-12-21T21:23:17Z", "publishedAt": "2017-12-21T19:34:59Z", "closedAt": null, "mergedAt": null, "merged": false, "closed": false, "changedFiles": 2, "additions": 54, "deletions": 4, "commits": [ { "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, "message": "abc 123", "committedDate": "2017-12-21T19:32:07Z" }, { "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, "message": "bcd 234", "committedDate": "2017-12-21T19:51:21Z" }, { "author": { "user": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, "message": "cde 345", "committedDate": "2017-12-21T19:53:01Z" } ], "author": { "login": "realnotabot", "url": "https://github.com/realnotabot" } }, ], "pageInfo": { "hasNextPage": false, "startCursor": "Y3Vyc29yOnYyOpHOBFTBQA==", "hasPreviousPage": false, "endCursor": "Y3Vyc29yOnYyOpHOBg+zyQ==" } } }, }, }, }, };
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-strict import json import sys from typing import Any, Dict, List, Type, TypeVar, cast # pyre-fixme[21]: Could not find name `_TypedDictMeta` in `typing_extensions`. from typing_extensions import _TypedDictMeta from typing_inspect import get_origin, is_optional_type if sys.version_info[:2] < (3, 7): from typing_inspect import get_last_args as get_args else: from typing_inspect import get_args as get_args class InvalidJson(json.JSONDecodeError): def __init__(self, message: str) -> None: super().__init__(message, "", 0) def _is_list(target_type: Type[object]) -> bool: return get_origin(target_type) in (List, list) def _is_dictionary(target_type: Type[object]) -> bool: return get_origin(target_type) in (Dict, dict) def _is_typed_dictionary(target_type: Type[object]) -> bool: return isinstance(target_type, _TypedDictMeta) # pyre-ignore: private API. def _validate_list(value: object, target_type: Type[List[object]]) -> None: if not isinstance(value, list): raise InvalidJson(f"`{value}` is not a list") (element_type,) = get_args(target_type) for element in value: _validate_value(element, element_type) def _validate_dictionary( value: object, target_type: Type[Dict[object, object]] ) -> None: if not isinstance(value, dict): raise InvalidJson(f"`{value}` is not a dictionary") key_type, value_type = get_args(target_type) for key, value in value.items(): _validate_value(key, key_type) _validate_value(value, value_type) def _validate_typed_dictionary(value: object, target_type: Type[object]) -> None: if not isinstance(value, dict): raise InvalidJson(f"`{value}` is not a dictionary") for key, value_type in target_type.__annotations__.items(): if key not in value: raise InvalidJson( f"{value} of TypedDict {target_type} must contain key {key}" ) _validate_value(value[key], value_type) def _validate_value(value: object, target_type: Type[object]) -> None: if target_type is Any: return elif _is_list(target_type): _validate_list(value, cast(Type[List[object]], target_type)) elif _is_dictionary(target_type): _validate_dictionary(value, cast(Type[Dict[object, object]], target_type)) elif _is_typed_dictionary(target_type): _validate_typed_dictionary(value, target_type) elif is_optional_type(target_type): if value is None: return _validate_value(value, get_args(target_type)[0]) else: if target_type not in [int, float, str, bool]: raise InvalidJson(f"Invalid value type {target_type}") if not isinstance(value, target_type): raise InvalidJson(f"`{value}` is not a {target_type}") def _validate_toplevel(value: object, target_type: Type[object]) -> None: if _is_list(target_type): _validate_list(value, cast(Type[List[object]], target_type)) elif _is_dictionary(target_type): _validate_dictionary(value, cast(Type[Dict[object, object]], target_type)) elif _is_typed_dictionary(target_type): _validate_typed_dictionary(value, target_type) else: raise NotImplementedError(f"Cannot safely parse {value}") T = TypeVar("T") def loads(input_: str, target: Type[T], *, validate: bool = True) -> T: try: parsed = json.loads(input_) if validate: _validate_toplevel(parsed, target) return parsed except Exception as exception: raise InvalidJson(str(exception))
const { PdfApi } = require("asposepdfcloud"); pdfApi = new PdfApi( "78946fb4-3bd4-4d3e-b309-f9e2ff9ac6f9", "b125f13bf6b76ed81ee990142d841195") console.log('running example'); pdfApi.getDocumentCaretAnnotations( "PdfWithAnnotations.pdf", null, null) .then((result) => { console.log(result.response); });
import Vue from 'vue'; import terminalComp from '~/environments/components/environment_terminal_button'; describe('Stop Component', () => { let TerminalComponent; let component; const terminalPath = '/path'; beforeEach(() => { TerminalComponent = Vue.extend(terminalComp); component = new TerminalComponent({ propsData: { terminalPath, }, }).$mount(); }); it('should render a link to open a web terminal with the provided path', () => { expect(component.$el.tagName).toEqual('A'); expect(component.$el.getAttribute('title')).toEqual('Terminal'); expect(component.$el.getAttribute('href')).toEqual(terminalPath); }); });
var x; var y; class Base { b(a) {} get c() { return x; } set c(v) {} static s(a) {} static get t() { return x; } static set t(v) {} constructor(a){} } class Derived extends Base { b(a) {} get c() { return y; } set c(v) {} static s(a) {} static get t() { return y; } static set t(a) {} constructor(a){ super(x); } } var d = new Derived(y); var r1 = d.a; var r2 = d.b(y); var r3 = d.c; var r3a = d.d; d.c = y; var r4 = Derived.r; var r5 = Derived.s(y); var r6 = Derived.t; var r6a = Derived.u; Derived.t = y; class Base2 { } class Derived2 extends Base2 { } var d2; var r7 = d2['']; var r8 = d2[1];
export { RestaurantsView } from './RestaurantsView';
/** * @name exports * @summary AppointmentParticipant Class */ module.exports = class AppointmentParticipant { constructor(opts) { // Create an object to store all props Object.defineProperty(this, '__data', { value: {} }); // Define getters and setters as enumerable Object.defineProperty(this, '_id', { enumerable: true, get: () => this.__data._id, set: (value) => { if (value === undefined || value === null) { return; } let Element = require('./element.js'); this.__data._id = new Element(value); }, }); Object.defineProperty(this, 'id', { enumerable: true, get: () => this.__data.id, set: (value) => { if (value === undefined || value === null) { return; } this.__data.id = value; }, }); Object.defineProperty(this, 'extension', { enumerable: true, get: () => this.__data.extension, set: (value) => { if (value === undefined || value === null) { return; } let Extension = require('./extension.js'); this.__data.extension = Array.isArray(value) ? value.map((v) => new Extension(v)) : [new Extension(value)]; }, }); Object.defineProperty(this, 'modifierExtension', { enumerable: true, get: () => this.__data.modifierExtension, set: (value) => { if (value === undefined || value === null) { return; } let Extension = require('./extension.js'); this.__data.modifierExtension = Array.isArray(value) ? value.map((v) => new Extension(v)) : [new Extension(value)]; }, }); Object.defineProperty(this, 'type', { enumerable: true, get: () => this.__data.type, set: (value) => { if (value === undefined || value === null) { return; } let CodeableConcept = require('./codeableconcept.js'); this.__data.type = Array.isArray(value) ? value.map((v) => new CodeableConcept(v)) : [new CodeableConcept(value)]; }, }); Object.defineProperty(this, 'actor', { enumerable: true, get: () => this.__data.actor, set: (value) => { if (value === undefined || value === null) { return; } let Reference = require('./reference.js'); this.__data.actor = new Reference(value); }, }); Object.defineProperty(this, '_required', { enumerable: true, get: () => this.__data._required, set: (value) => { if (value === undefined || value === null) { return; } let Element = require('./element.js'); this.__data._required = new Element(value); }, }); Object.defineProperty(this, 'required', { enumerable: true, get: () => this.__data.required, set: (value) => { if (value === undefined || value === null) { return; } this.__data.required = value; }, }); Object.defineProperty(this, '_status', { enumerable: true, get: () => this.__data._status, set: (value) => { if (value === undefined || value === null) { return; } let Element = require('./element.js'); this.__data._status = new Element(value); }, }); Object.defineProperty(this, 'status', { enumerable: true, get: () => this.__data.status, set: (value) => { if (value === undefined || value === null) { return; } this.__data.status = value; }, }); Object.defineProperty(this, 'period', { enumerable: true, get: () => this.__data.period, set: (value) => { if (value === undefined || value === null) { return; } let Period = require('./period.js'); this.__data.period = new Period(value); }, }); // Merge in any defaults Object.assign(this, opts); // Define a default non-writable resourceType property Object.defineProperty(this, 'resourceType', { value: 'AppointmentParticipant', enumerable: true, writable: false, }); } static get resourceType() { return 'AppointmentParticipant'; } toJSON() { return { id: this.id, extension: this.extension && this.extension.map((v) => v.toJSON()), modifierExtension: this.modifierExtension && this.modifierExtension.map((v) => v.toJSON()), type: this.type && this.type.map((v) => v.toJSON()), actor: this.actor && this.actor.toJSON(), _required: this._required && this._required.toJSON(), required: this.required, _status: this._status && this._status.toJSON(), status: this.status, period: this.period && this.period.toJSON(), }; } };
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js'); firebase.initializeApp({ 'messagingSenderId': 'myId' }); const messaging = firebase.messaging();
# -*- coding: utf-8 -*- """Clinical Knowledge Graph.""" import tarfile from pathlib import Path from typing import Iterable, Optional from urllib.request import urlretrieve import click import pandas as pd from docdata import parse_docdata from more_click import verbose_option from .base import TabbedDataset from ..typing import TorchRandomHint __all__ = [ 'CKG', ] URL = 'https://md-datasets-public-files-prod.s3.eu-west-1.amazonaws.com/d1e8d3df-2342-468a-91a9-97a981a479ad' COLUMNS = ['START_ID', 'TYPE', 'END_ID'] @parse_docdata class CKG(TabbedDataset): """The Clinical Knowledge Graph (CKG) dataset from [santos2020]_. --- name: Clinical Knowledge Graph citation: author: Santos year: 2020 link: https://doi.org/10.1101/2020.05.09.084897 github: MannLabs/CKG single: true statistics: entities: 7617419 relations: 11 triples: 26691525 """ def __init__( self, create_inverse_triples: bool = False, random_state: TorchRandomHint = 0, **kwargs, ): """Initialize the `CKG <https://github.com/MannLabs/CKG>`_ dataset from [santos2020]_. :param create_inverse_triples: Should inverse triples be created? Defaults to false. :param random_state: The random seed to use in splitting the dataset. Defaults to 0. :param kwargs: keyword arguments passed to :class:`pykeen.datasets.base.TabbedDataset`. """ super().__init__( create_inverse_triples=create_inverse_triples, random_state=random_state, **kwargs, ) self.preloaded_path = self.cache_root / 'preloaded.tsv.gz' def _get_path(self) -> Optional[str]: return self.preloaded_path.as_posix() def _get_df(self) -> pd.DataFrame: if self.preloaded_path.exists(): return pd.read_csv(self.preloaded_path, sep='\t', dtype=str) df = pd.concat(self._iterate_dataframes()) df.to_csv(self.preloaded_path, sep='\t', index=False) return df def _iterate_dataframes(self) -> Iterable[pd.DataFrame]: archive_path = self.cache_root / 'data.tar.gz' if not archive_path.exists(): urlretrieve(URL, archive_path) # noqa:S310 with tarfile.TarFile.open(archive_path) as tar_file: if tar_file is None: raise ValueError for tarinfo in tar_file: if not tarinfo.name.startswith('data/imports/') or not tarinfo.name.endswith('.tsv'): continue path = Path(tarinfo.name) if path.name.startswith('.'): continue _inner_file = tar_file.extractfile(tarinfo) if _inner_file is None: raise ValueError(f'Unable to open inner file: {tarinfo}') with _inner_file as file: df = pd.read_csv(file, usecols=COLUMNS, sep='\t', dtype=str) df = df[COLUMNS] yield df @click.command() @verbose_option def _main(): d = CKG() d.summarize() if __name__ == '__main__': _main()
import merge from 'lodash/merge'; import Breakpoints from '../breakpoints'; import { columnOptions } from '../constants'; import { hexToRgba } from '../utils'; import { getDataZoomConfig, getThresholdConfig, mergeSeriesToOptions, parseAnnotations, generateBarSeries, generateLineSeries, } from './config'; import { mockDefaultDataZoomConfig, mockDefaultChartOptions, mockDefaultStackedBarData, mockDefaultLineData, } from './mock_data'; import { colorFromDefaultPalette } from './theme'; describe('chart config helpers', () => { describe('getThresholdConfig', () => { const makeThreshold = (threshold, operator) => [ { threshold, operator, }, ]; it('returns empty object for no thresholds', () => { expect(getThresholdConfig([])).toEqual({}); }); it('draws area below line for < threshold', () => { const threshold = 3; const thresholds = makeThreshold(threshold, '<'); const expectedLineData = [{ yAxis: threshold }]; const expectedAreaData = [[{ yAxis: Number.NEGATIVE_INFINITY }, { yAxis: threshold }]]; const { markLine, markArea } = getThresholdConfig(thresholds); expect(markLine.data).toEqual(expectedLineData); expect(markArea.data).toEqual(expectedAreaData); }); it('draws line only for = threshold', () => { const threshold = 7; const thresholds = makeThreshold(threshold, '='); const expectedLineData = [{ yAxis: threshold }]; const expectedAreaData = []; const { markLine, markArea } = getThresholdConfig(thresholds); expect(markLine.data).toEqual(expectedLineData); expect(markArea.data).toEqual(expectedAreaData); }); it('draws area above line for > threshold', () => { const threshold = 9000; const thresholds = makeThreshold(threshold, '>'); const expectedLineData = [{ yAxis: threshold }]; const expectedAreaData = [[{ yAxis: threshold }, { yAxis: Infinity }]]; const { markLine, markArea } = getThresholdConfig(thresholds); expect(markLine.data).toEqual(expectedLineData); expect(markArea.data).toEqual(expectedAreaData); }); }); describe('parseAnnotations', () => { const makeAnnotation = ({ min, max }) => [ { min, max, }, ]; it('returns empty object for no annotations', () => { expect(parseAnnotations([])).toEqual({ areas: [], lines: [], points: [], }); }); it('draws an annotation range between two fixed points', () => { const annotation = makeAnnotation({ min: 10, max: 40, }); const expectedLineData = []; const expectedAreaData = [[{ xAxis: 10 }, { xAxis: 40 }]]; const { lines, areas } = parseAnnotations(annotation); expect(lines).toEqual(expectedLineData); expect(areas).toEqual(expectedAreaData); }); it('draws an annotation range with infinity upper bound', () => { const annotation = makeAnnotation({ min: 10, max: Infinity, }); const expectedLineData = []; const expectedAreaData = [[{ xAxis: 10 }, { xAxis: Infinity }]]; const { lines, areas } = parseAnnotations(annotation); expect(lines).toEqual(expectedLineData); expect(areas).toEqual(expectedAreaData); }); it('draws an annotation range with infinity lower bound', () => { const annotation = makeAnnotation({ min: Number.NEGATIVE_INFINITY, max: 10, }); const expectedLineData = []; const expectedAreaData = [[{ xAxis: -Infinity }, { xAxis: 10 }]]; const { lines, areas } = parseAnnotations(annotation); expect(lines).toEqual(expectedLineData); expect(areas).toEqual(expectedAreaData); }); it('draws an annotation range without upper bound', () => { const annotation = makeAnnotation({ min: 10, }); const expectedLineData = []; const expectedAreaData = [[{ xAxis: 10 }, { xAxis: undefined }]]; const { lines, areas } = parseAnnotations(annotation); expect(lines).toEqual(expectedLineData); expect(areas).toEqual(expectedAreaData); }); it('draws an annotation range without lower bound', () => { const annotation = makeAnnotation({ max: 10, }); const expectedLineData = []; const expectedAreaData = [[{ xAxis: undefined }, { xAxis: 10 }]]; const { lines, areas } = parseAnnotations(annotation); expect(lines).toEqual(expectedLineData); expect(areas).toEqual(expectedAreaData); }); it('draws an annotation line', () => { const annotation = makeAnnotation({ min: 10, max: 10, }); const expectedLineData = [{ xAxis: 10 }]; const expectedAreaData = []; const { lines, areas } = parseAnnotations(annotation); expect(lines).toEqual(expectedLineData); expect(areas).toEqual(expectedAreaData); }); it('draws multiple annotation lines', () => { const annotation1 = makeAnnotation({ min: 10, max: 10, }); const annotation2 = makeAnnotation({ min: 30, max: 30, }); const expectedLineData = [{ xAxis: 10 }, { xAxis: 30 }]; const expectedAreaData = []; const { lines, areas } = parseAnnotations([...annotation1, ...annotation2]); expect(lines).toEqual(expectedLineData); expect(areas).toEqual(expectedAreaData); }); }); describe('getDataZoomConfig', () => { describe('on large viewports (lg, xl)', () => { it('creates a basic dataZoomConfig with inside scrolling being disabled', () => { const actual = getDataZoomConfig(); const expected = mockDefaultDataZoomConfig; expect(actual).toEqual(expected); }); }); describe('on small viewports', () => { it('creates a basic dataZoomConfig with inside scrolling being enabled', () => { jest.spyOn(Breakpoints, 'getBreakpointSize').mockImplementationOnce(() => 'sm'); const actual = getDataZoomConfig(); const dataZoomWithInsideEnabled = [ { bottom: 22, filterMode: 'none', minSpan: 0.01, type: 'slider', }, { type: 'inside', filterMode: 'none', minSpan: 0.01, disabled: false, }, ]; const expected = merge(mockDefaultDataZoomConfig, { dataZoom: dataZoomWithInsideEnabled, }); expect(actual).toEqual(expected); }); }); it('allows the filterMode to be set', () => { const actual = getDataZoomConfig({ filterMode: 'filter' }); // After https://gitlab.com/gitlab-org/gitlab-ui/issues/240 // all default dataZoom configs will have slider & inside. // inside is specifically to enable touch zoom for mobile devices const dataZoomWithFilter = [ { type: 'slider', filterMode: 'filter', minSpan: null, }, { type: 'inside', filterMode: 'filter', minSpan: null, disabled: true, }, ]; const expected = merge(mockDefaultDataZoomConfig, { dataZoom: dataZoomWithFilter, }); expect(actual).toEqual(expected); }); }); describe('mergeSeriesToOptions', () => { const series = { areaStyle: { opacity: 0.2, color: '#1f78d1', }, showSymbol: false, lineStyle: { color: '#1f78d1', }, itemStyle: { color: '#1f78d1', }, symbol: 'circle', type: 'line', width: 2, name: 'Values', data: [ [0, 5], [4, 3], [8, 10], ], }; it('create chart options with invalid series props', () => { const chartOptionsOutput = { ...mockDefaultChartOptions, series: [], }; expect(mergeSeriesToOptions(mockDefaultChartOptions)).toEqual(chartOptionsOutput); expect(mergeSeriesToOptions(mockDefaultChartOptions, [])).toEqual(chartOptionsOutput); }); it('creates chart options with single series object passed as data prop', () => { // data for chart can also be passed as a data prop which is transformed to series const chartOptions = mergeSeriesToOptions({ ...mockDefaultChartOptions, series, }); expect(chartOptions.series).toBeInstanceOf(Array); expect(chartOptions.series.length).toBe(1); }); it('creates chart options with single series array passed as data prop', () => { const chartOptions = mergeSeriesToOptions({ ...mockDefaultChartOptions, series: [series], }); expect(chartOptions.series).toBeInstanceOf(Array); expect(chartOptions.series.length).toBe(1); }); it('creates chart options with multiple series array passed as data prop', () => { const chartOptions = mergeSeriesToOptions({ ...mockDefaultChartOptions, series: [series, series], }); expect(chartOptions.series).toBeInstanceOf(Array); expect(chartOptions.series.length).toBe(2); }); it('creates chart options with single series object passed as series prop', () => { const chartOptions = mergeSeriesToOptions(mockDefaultChartOptions, series); expect(chartOptions.series).toBeInstanceOf(Array); expect(chartOptions.series.length).toBe(1); }); it('creates chart options with single series array passed as series prop', () => { const chartOptions = mergeSeriesToOptions(mockDefaultChartOptions, [series]); expect(chartOptions.series).toBeInstanceOf(Array); expect(chartOptions.series.length).toBe(1); }); it('creates chart options with multiple series array passed as series prop', () => { const chartOptions = mergeSeriesToOptions(mockDefaultChartOptions, [series, series]); expect(chartOptions.series).toBeInstanceOf(Array); expect(chartOptions.series.length).toBe(2); }); }); describe('generateBarSeries', () => { const defaultBarColors = { itemStyle: { color: hexToRgba(colorFromDefaultPalette(1), 0.2) }, emphasis: { itemStyle: { color: hexToRgba(colorFromDefaultPalette(1), 0.4) } }, }; const barDefaultParams = { name: 'Bar chart', color: colorFromDefaultPalette(0), stack: columnOptions.stacked, }; it.each` param | value | result ${'name'} | ${'Cool new bar chart'} | ${{ name: 'Cool new bar chart' }} ${'color'} | ${colorFromDefaultPalette(1)} | ${defaultBarColors} ${'data'} | ${mockDefaultStackedBarData} | ${{ data: mockDefaultStackedBarData }} ${'stack'} | ${columnOptions.tiled} | ${{ stack: columnOptions.tiled }} ${'yAxisIndex'} | ${3} | ${{ yAxisIndex: 3 }} `('with $param set will contain $result', ({ param, value, result }) => { expect( generateBarSeries({ ...barDefaultParams, [param]: value, }) ).toMatchObject(result); }); }); describe('generateLineSeries', () => { const defaultLineColors = { itemStyle: { color: colorFromDefaultPalette(1) }, lineStyle: { color: colorFromDefaultPalette(1) }, }; const lineDefaultParams = { name: 'Line chart', color: colorFromDefaultPalette(0) }; it.each` param | value | result ${'name'} | ${'Cool new line chart'} | ${{ name: 'Cool new line chart' }} ${'color'} | ${colorFromDefaultPalette(1)} | ${defaultLineColors} ${'data'} | ${mockDefaultLineData} | ${{ data: mockDefaultLineData }} ${'yAxisIndex'} | ${2} | ${{ yAxisIndex: 2 }} `('with $param set will contain $result', ({ param, value, result }) => { expect( generateLineSeries({ ...lineDefaultParams, [param]: value, }) ).toMatchObject(result); }); }); });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.lang['sv']={"editor":"Rich Text Editor","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"Tryck ALT 0 för hjälp","browseServer":"Bläddra på server","url":"URL","protocol":"Protokoll","upload":"Ladda upp","uploadSubmit":"Skicka till server","image":"Bild","flash":"Flash","form":"Formulär","checkbox":"Kryssruta","radio":"Alternativknapp","textField":"Textfält","textarea":"Textruta","hiddenField":"Dolt fält","button":"Knapp","select":"Flervalslista","imageButton":"Bildknapp","notSet":"<ej angivet>","id":"Id","name":"Namn","langDir":"Språkriktning","langDirLtr":"Vänster till Höger (VTH)","langDirRtl":"Höger till Vänster (HTV)","langCode":"Språkkod","longDescr":"URL-beskrivning","cssClass":"Stilmall","advisoryTitle":"Titel","cssStyle":"Stilmall","ok":"OK","cancel":"Avbryt","close":"Stäng","preview":"Förhandsgranska","resize":"Dra för att ändra storlek","generalTab":"Allmänt","advancedTab":"Avancerad","validateNumberFailed":"Värdet är inte ett nummer.","confirmNewPage":"Alla ändringar i innehållet kommer att förloras. Är du säker på att du vill ladda en ny sida?","confirmCancel":"Några av alternativen har ändrats. Är du säker på att du vill stänga dialogrutan?","options":"Alternativ","target":"Mål","targetNew":"Nytt fönster (_blank)","targetTop":"Översta fönstret (_top)","targetSelf":"Samma fönster (_self)","targetParent":"Föregående fönster (_parent)","langDirLTR":"Vänster till höger (LTR)","langDirRTL":"Höger till vänster (RTL)","styles":"Stil","cssClasses":"Stilmallar","width":"Bredd","height":"Höjd","align":"Justering","alignLeft":"Vänster","alignRight":"Höger","alignCenter":"Centrerad","alignTop":"Överkant","alignMiddle":"Mitten","alignBottom":"Nederkant","invalidValue":"Felaktigt värde.","invalidHeight":"Höjd måste vara ett nummer.","invalidWidth":"Bredd måste vara ett nummer.","invalidCssLength":"Värdet för fältet \"%1\" måste vara ett positivt nummer med eller utan CSS-mätenheter (px, %, in, cm, mm, em, ex, pt, eller pc).","invalidHtmlLength":"Värdet för fältet \"%1\" måste vara ett positivt nummer med eller utan godkända HTML-mätenheter (px eller %).","invalidInlineStyle":"Det angivna värdet för style måste innehålla en eller flera tupler separerade med semikolon i följande format: \"name : value\"","cssLengthTooltip":"Ange ett nummer i pixlar eller ett nummer men godkänd CSS-mätenhet (px, %, in, cm, mm, em, ex, pt, eller pc).","unavailable":"%1<span class=\"cke_accessibility\">, Ej tillgänglig</span>"},"about":{"copy":"Copyright &copy; $1. Alla rättigheter reserverade.","dlgTitle":"Om CKEditor","help":"Se $1 för hjälp.","moreInfo":"För information av licensiering besök vår hemsida:","title":"Om CKEditor","userGuide":"CKEditor User's Guide"},"basicstyles":{"bold":"Fet","italic":"Kursiv","strike":"Genomstruken","subscript":"Nedsänkta tecken","superscript":"Upphöjda tecken","underline":"Understruken"},"blockquote":{"toolbar":"Blockcitat"},"clipboard":{"copy":"Kopiera","copyError":"Säkerhetsinställningar i Er webbläsare tillåter inte åtgärden kopiera. Använd (Ctrl/Cmd+C) istället.","cut":"Klipp ut","cutError":"Säkerhetsinställningar i Er webbläsare tillåter inte åtgärden klipp ut. Använd (Ctrl/Cmd+X) istället.","paste":"Klistra in","pasteArea":"Paste Area","pasteMsg":"Var god och klistra in Er text i rutan nedan genom att använda (<strong>Ctrl/Cmd+V</strong>) klicka sen på OK.","securityMsg":"På grund av din webbläsares säkerhetsinställningar kan verktyget inte få åtkomst till urklippsdatan. Var god och använd detta fönster istället.","title":"Klistra in"},"contextmenu":{"options":"Context menu Options"},"toolbar":{"toolbarCollapse":"Dölj verktygsfält","toolbarExpand":"Visa verktygsfält","toolbarGroups":{"document":"Dokument","clipboard":"Clipboard/Undo","editing":"Editing","forms":"Forms","basicstyles":"Basic Styles","paragraph":"Paragraph","links":"Links","insert":"Insert","styles":"Styles","colors":"Colors","tools":"Tools"},"toolbars":"Redigera verktygsfält"},"elementspath":{"eleLabel":"Elementets sökväg","eleTitle":"%1 element"},"format":{"label":"Teckenformat","panelTitle":"Teckenformat","tag_address":"Adress","tag_div":"Normal (DIV)","tag_h1":"Rubrik 1","tag_h2":"Rubrik 2","tag_h3":"Rubrik 3","tag_h4":"Rubrik 4","tag_h5":"Rubrik 5","tag_h6":"Rubrik 6","tag_p":"Normal","tag_pre":"Formaterad"},"horizontalrule":{"toolbar":"Infoga horisontal linje"},"image":{"alertUrl":"Var god och ange bildens URL","alt":"Alternativ text","border":"Kant","btnUpload":"Skicka till server","button2Img":"Vill du omvandla den valda bildknappen på en enkel bild?","hSpace":"Horis. marginal","img2Button":"Vill du omvandla den valda bildknappen på en enkel bild?","infoTab":"Bildinformation","linkTab":"Länk","lockRatio":"Lås höjd/bredd förhållanden","menu":"Bildegenskaper","resetSize":"Återställ storlek","title":"Bildegenskaper","titleButton":"Egenskaper för bildknapp","upload":"Ladda upp","urlMissing":"Bildkällans URL saknas.","vSpace":"Vert. marginal","validateBorder":"Kantlinje måste vara ett heltal.","validateHSpace":"HSpace måste vara ett heltal.","validateVSpace":"VSpace måste vara ett heltal."},"indent":{"indent":"Öka indrag","outdent":"Minska indrag"},"fakeobjects":{"anchor":"Ankare","flash":"Flashanimation","hiddenfield":"Gömt fält","iframe":"iFrame","unknown":"Okänt objekt"},"link":{"acccessKey":"Behörighetsnyckel","advanced":"Avancerad","advisoryContentType":"Innehållstyp","advisoryTitle":"Titel","anchor":{"toolbar":"Infoga/Redigera ankarlänk","menu":"Egenskaper för ankarlänk","title":"Egenskaper för ankarlänk","name":"Ankarnamn","errorName":"Var god ange ett ankarnamn","remove":"Radera ankare"},"anchorId":"Efter element-id","anchorName":"Efter ankarnamn","charset":"Teckenuppställning","cssClasses":"Stilmall","emailAddress":"E-postadress","emailBody":"Innehåll","emailSubject":"Ämne","id":"Id","info":"Länkinformation","langCode":"Språkkod","langDir":"Språkriktning","langDirLTR":"Vänster till höger (VTH)","langDirRTL":"Höger till vänster (HTV)","menu":"Redigera länk","name":"Namn","noAnchors":"(Inga ankare kunde hittas)","noEmail":"Var god ange e-postadress","noUrl":"Var god ange länkens URL","other":"<annan>","popupDependent":"Beroende (endast Netscape)","popupFeatures":"Popup-fönstrets egenskaper","popupFullScreen":"Helskärm (endast IE)","popupLeft":"Position från vänster","popupLocationBar":"Adressfält","popupMenuBar":"Menyfält","popupResizable":"Resizable","popupScrollBars":"Scrolllista","popupStatusBar":"Statusfält","popupToolbar":"Verktygsfält","popupTop":"Position från sidans topp","rel":"Förhållande","selectAnchor":"Välj ett ankare","styles":"Stilmall","tabIndex":"Tabindex","target":"Mål","targetFrame":"<ram>","targetFrameName":"Målets ramnamn","targetPopup":"<popup-fönster>","targetPopupName":"Popup-fönstrets namn","title":"Länk","toAnchor":"Länk till ankare i texten","toEmail":"E-post","toUrl":"URL","toolbar":"Infoga/Redigera länk","type":"Länktyp","unlink":"Radera länk","upload":"Ladda upp"},"list":{"bulletedlist":"Punktlista","numberedlist":"Numrerad lista"},"magicline":{"title":"Infoga paragraf här"},"maximize":{"maximize":"Maximera","minimize":"Minimera"},"pastetext":{"button":"Klistra in som vanlig text","title":"Klistra in som vanlig text"},"pastefromword":{"confirmCleanup":"Texten du vill klistra in verkar vara kopierad från Word. Vill du rensa den innan du klistrar in den?","error":"Det var inte möjligt att städa upp den inklistrade data på grund av ett internt fel","title":"Klistra in från Word","toolbar":"Klistra in från Word"},"removeformat":{"toolbar":"Radera formatering"},"sourcearea":{"toolbar":"Källa"},"specialchar":{"options":"Alternativ för utökade tecken","title":"Välj utökat tecken","toolbar":"Klistra in utökat tecken"},"scayt":{"about":"Om SCAYT","aboutTab":"Om","addWord":"Lägg till ord","allCaps":"Ignorera alla ord med enbart versaler","dic_create":"Skapa","dic_delete":"Ta bort","dic_field_name":"Ordlistans namn","dic_info":"Inledningsvis lagras ordlistan i en cookie. När ordlista växer till en punkt där det inte kan lagras i en cookie, lagras den på vår server. För att lagra din personliga ordlista på vår server du ska ange ett namn för din ordbok. Om du redan har en lagrad ordbok, skriv namnet och klicka på knappen Återställ.","dic_rename":"Byt namn","dic_restore":"Återställ","dictionariesTab":"Ordlistor","disable":"Inaktivera SCAYT","emptyDic":"Ordlistans namn får ej vara tomt.","enable":"Aktivera SCAYT","ignore":"Ignorera","ignoreAll":"Ignorera alla","ignoreDomainNames":"Ignorera domännamn","langs":"Språk","languagesTab":"Språk","mixedCase":"Ignorera ord med blandat shiftläge","mixedWithDigits":"Ignorera ord med nummer","moreSuggestions":"Fler förslag","opera_title":"Stöds ej av Opera","options":"Inställningar","optionsTab":"Inställningar","title":"Stavningskontroll medan du skriver","toggle":"Växla SCAYT","noSuggestions":"No suggestion"},"stylescombo":{"label":"Anpassad stil","panelTitle":"Formatmallar","panelTitle1":"Blockstil","panelTitle2":"Inbäddad stil","panelTitle3":"Objektets stil"},"table":{"border":"Kantstorlek","caption":"Rubrik","cell":{"menu":"Cell","insertBefore":"Lägg till cell före","insertAfter":"Lägg till cell efter","deleteCell":"Radera celler","merge":"Sammanfoga celler","mergeRight":"Sammanfoga höger","mergeDown":"Sammanfoga ner","splitHorizontal":"Dela cell horisontellt","splitVertical":"Dela cell vertikalt","title":"Egenskaper för cell","cellType":"Celltyp","rowSpan":"Rad spann","colSpan":"Kolumnen spann","wordWrap":"Radbrytning","hAlign":"Horisontell justering","vAlign":"Vertikal justering","alignBaseline":"Baslinje","bgColor":"Bakgrundsfärg","borderColor":"Ramfärg","data":"Data","header":"Rubrik","yes":"Ja","no":"Nej","invalidWidth":"Cellens bredd måste vara ett nummer.","invalidHeight":"Cellens höjd måste vara ett nummer.","invalidRowSpan":"Radutvidgning måste vara ett heltal.","invalidColSpan":"Kolumn måste vara ett heltal.","chooseColor":"Välj"},"cellPad":"Cellutfyllnad","cellSpace":"Cellavstånd","column":{"menu":"Kolumn","insertBefore":"Lägg till kolumn före","insertAfter":"Lägg till kolumn efter","deleteColumn":"Radera kolumn"},"columns":"Kolumner","deleteTable":"Radera tabell","headers":"Rubriker","headersBoth":"Båda","headersColumn":"Första kolumnen","headersNone":"Ingen","headersRow":"Första raden","invalidBorder":"Ram måste vara ett nummer.","invalidCellPadding":"Luft i cell måste vara ett nummer.","invalidCellSpacing":"Luft i cell måste vara ett nummer.","invalidCols":"Antal kolumner måste vara ett nummer större än 0.","invalidHeight":"Tabellens höjd måste vara ett nummer.","invalidRows":"Antal rader måste vara större än 0.","invalidWidth":"Tabell måste vara ett nummer.","menu":"Tabellegenskaper","row":{"menu":"Rad","insertBefore":"Lägg till rad före","insertAfter":"Lägg till rad efter","deleteRow":"Radera rad"},"rows":"Rader","summary":"Sammanfattning","title":"Tabellegenskaper","toolbar":"Tabell","widthPc":"procent","widthPx":"pixlar","widthUnit":"enhet bredd"},"undo":{"redo":"Gör om","undo":"Ångra"},"wsc":{"btnIgnore":"Ignorera","btnIgnoreAll":"Ignorera alla","btnReplace":"Ersätt","btnReplaceAll":"Ersätt alla","btnUndo":"Ångra","changeTo":"Ändra till","errorLoading":"Tjänsten är ej tillgänglig: %s.","ieSpellDownload":"Stavningskontrollen är ej installerad. Vill du göra det nu?","manyChanges":"Stavningskontroll slutförd: %1 ord rättades.","noChanges":"Stavningskontroll slutförd: Inga ord rättades.","noMispell":"Stavningskontroll slutförd: Inga stavfel påträffades.","noSuggestions":"- Förslag saknas -","notAvailable":"Tyvärr är tjänsten ej tillgänglig nu","notInDic":"Saknas i ordlistan","oneChange":"Stavningskontroll slutförd: Ett ord rättades.","progress":"Stavningskontroll pågår...","title":"Kontrollera stavning","toolbar":"Stavningskontroll"}};
/** * Copyright IBM Corp. 2019, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Icon = require('../Icon-e8f71a9c.js'); require('@carbon/icon-helpers'); require('prop-types'); var React = _interopDefault(require('react')); var _ref2 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M30,24a6,6,0,1,0-6,6A6.0066,6.0066,0,0,0,30,24Zm-2,0a3.9521,3.9521,0,0,1-.5669,2.019L21.981,20.5669A3.9529,3.9529,0,0,1,24,20,4.0045,4.0045,0,0,1,28,24Zm-8,0a3.9521,3.9521,0,0,1,.5669-2.019l5.4521,5.4521A3.9529,3.9529,0,0,1,24,28,4.0045,4.0045,0,0,1,20,24Z" }); var _ref3 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M14,2a12,12,0,1,0,2,23.82V24a8,8,0,0,1,8-8h1.82A11.9348,11.9348,0,0,0,14,2ZM12,18.5908l-4-4L9.5908,13,12,15.4092,17.4092,10,19,11.5908Z" }); var _ref4 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { fill: "none", d: "M12 18.591L8 14.591 9.591 13 12 15.409 17.409 10 19 11.591 12 18.591z" }); var CheckmarkFilledError24 = /*#__PURE__*/React.forwardRef(function CheckmarkFilledError24(_ref, ref) { var children = _ref.children, rest = Icon._objectWithoutProperties(_ref, ["children"]); return /*#__PURE__*/React.createElement(Icon.Icon, Icon._extends({ width: 24, height: 24, viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", ref: ref }, rest), _ref2, _ref3, _ref4, children); }); module.exports = CheckmarkFilledError24;
import { module, test } from '../qunit'; import moment from '../../moment'; import each from '../helpers/each'; module('days in month'); test('days in month', function (assert) { each([31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], function (days, i) { var firstDay = moment([2012, i]), lastDay = moment([2012, i, days]); assert.equal(firstDay.daysInMonth(), days, firstDay.format('L') + ' should have ' + days + ' days.'); assert.equal(lastDay.daysInMonth(), days, lastDay.format('L') + ' should have ' + days + ' days.'); }); }); test('days in month leap years', function (assert) { assert.equal(moment([2010, 1]).daysInMonth(), 28, 'Feb 2010 should have 28 days'); assert.equal(moment([2100, 1]).daysInMonth(), 28, 'Feb 2100 should have 28 days'); assert.equal(moment([2008, 1]).daysInMonth(), 29, 'Feb 2008 should have 29 days'); assert.equal(moment([2000, 1]).daysInMonth(), 29, 'Feb 2000 should have 29 days'); });
/*! * sweetalert2 v8.11.4 * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Sweetalert2 = factory()); }(this, (function () { 'use strict'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } var consolePrefix = 'SweetAlert2:'; /** * Filter the unique values into a new array * @param arr */ var uniqueArray = function uniqueArray(arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (result.indexOf(arr[i]) === -1) { result.push(arr[i]); } } return result; }; /** * Returns the array ob object values (Object.values isn't supported in IE11) * @param obj */ var objectValues = function objectValues(obj) { return Object.keys(obj).map(function (key) { return obj[key]; }); }; /** * Convert NodeList to Array * @param nodeList */ var toArray = function toArray(nodeList) { return Array.prototype.slice.call(nodeList); }; /** * Standardise console warnings * @param message */ var warn = function warn(message) { console.warn("".concat(consolePrefix, " ").concat(message)); }; /** * Standardise console errors * @param message */ var error = function error(message) { console.error("".concat(consolePrefix, " ").concat(message)); }; /** * Private global state for `warnOnce` * @type {Array} * @private */ var previousWarnOnceMessages = []; /** * Show a console warning, but only if it hasn't already been shown * @param message */ var warnOnce = function warnOnce(message) { if (!(previousWarnOnceMessages.indexOf(message) !== -1)) { previousWarnOnceMessages.push(message); warn(message); } }; /** * Show a one-time console warning about deprecated params/methods */ var warnAboutDepreation = function warnAboutDepreation(deprecatedParam, useInstead) { warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead.")); }; /** * If `arg` is a function, call it (with no arguments or context) and return the result. * Otherwise, just pass the value through * @param arg */ var callIfFunction = function callIfFunction(arg) { return typeof arg === 'function' ? arg() : arg; }; var isPromise = function isPromise(arg) { return arg && Promise.resolve(arg) === arg; }; var DismissReason = Object.freeze({ cancel: 'cancel', backdrop: 'backdrop', close: 'close', esc: 'esc', timer: 'timer' }); var argsToParams = function argsToParams(args) { var params = {}; switch (_typeof(args[0])) { case 'object': _extends(params, args[0]); break; default: ['title', 'html', 'type'].forEach(function (name, index) { switch (_typeof(args[index])) { case 'string': params[name] = args[index]; break; case 'undefined': break; default: error("Unexpected type of ".concat(name, "! Expected \"string\", got ").concat(_typeof(args[index]))); } }); } return params; }; var swalPrefix = 'swal2-'; var prefix = function prefix(items) { var result = {}; for (var i in items) { result[items[i]] = swalPrefix + items[i]; } return result; }; var swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'toast', 'toast-shown', 'toast-column', 'fade', 'show', 'hide', 'noanimation', 'close', 'title', 'header', 'content', 'actions', 'confirm', 'cancel', 'footer', 'icon', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl']); var iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']); var states = { previousBodyPadding: null }; var hasClass = function hasClass(elem, className) { return elem.classList.contains(className); }; var applyCustomClass = function applyCustomClass(elem, customClass, className) { // Clean up previous custom classes toArray(elem.classList).forEach(function (className) { if (!(objectValues(swalClasses).indexOf(className) !== -1) && !(objectValues(iconTypes).indexOf(className) !== -1)) { elem.classList.remove(className); } }); if (customClass && customClass[className]) { addClass(elem, customClass[className]); } }; function getInput(content, inputType) { if (!inputType) { return null; } switch (inputType) { case 'select': case 'textarea': case 'file': return getChildByClass(content, swalClasses[inputType]); case 'checkbox': return content.querySelector(".".concat(swalClasses.checkbox, " input")); case 'radio': return content.querySelector(".".concat(swalClasses.radio, " input:checked")) || content.querySelector(".".concat(swalClasses.radio, " input:first-child")); case 'range': return content.querySelector(".".concat(swalClasses.range, " input")); default: return getChildByClass(content, swalClasses.input); } } var focusInput = function focusInput(input) { input.focus(); // place cursor at end of text in text input if (input.type !== 'file') { // http://stackoverflow.com/a/2345915 var val = input.value; input.value = ''; input.value = val; } }; var toggleClass = function toggleClass(target, classList, condition) { if (!target || !classList) { return; } if (typeof classList === 'string') { classList = classList.split(/\s+/).filter(Boolean); } classList.forEach(function (className) { if (target.forEach) { target.forEach(function (elem) { condition ? elem.classList.add(className) : elem.classList.remove(className); }); } else { condition ? target.classList.add(className) : target.classList.remove(className); } }); }; var addClass = function addClass(target, classList) { toggleClass(target, classList, true); }; var removeClass = function removeClass(target, classList) { toggleClass(target, classList, false); }; var getChildByClass = function getChildByClass(elem, className) { for (var i = 0; i < elem.childNodes.length; i++) { if (hasClass(elem.childNodes[i], className)) { return elem.childNodes[i]; } } }; var applyNumericalStyle = function applyNumericalStyle(elem, property, value) { if (value || parseInt(value) === 0) { elem.style[property] = typeof value === 'number' ? value + 'px' : value; } else { elem.style.removeProperty(property); } }; var show = function show(elem) { var display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex'; elem.style.opacity = ''; elem.style.display = display; }; var hide = function hide(elem) { elem.style.opacity = ''; elem.style.display = 'none'; }; var toggle = function toggle(elem, condition, display) { condition ? show(elem, display) : hide(elem); }; // borrowed from jquery $(elem).is(':visible') implementation var isVisible = function isVisible(elem) { return !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length)); }; var isScrollable = function isScrollable(elem) { return !!(elem.scrollHeight > elem.clientHeight); }; // borrowed from https://stackoverflow.com/a/46352119 var hasCssAnimation = function hasCssAnimation(elem) { var style = window.getComputedStyle(elem); var animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0'); var transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0'); return animDuration > 0 || transDuration > 0; }; var contains = function contains(haystack, needle) { if (typeof haystack.contains === 'function') { return haystack.contains(needle); } }; var getContainer = function getContainer() { return document.body.querySelector('.' + swalClasses.container); }; var elementBySelector = function elementBySelector(selectorString) { var container = getContainer(); return container ? container.querySelector(selectorString) : null; }; var elementByClass = function elementByClass(className) { return elementBySelector('.' + className); }; var getPopup = function getPopup() { return elementByClass(swalClasses.popup); }; var getIcons = function getIcons() { var popup = getPopup(); return toArray(popup.querySelectorAll('.' + swalClasses.icon)); }; var getIcon = function getIcon() { var visibleIcon = getIcons().filter(function (icon) { return isVisible(icon); }); return visibleIcon.length ? visibleIcon[0] : null; }; var getTitle = function getTitle() { return elementByClass(swalClasses.title); }; var getContent = function getContent() { return elementByClass(swalClasses.content); }; var getImage = function getImage() { return elementByClass(swalClasses.image); }; var getProgressSteps = function getProgressSteps() { return elementByClass(swalClasses['progress-steps']); }; var getValidationMessage = function getValidationMessage() { return elementByClass(swalClasses['validation-message']); }; var getConfirmButton = function getConfirmButton() { return elementBySelector('.' + swalClasses.actions + ' .' + swalClasses.confirm); }; var getCancelButton = function getCancelButton() { return elementBySelector('.' + swalClasses.actions + ' .' + swalClasses.cancel); }; var getActions = function getActions() { return elementByClass(swalClasses.actions); }; var getHeader = function getHeader() { return elementByClass(swalClasses.header); }; var getFooter = function getFooter() { return elementByClass(swalClasses.footer); }; var getCloseButton = function getCloseButton() { return elementByClass(swalClasses.close); }; var getFocusableElements = function getFocusableElements() { var focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex .sort(function (a, b) { a = parseInt(a.getAttribute('tabindex')); b = parseInt(b.getAttribute('tabindex')); if (a > b) { return 1; } else if (a < b) { return -1; } return 0; }); // https://github.com/jkup/focusable/blob/master/index.js var otherFocusableElements = toArray(getPopup().querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable], audio[controls], video[controls]')).filter(function (el) { return el.getAttribute('tabindex') !== '-1'; }); return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(function (el) { return isVisible(el); }); }; var isModal = function isModal() { return !isToast() && !document.body.classList.contains(swalClasses['no-backdrop']); }; var isToast = function isToast() { return document.body.classList.contains(swalClasses['toast-shown']); }; var isLoading = function isLoading() { return getPopup().hasAttribute('data-loading'); }; // Detect Node env var isNodeEnv = function isNodeEnv() { return typeof window === 'undefined' || typeof document === 'undefined'; }; var sweetHTML = "\n <div aria-labelledby=\"".concat(swalClasses.title, "\" aria-describedby=\"").concat(swalClasses.content, "\" class=\"").concat(swalClasses.popup, "\" tabindex=\"-1\">\n <div class=\"").concat(swalClasses.header, "\">\n <ul class=\"").concat(swalClasses['progress-steps'], "\"></ul>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.error, "\">\n <span class=\"swal2-x-mark\"><span class=\"swal2-x-mark-line-left\"></span><span class=\"swal2-x-mark-line-right\"></span></span>\n </div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.question, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.warning, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.info, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.success, "\">\n <div class=\"swal2-success-circular-line-left\"></div>\n <span class=\"swal2-success-line-tip\"></span> <span class=\"swal2-success-line-long\"></span>\n <div class=\"swal2-success-ring\"></div> <div class=\"swal2-success-fix\"></div>\n <div class=\"swal2-success-circular-line-right\"></div>\n </div>\n <img class=\"").concat(swalClasses.image, "\" />\n <h2 class=\"").concat(swalClasses.title, "\" id=\"").concat(swalClasses.title, "\"></h2>\n <button type=\"button\" class=\"").concat(swalClasses.close, "\">&times;</button>\n </div>\n <div class=\"").concat(swalClasses.content, "\">\n <div id=\"").concat(swalClasses.content, "\"></div>\n <input class=\"").concat(swalClasses.input, "\" />\n <input type=\"file\" class=\"").concat(swalClasses.file, "\" />\n <div class=\"").concat(swalClasses.range, "\">\n <input type=\"range\" />\n <output></output>\n </div>\n <select class=\"").concat(swalClasses.select, "\"></select>\n <div class=\"").concat(swalClasses.radio, "\"></div>\n <label for=\"").concat(swalClasses.checkbox, "\" class=\"").concat(swalClasses.checkbox, "\">\n <input type=\"checkbox\" />\n <span class=\"").concat(swalClasses.label, "\"></span>\n </label>\n <textarea class=\"").concat(swalClasses.textarea, "\"></textarea>\n <div class=\"").concat(swalClasses['validation-message'], "\" id=\"").concat(swalClasses['validation-message'], "\"></div>\n </div>\n <div class=\"").concat(swalClasses.actions, "\">\n <button type=\"button\" class=\"").concat(swalClasses.confirm, "\">OK</button>\n <button type=\"button\" class=\"").concat(swalClasses.cancel, "\">Cancel</button>\n </div>\n <div class=\"").concat(swalClasses.footer, "\">\n </div>\n </div>\n").replace(/(^|\n)\s*/g, ''); var resetOldContainer = function resetOldContainer() { var oldContainer = getContainer(); if (!oldContainer) { return; } oldContainer.parentNode.removeChild(oldContainer); removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]); }; var oldInputVal; // IE11 workaround, see #1109 for details var resetValidationMessage = function resetValidationMessage(e) { if (Swal.isVisible() && oldInputVal !== e.target.value) { Swal.resetValidationMessage(); } oldInputVal = e.target.value; }; var addInputChangeListeners = function addInputChangeListeners() { var content = getContent(); var input = getChildByClass(content, swalClasses.input); var file = getChildByClass(content, swalClasses.file); var range = content.querySelector(".".concat(swalClasses.range, " input")); var rangeOutput = content.querySelector(".".concat(swalClasses.range, " output")); var select = getChildByClass(content, swalClasses.select); var checkbox = content.querySelector(".".concat(swalClasses.checkbox, " input")); var textarea = getChildByClass(content, swalClasses.textarea); input.oninput = resetValidationMessage; file.onchange = resetValidationMessage; select.onchange = resetValidationMessage; checkbox.onchange = resetValidationMessage; textarea.oninput = resetValidationMessage; range.oninput = function (e) { resetValidationMessage(e); rangeOutput.value = range.value; }; range.onchange = function (e) { resetValidationMessage(e); range.nextSibling.value = range.value; }; }; var getTarget = function getTarget(target) { return typeof target === 'string' ? document.querySelector(target) : target; }; var setupAccessibility = function setupAccessibility(params) { var popup = getPopup(); popup.setAttribute('role', params.toast ? 'alert' : 'dialog'); popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive'); if (!params.toast) { popup.setAttribute('aria-modal', 'true'); } }; var setupRTL = function setupRTL(targetElement) { if (window.getComputedStyle(targetElement).direction === 'rtl') { addClass(getContainer(), swalClasses.rtl); } }; /* * Add modal + backdrop to DOM */ var init = function init(params) { // Clean up the old popup container if it exists resetOldContainer(); /* istanbul ignore if */ if (isNodeEnv()) { error('SweetAlert2 requires document to initialize'); return; } var container = document.createElement('div'); container.className = swalClasses.container; container.innerHTML = sweetHTML; var targetElement = getTarget(params.target); targetElement.appendChild(container); setupAccessibility(params); setupRTL(targetElement); addInputChangeListeners(); }; var parseHtmlToContainer = function parseHtmlToContainer(param, target) { // DOM element if (param instanceof HTMLElement) { target.appendChild(param); // JQuery element(s) } else if (_typeof(param) === 'object') { handleJqueryElem(target, param); // Plain string } else if (param) { target.innerHTML = param; } }; var handleJqueryElem = function handleJqueryElem(target, elem) { target.innerHTML = ''; if (0 in elem) { for (var i = 0; i in elem; i++) { target.appendChild(elem[i].cloneNode(true)); } } else { target.appendChild(elem.cloneNode(true)); } }; var animationEndEvent = function () { // Prevent run in Node env /* istanbul ignore if */ if (isNodeEnv()) { return false; } var testEl = document.createElement('div'); var transEndEventNames = { 'WebkitAnimation': 'webkitAnimationEnd', 'OAnimation': 'oAnimationEnd oanimationend', 'animation': 'animationend' }; for (var i in transEndEventNames) { if (transEndEventNames.hasOwnProperty(i) && typeof testEl.style[i] !== 'undefined') { return transEndEventNames[i]; } } return false; }(); // Measure width of scrollbar // https://github.com/twbs/bootstrap/blob/master/js/modal.js#L279-L286 var measureScrollbar = function measureScrollbar() { var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints; if (supportsTouch) { return 0; } var scrollDiv = document.createElement('div'); scrollDiv.style.width = '50px'; scrollDiv.style.height = '50px'; scrollDiv.style.overflow = 'scroll'; document.body.appendChild(scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); return scrollbarWidth; }; function handleButtonsStyling(confirmButton, cancelButton, params) { addClass([confirmButton, cancelButton], swalClasses.styled); // Buttons background colors if (params.confirmButtonColor) { confirmButton.style.backgroundColor = params.confirmButtonColor; } if (params.cancelButtonColor) { cancelButton.style.backgroundColor = params.cancelButtonColor; } // Loading state var confirmButtonBackgroundColor = window.getComputedStyle(confirmButton).getPropertyValue('background-color'); confirmButton.style.borderLeftColor = confirmButtonBackgroundColor; confirmButton.style.borderRightColor = confirmButtonBackgroundColor; } function renderButton(button, buttonType, params) { toggle(button, params['showC' + buttonType.substring(1) + 'Button'], 'inline-block'); button.innerHTML = params[buttonType + 'ButtonText']; // Set caption text button.setAttribute('aria-label', params[buttonType + 'ButtonAriaLabel']); // ARIA label // Add buttons custom classes button.className = swalClasses[buttonType]; applyCustomClass(button, params.customClass, buttonType + 'Button'); addClass(button, params[buttonType + 'ButtonClass']); } var renderActions = function renderActions(instance, params) { var actions = getActions(); var confirmButton = getConfirmButton(); var cancelButton = getCancelButton(); // Actions (buttons) wrapper if (!params.showConfirmButton && !params.showCancelButton) { hide(actions); } else { show(actions); } // Custom class applyCustomClass(actions, params.customClass, 'actions'); // Render confirm button renderButton(confirmButton, 'confirm', params); // render Cancel Button renderButton(cancelButton, 'cancel', params); if (params.buttonsStyling) { handleButtonsStyling(confirmButton, cancelButton, params); } else { removeClass([confirmButton, cancelButton], swalClasses.styled); confirmButton.style.backgroundColor = confirmButton.style.borderLeftColor = confirmButton.style.borderRightColor = ''; cancelButton.style.backgroundColor = cancelButton.style.borderLeftColor = cancelButton.style.borderRightColor = ''; } }; function handleBackdropParam(container, backdrop) { if (typeof backdrop === 'string') { container.style.background = backdrop; } else if (!backdrop) { addClass([document.documentElement, document.body], swalClasses['no-backdrop']); } } function handlePositionParam(container, position) { if (position in swalClasses) { addClass(container, swalClasses[position]); } else { warn('The "position" parameter is not valid, defaulting to "center"'); addClass(container, swalClasses.center); } } function handleGrowParam(container, grow) { if (grow && typeof grow === 'string') { var growClass = 'grow-' + grow; if (growClass in swalClasses) { addClass(container, swalClasses[growClass]); } } } var renderContainer = function renderContainer(instance, params) { var container = getContainer(); if (!container) { return; } handleBackdropParam(container, params.backdrop); if (!params.backdrop && params.allowOutsideClick) { warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`'); } handlePositionParam(container, params.position); handleGrowParam(container, params.grow); // Custom class applyCustomClass(container, params.customClass, 'container'); if (params.customContainerClass) { // @deprecated addClass(container, params.customContainerClass); } }; /** * This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')` * This is the approach that Babel will probably take to implement private methods/fields * https://github.com/tc39/proposal-private-methods * https://github.com/babel/babel/pull/7555 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module* * then we can use that language feature. */ var privateProps = { promise: new WeakMap(), innerParams: new WeakMap(), domCache: new WeakMap() }; var renderInput = function renderInput(instance, params) { var innerParams = privateProps.innerParams.get(instance); var rerender = !innerParams || params.input !== innerParams.input; var content = getContent(); var inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea']; for (var i = 0; i < inputTypes.length; i++) { var inputClass = swalClasses[inputTypes[i]]; var inputContainer = getChildByClass(content, inputClass); // set attributes setAttributes(inputTypes[i], params.inputAttributes); // set class setClass(inputContainer, inputClass, params); rerender && hide(inputContainer); } if (!params.input) { return; } if (!renderInputType[params.input]) { return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\"")); } if (rerender) { var input = renderInputType[params.input](params); show(input); } }; var removeAttributes = function removeAttributes(input) { for (var i = 0; i < input.attributes.length; i++) { var attrName = input.attributes[i].name; if (!(['type', 'value', 'style'].indexOf(attrName) !== -1)) { input.removeAttribute(attrName); } } }; var setAttributes = function setAttributes(inputType, inputAttributes) { var input = getInput(getContent(), inputType); if (!input) { return; } removeAttributes(input); for (var attr in inputAttributes) { // Do not set a placeholder for <input type="range"> // it'll crash Edge, #1298 if (inputType === 'range' && attr === 'placeholder') { continue; } input.setAttribute(attr, inputAttributes[attr]); } }; var setClass = function setClass(inputContainer, inputClass, params) { inputContainer.className = inputClass; if (params.inputClass) { addClass(inputContainer, params.inputClass); } if (params.customClass) { addClass(inputContainer, params.customClass.input); } }; var setInputPlaceholder = function setInputPlaceholder(input, params) { if (!input.placeholder || params.inputPlaceholder) { input.placeholder = params.inputPlaceholder; } }; var renderInputType = {}; renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = function (params) { var input = getChildByClass(getContent(), swalClasses.input); if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') { input.value = params.inputValue; } else if (!isPromise(params.inputValue)) { warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(_typeof(params.inputValue), "\"")); } setInputPlaceholder(input, params); input.type = params.input; return input; }; renderInputType.file = function (params) { var input = getChildByClass(getContent(), swalClasses.file); setInputPlaceholder(input, params); input.type = params.input; return input; }; renderInputType.range = function (params) { var range = getChildByClass(getContent(), swalClasses.range); var rangeInput = range.querySelector('input'); var rangeOutput = range.querySelector('output'); rangeInput.value = params.inputValue; rangeInput.type = params.input; rangeOutput.value = params.inputValue; return range; }; renderInputType.select = function (params) { var select = getChildByClass(getContent(), swalClasses.select); select.innerHTML = ''; if (params.inputPlaceholder) { var placeholder = document.createElement('option'); placeholder.innerHTML = params.inputPlaceholder; placeholder.value = ''; placeholder.disabled = true; placeholder.selected = true; select.appendChild(placeholder); } return select; }; renderInputType.radio = function () { var radio = getChildByClass(getContent(), swalClasses.radio); radio.innerHTML = ''; return radio; }; renderInputType.checkbox = function (params) { var checkbox = getChildByClass(getContent(), swalClasses.checkbox); var checkboxInput = getInput(getContent(), 'checkbox'); checkboxInput.type = 'checkbox'; checkboxInput.value = 1; checkboxInput.id = swalClasses.checkbox; checkboxInput.checked = Boolean(params.inputValue); var label = checkbox.querySelector('span'); label.innerHTML = params.inputPlaceholder; return checkbox; }; renderInputType.textarea = function (params) { var textarea = getChildByClass(getContent(), swalClasses.textarea); textarea.value = params.inputValue; setInputPlaceholder(textarea, params); return textarea; }; var renderContent = function renderContent(instance, params) { var content = getContent().querySelector('#' + swalClasses.content); // Content as HTML if (params.html) { parseHtmlToContainer(params.html, content); show(content, 'block'); // Content as plain text } else if (params.text) { content.textContent = params.text; show(content, 'block'); // No content } else { hide(content); } renderInput(instance, params); // Custom class applyCustomClass(getContent(), params.customClass, 'content'); }; var renderFooter = function renderFooter(instance, params) { var footer = getFooter(); toggle(footer, params.footer); if (params.footer) { parseHtmlToContainer(params.footer, footer); } // Custom class applyCustomClass(footer, params.customClass, 'footer'); }; var renderCloseButton = function renderCloseButton(instance, params) { var closeButton = getCloseButton(); // Custom class applyCustomClass(closeButton, params.customClass, 'closeButton'); toggle(closeButton, params.showCloseButton); closeButton.setAttribute('aria-label', params.closeButtonAriaLabel); }; var renderIcon = function renderIcon(instance, params) { var innerParams = privateProps.innerParams.get(instance); // if the icon with the given type already rendered, // apply the custom class without re-rendering the icon if (innerParams && params.type === innerParams.type && getIcon()) { applyCustomClass(getIcon(), params.customClass, 'icon'); return; } hideAllIcons(); if (!params.type) { return; } adjustSuccessIconBackgoundColor(); if (Object.keys(iconTypes).indexOf(params.type) !== -1) { var icon = elementBySelector(".".concat(swalClasses.icon, ".").concat(iconTypes[params.type])); show(icon); // Custom class applyCustomClass(icon, params.customClass, 'icon'); // Animate icon toggleClass(icon, "swal2-animate-".concat(params.type, "-icon"), params.animation); } else { error("Unknown type! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.type, "\"")); } }; var hideAllIcons = function hideAllIcons() { var icons = getIcons(); for (var i = 0; i < icons.length; i++) { hide(icons[i]); } }; // Adjust success icon background color to match the popup background color var adjustSuccessIconBackgoundColor = function adjustSuccessIconBackgoundColor() { var popup = getPopup(); var popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color'); var successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix'); for (var i = 0; i < successIconParts.length; i++) { successIconParts[i].style.backgroundColor = popupBackgroundColor; } }; var renderImage = function renderImage(instance, params) { var image = getImage(); if (!params.imageUrl) { return hide(image); } show(image); // Src, alt image.setAttribute('src', params.imageUrl); image.setAttribute('alt', params.imageAlt); // Width, height applyNumericalStyle(image, 'width', params.imageWidth); applyNumericalStyle(image, 'height', params.imageHeight); // Class image.className = swalClasses.image; applyCustomClass(image, params.customClass, 'image'); if (params.imageClass) { addClass(image, params.imageClass); } }; var createStepElement = function createStepElement(step) { var stepEl = document.createElement('li'); addClass(stepEl, swalClasses['progress-step']); stepEl.innerHTML = step; return stepEl; }; var createLineElement = function createLineElement(params) { var lineEl = document.createElement('li'); addClass(lineEl, swalClasses['progress-step-line']); if (params.progressStepsDistance) { lineEl.style.width = params.progressStepsDistance; } return lineEl; }; var renderProgressSteps = function renderProgressSteps(instance, params) { var progressStepsContainer = getProgressSteps(); if (!params.progressSteps || params.progressSteps.length === 0) { return hide(progressStepsContainer); } show(progressStepsContainer); progressStepsContainer.innerHTML = ''; var currentProgressStep = parseInt(params.currentProgressStep === null ? Swal.getQueueStep() : params.currentProgressStep); if (currentProgressStep >= params.progressSteps.length) { warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)'); } params.progressSteps.forEach(function (step, index) { var stepEl = createStepElement(step); progressStepsContainer.appendChild(stepEl); if (index === currentProgressStep) { addClass(stepEl, swalClasses['active-progress-step']); } if (index !== params.progressSteps.length - 1) { var lineEl = createLineElement(step); progressStepsContainer.appendChild(lineEl); } }); }; var renderTitle = function renderTitle(instance, params) { var title = getTitle(); toggle(title, params.title || params.titleText); if (params.title) { parseHtmlToContainer(params.title, title); } if (params.titleText) { title.innerText = params.titleText; } // Custom class applyCustomClass(title, params.customClass, 'title'); }; var renderHeader = function renderHeader(instance, params) { var header = getHeader(); // Custom class applyCustomClass(header, params.customClass, 'header'); // Progress steps renderProgressSteps(instance, params); // Icon renderIcon(instance, params); // Image renderImage(instance, params); // Title renderTitle(instance, params); // Close button renderCloseButton(instance, params); }; var renderPopup = function renderPopup(instance, params) { var popup = getPopup(); // Width applyNumericalStyle(popup, 'width', params.width); // Padding applyNumericalStyle(popup, 'padding', params.padding); // Background if (params.background) { popup.style.background = params.background; } // Default Class popup.className = swalClasses.popup; if (params.toast) { addClass([document.documentElement, document.body], swalClasses['toast-shown']); addClass(popup, swalClasses.toast); } else { addClass(popup, swalClasses.modal); } // Custom class applyCustomClass(popup, params.customClass, 'popup'); if (typeof params.customClass === 'string') { addClass(popup, params.customClass); } // CSS animation toggleClass(popup, swalClasses.noanimation, !params.animation); }; var render = function render(instance, params) { renderPopup(instance, params); renderContainer(instance, params); renderHeader(instance, params); renderContent(instance, params); renderActions(instance, params); renderFooter(instance, params); }; /* * Global function to determine if SweetAlert2 popup is shown */ var isVisible$1 = function isVisible$$1() { return isVisible(getPopup()); }; /* * Global function to click 'Confirm' button */ var clickConfirm = function clickConfirm() { return getConfirmButton() && getConfirmButton().click(); }; /* * Global function to click 'Cancel' button */ var clickCancel = function clickCancel() { return getCancelButton() && getCancelButton().click(); }; function fire() { var Swal = this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _construct(Swal, args); } /** * Returns an extended version of `Swal` containing `params` as defaults. * Useful for reusing Swal configuration. * * For example: * * Before: * const textPromptOptions = { input: 'text', showCancelButton: true } * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' }) * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' }) * * After: * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true }) * const {value: firstName} = await TextPrompt('What is your first name?') * const {value: lastName} = await TextPrompt('What is your last name?') * * @param mixinParams */ function mixin(mixinParams) { var MixinSwal = /*#__PURE__*/ function (_this) { _inherits(MixinSwal, _this); function MixinSwal() { _classCallCheck(this, MixinSwal); return _possibleConstructorReturn(this, _getPrototypeOf(MixinSwal).apply(this, arguments)); } _createClass(MixinSwal, [{ key: "_main", value: function _main(params) { return _get(_getPrototypeOf(MixinSwal.prototype), "_main", this).call(this, _extends({}, mixinParams, params)); } }]); return MixinSwal; }(this); return MixinSwal; } // private global state for the queue feature var currentSteps = []; /* * Global function for chaining sweetAlert popups */ var queue = function queue(steps) { var Swal = this; currentSteps = steps; var resetAndResolve = function resetAndResolve(resolve, value) { currentSteps = []; document.body.removeAttribute('data-swal2-queue-step'); resolve(value); }; var queueResult = []; return new Promise(function (resolve) { (function step(i, callback) { if (i < currentSteps.length) { document.body.setAttribute('data-swal2-queue-step', i); Swal.fire(currentSteps[i]).then(function (result) { if (typeof result.value !== 'undefined') { queueResult.push(result.value); step(i + 1, callback); } else { resetAndResolve(resolve, { dismiss: result.dismiss }); } }); } else { resetAndResolve(resolve, { value: queueResult }); } })(0); }); }; /* * Global function for getting the index of current popup in queue */ var getQueueStep = function getQueueStep() { return document.body.getAttribute('data-swal2-queue-step'); }; /* * Global function for inserting a popup to the queue */ var insertQueueStep = function insertQueueStep(step, index) { if (index && index < currentSteps.length) { return currentSteps.splice(index, 0, step); } return currentSteps.push(step); }; /* * Global function for deleting a popup from the queue */ var deleteQueueStep = function deleteQueueStep(index) { if (typeof currentSteps[index] !== 'undefined') { currentSteps.splice(index, 1); } }; /** * Show spinner instead of Confirm button and disable Cancel button */ var showLoading = function showLoading() { var popup = getPopup(); if (!popup) { Swal.fire(''); } popup = getPopup(); var actions = getActions(); var confirmButton = getConfirmButton(); var cancelButton = getCancelButton(); show(actions); show(confirmButton); addClass([popup, actions], swalClasses.loading); confirmButton.disabled = true; cancelButton.disabled = true; popup.setAttribute('data-loading', true); popup.setAttribute('aria-busy', true); popup.focus(); }; var RESTORE_FOCUS_TIMEOUT = 100; var globalState = {}; var focusPreviousActiveElement = function focusPreviousActiveElement() { if (globalState.previousActiveElement && globalState.previousActiveElement.focus) { globalState.previousActiveElement.focus(); globalState.previousActiveElement = null; } else if (document.body) { document.body.focus(); } }; // Restore previous active (focused) element var restoreActiveElement = function restoreActiveElement() { return new Promise(function (resolve) { var x = window.scrollX; var y = window.scrollY; globalState.restoreFocusTimeout = setTimeout(function () { focusPreviousActiveElement(); resolve(); }, RESTORE_FOCUS_TIMEOUT); // issues/900 if (typeof x !== 'undefined' && typeof y !== 'undefined') { // IE doesn't have scrollX/scrollY support window.scrollTo(x, y); } }); }; /** * If `timer` parameter is set, returns number of milliseconds of timer remained. * Otherwise, returns undefined. */ var getTimerLeft = function getTimerLeft() { return globalState.timeout && globalState.timeout.getTimerLeft(); }; /** * Stop timer. Returns number of milliseconds of timer remained. * If `timer` parameter isn't set, returns undefined. */ var stopTimer = function stopTimer() { return globalState.timeout && globalState.timeout.stop(); }; /** * Resume timer. Returns number of milliseconds of timer remained. * If `timer` parameter isn't set, returns undefined. */ var resumeTimer = function resumeTimer() { return globalState.timeout && globalState.timeout.start(); }; /** * Resume timer. Returns number of milliseconds of timer remained. * If `timer` parameter isn't set, returns undefined. */ var toggleTimer = function toggleTimer() { var timer = globalState.timeout; return timer && (timer.running ? timer.stop() : timer.start()); }; /** * Increase timer. Returns number of milliseconds of an updated timer. * If `timer` parameter isn't set, returns undefined. */ var increaseTimer = function increaseTimer(n) { return globalState.timeout && globalState.timeout.increase(n); }; /** * Check if timer is running. Returns true if timer is running * or false if timer is paused or stopped. * If `timer` parameter isn't set, returns undefined */ var isTimerRunning = function isTimerRunning() { return globalState.timeout && globalState.timeout.isRunning(); }; var defaultParams = { title: '', titleText: '', text: '', html: '', footer: '', type: null, toast: false, customClass: '', customContainerClass: '', target: 'body', backdrop: true, animation: true, heightAuto: true, allowOutsideClick: true, allowEscapeKey: true, allowEnterKey: true, stopKeydownPropagation: true, keydownListenerCapture: false, showConfirmButton: true, showCancelButton: false, preConfirm: null, confirmButtonText: 'OK', confirmButtonAriaLabel: '', confirmButtonColor: null, confirmButtonClass: '', cancelButtonText: 'Cancel', cancelButtonAriaLabel: '', cancelButtonColor: null, cancelButtonClass: '', buttonsStyling: true, reverseButtons: false, focusConfirm: true, focusCancel: false, showCloseButton: false, closeButtonAriaLabel: 'Close this dialog', showLoaderOnConfirm: false, imageUrl: null, imageWidth: null, imageHeight: null, imageAlt: '', imageClass: '', timer: null, width: null, padding: null, background: null, input: null, inputPlaceholder: '', inputValue: '', inputOptions: {}, inputAutoTrim: true, inputClass: '', inputAttributes: {}, inputValidator: null, validationMessage: null, grow: false, position: 'center', progressSteps: [], currentProgressStep: null, progressStepsDistance: null, onBeforeOpen: null, onAfterClose: null, onOpen: null, onClose: null, scrollbarPadding: true }; var updatableParams = ['title', 'titleText', 'text', 'html', 'type', 'customClass', 'showConfirmButton', 'showCancelButton', 'confirmButtonText', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonClass', 'cancelButtonText', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonClass', 'buttonsStyling', 'reverseButtons', 'imageUrl', 'imageWidth', 'imageHeigth', 'imageAlt', 'imageClass', 'progressSteps', 'currentProgressStep']; var deprecatedParams = { customContainerClass: 'customClass', confirmButtonClass: 'customClass', cancelButtonClass: 'customClass', imageClass: 'customClass', inputClass: 'customClass' }; var toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusCancel', 'heightAuto', 'keydownListenerCapture']; /** * Is valid parameter * @param {String} paramName */ var isValidParameter = function isValidParameter(paramName) { return defaultParams.hasOwnProperty(paramName); }; /** * Is valid parameter for Swal.update() method * @param {String} paramName */ var isUpdatableParameter = function isUpdatableParameter(paramName) { return updatableParams.indexOf(paramName) !== -1; }; /** * Is deprecated parameter * @param {String} paramName */ var isDeprecatedParameter = function isDeprecatedParameter(paramName) { return deprecatedParams[paramName]; }; var checkIfParamIsValid = function checkIfParamIsValid(param) { if (!isValidParameter(param)) { warn("Unknown parameter \"".concat(param, "\"")); } }; var checkIfToastParamIsValid = function checkIfToastParamIsValid(param) { if (toastIncompatibleParams.indexOf(param) !== -1) { warn("The parameter \"".concat(param, "\" is incompatible with toasts")); } }; var checkIfParamIsDeprecated = function checkIfParamIsDeprecated(param) { if (isDeprecatedParameter(param)) { warnAboutDepreation(param, isDeprecatedParameter(param)); } }; /** * Show relevant warnings for given params * * @param params */ var showWarningsForParams = function showWarningsForParams(params) { for (var param in params) { checkIfParamIsValid(param); if (params.toast) { checkIfToastParamIsValid(param); } checkIfParamIsDeprecated(); } }; var staticMethods = Object.freeze({ isValidParameter: isValidParameter, isUpdatableParameter: isUpdatableParameter, isDeprecatedParameter: isDeprecatedParameter, argsToParams: argsToParams, isVisible: isVisible$1, clickConfirm: clickConfirm, clickCancel: clickCancel, getContainer: getContainer, getPopup: getPopup, getTitle: getTitle, getContent: getContent, getImage: getImage, getIcon: getIcon, getIcons: getIcons, getCloseButton: getCloseButton, getActions: getActions, getConfirmButton: getConfirmButton, getCancelButton: getCancelButton, getHeader: getHeader, getFooter: getFooter, getFocusableElements: getFocusableElements, getValidationMessage: getValidationMessage, isLoading: isLoading, fire: fire, mixin: mixin, queue: queue, getQueueStep: getQueueStep, insertQueueStep: insertQueueStep, deleteQueueStep: deleteQueueStep, showLoading: showLoading, enableLoading: showLoading, getTimerLeft: getTimerLeft, stopTimer: stopTimer, resumeTimer: resumeTimer, toggleTimer: toggleTimer, increaseTimer: increaseTimer, isTimerRunning: isTimerRunning }); /** * Enables buttons and hide loader. */ function hideLoading() { var innerParams = privateProps.innerParams.get(this); var domCache = privateProps.domCache.get(this); if (!innerParams.showConfirmButton) { hide(domCache.confirmButton); if (!innerParams.showCancelButton) { hide(domCache.actions); } } removeClass([domCache.popup, domCache.actions], swalClasses.loading); domCache.popup.removeAttribute('aria-busy'); domCache.popup.removeAttribute('data-loading'); domCache.confirmButton.disabled = false; domCache.cancelButton.disabled = false; } function getInput$1(instance) { var innerParams = privateProps.innerParams.get(instance || this); var domCache = privateProps.domCache.get(instance || this); return getInput(domCache.content, innerParams.input); } var fixScrollbar = function fixScrollbar() { // for queues, do not do this more than once if (states.previousBodyPadding !== null) { return; } // if the body has overflow if (document.body.scrollHeight > window.innerHeight) { // add padding so the content doesn't shift after removal of scrollbar states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right')); document.body.style.paddingRight = states.previousBodyPadding + measureScrollbar() + 'px'; } }; var undoScrollbar = function undoScrollbar() { if (states.previousBodyPadding !== null) { document.body.style.paddingRight = states.previousBodyPadding + 'px'; states.previousBodyPadding = null; } }; /* istanbul ignore next */ var iOSfix = function iOSfix() { var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; if (iOS && !hasClass(document.body, swalClasses.iosfix)) { var offset = document.body.scrollTop; document.body.style.top = offset * -1 + 'px'; addClass(document.body, swalClasses.iosfix); lockBodyScroll(); } }; var lockBodyScroll = function lockBodyScroll() { // #1246 var container = getContainer(); var preventTouchMove; container.ontouchstart = function (e) { preventTouchMove = e.target === container || !isScrollable(container); }; container.ontouchmove = function (e) { if (preventTouchMove) { e.preventDefault(); e.stopPropagation(); } }; }; /* istanbul ignore next */ var undoIOSfix = function undoIOSfix() { if (hasClass(document.body, swalClasses.iosfix)) { var offset = parseInt(document.body.style.top, 10); removeClass(document.body, swalClasses.iosfix); document.body.style.top = ''; document.body.scrollTop = offset * -1; } }; var isIE11 = function isIE11() { return !!window.MSInputMethodContext && !!document.documentMode; }; // Fix IE11 centering sweetalert2/issues/933 /* istanbul ignore next */ var fixVerticalPositionIE = function fixVerticalPositionIE() { var container = getContainer(); var popup = getPopup(); container.style.removeProperty('align-items'); if (popup.offsetTop < 0) { container.style.alignItems = 'flex-start'; } }; /* istanbul ignore next */ var IEfix = function IEfix() { if (typeof window !== 'undefined' && isIE11()) { fixVerticalPositionIE(); window.addEventListener('resize', fixVerticalPositionIE); } }; /* istanbul ignore next */ var undoIEfix = function undoIEfix() { if (typeof window !== 'undefined' && isIE11()) { window.removeEventListener('resize', fixVerticalPositionIE); } }; // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that // elements not within the active modal dialog will not be surfaced if a user opens a screen // reader’s list of elements (headings, form controls, landmarks, etc.) in the document. var setAriaHidden = function setAriaHidden() { var bodyChildren = toArray(document.body.children); bodyChildren.forEach(function (el) { if (el === getContainer() || contains(el, getContainer())) { return; } if (el.hasAttribute('aria-hidden')) { el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden')); } el.setAttribute('aria-hidden', 'true'); }); }; var unsetAriaHidden = function unsetAriaHidden() { var bodyChildren = toArray(document.body.children); bodyChildren.forEach(function (el) { if (el.hasAttribute('data-previous-aria-hidden')) { el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden')); el.removeAttribute('data-previous-aria-hidden'); } else { el.removeAttribute('aria-hidden'); } }); }; /** * This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')` * This is the approach that Babel will probably take to implement private methods/fields * https://github.com/tc39/proposal-private-methods * https://github.com/babel/babel/pull/7555 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module* * then we can use that language feature. */ var privateMethods = { swalPromiseResolve: new WeakMap() }; /* * Instance method to close sweetAlert */ function removePopupAndResetState(container, isToast, onAfterClose) { if (isToast) { triggerOnAfterClose(onAfterClose); } else { restoreActiveElement().then(function () { return triggerOnAfterClose(onAfterClose); }); globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture }); globalState.keydownHandlerAdded = false; } // Unset globalState props so GC will dispose globalState (#1569) delete globalState.keydownHandler; delete globalState.keydownTarget; if (container.parentNode) { container.parentNode.removeChild(container); } removeBodyClasses(); if (isModal()) { undoScrollbar(); undoIOSfix(); undoIEfix(); unsetAriaHidden(); } } function removeBodyClasses() { removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['toast-column']]); } function swalCloseEventFinished(popup, container, isToast, onAfterClose) { // TODO(@limonte): for some reason swalCloseEventFinished is triggered twice sometimes // avoid double-executing if (!globalState.keydownTarget) { return; } popup.removeEventListener(animationEndEvent, swalCloseEventFinished); if (hasClass(popup, swalClasses.hide)) { removePopupAndResetState(container, isToast, onAfterClose); } // Unset WeakMaps so GC will be able to dispose them (#1569) unsetWeakMaps(privateProps); unsetWeakMaps(privateMethods); } function close(resolveValue) { var container = getContainer(); var popup = getPopup(); if (!popup || hasClass(popup, swalClasses.hide)) { return; } var innerParams = privateProps.innerParams.get(this); var swalPromiseResolve = privateMethods.swalPromiseResolve.get(this); var onClose = innerParams.onClose; var onAfterClose = innerParams.onAfterClose; removeClass(popup, swalClasses.show); addClass(popup, swalClasses.hide); // If animation is supported, animate if (animationEndEvent && hasCssAnimation(popup)) { popup.addEventListener(animationEndEvent, swalCloseEventFinished.bind(null, popup, container, isToast(), onAfterClose)); } else { // Otherwise, remove immediately removePopupAndResetState(container, isToast(), onAfterClose); } if (onClose !== null && typeof onClose === 'function') { onClose(popup); } // Resolve Swal promise swalPromiseResolve(resolveValue || {}); // Unset this.params so GC will dispose it (#1569) delete this.params; } var unsetWeakMaps = function unsetWeakMaps(obj) { for (var i in obj) { obj[i] = new WeakMap(); } }; var triggerOnAfterClose = function triggerOnAfterClose(onAfterClose) { if (onAfterClose !== null && typeof onAfterClose === 'function') { setTimeout(function () { onAfterClose(); }); } }; function setButtonsDisabled(instance, buttons, disabled) { var domCache = privateProps.domCache.get(instance); buttons.forEach(function (button) { domCache[button].disabled = disabled; }); } function setInputDisabled(input, disabled) { if (!input) { return false; } if (input.type === 'radio') { var radiosContainer = input.parentNode.parentNode; var radios = radiosContainer.querySelectorAll('input'); for (var i = 0; i < radios.length; i++) { radios[i].disabled = disabled; } } else { input.disabled = disabled; } } function enableButtons() { setButtonsDisabled(this, ['confirmButton', 'cancelButton'], false); } function disableButtons() { setButtonsDisabled(this, ['confirmButton', 'cancelButton'], true); } // @deprecated function enableConfirmButton() { warnAboutDepreation('Swal.disableConfirmButton()', "Swal.getConfirmButton().removeAttribute('disabled')"); setButtonsDisabled(this, ['confirmButton'], false); } // @deprecated function disableConfirmButton() { warnAboutDepreation('Swal.enableConfirmButton()', "Swal.getConfirmButton().setAttribute('disabled', '')"); setButtonsDisabled(this, ['confirmButton'], true); } function enableInput() { return setInputDisabled(this.getInput(), false); } function disableInput() { return setInputDisabled(this.getInput(), true); } function showValidationMessage(error) { var domCache = privateProps.domCache.get(this); domCache.validationMessage.innerHTML = error; var popupComputedStyle = window.getComputedStyle(domCache.popup); domCache.validationMessage.style.marginLeft = "-".concat(popupComputedStyle.getPropertyValue('padding-left')); domCache.validationMessage.style.marginRight = "-".concat(popupComputedStyle.getPropertyValue('padding-right')); show(domCache.validationMessage); var input = this.getInput(); if (input) { input.setAttribute('aria-invalid', true); input.setAttribute('aria-describedBy', swalClasses['validation-message']); focusInput(input); addClass(input, swalClasses.inputerror); } } // Hide block with validation message function resetValidationMessage$1() { var domCache = privateProps.domCache.get(this); if (domCache.validationMessage) { hide(domCache.validationMessage); } var input = this.getInput(); if (input) { input.removeAttribute('aria-invalid'); input.removeAttribute('aria-describedBy'); removeClass(input, swalClasses.inputerror); } } function getProgressSteps$1() { warnAboutDepreation('Swal.getProgressSteps()', "const swalInstance = Swal.fire({progressSteps: ['1', '2', '3']}); const progressSteps = swalInstance.params.progressSteps"); var innerParams = privateProps.innerParams.get(this); return innerParams.progressSteps; } function setProgressSteps(progressSteps) { warnAboutDepreation('Swal.setProgressSteps()', 'Swal.update()'); var innerParams = privateProps.innerParams.get(this); var updatedParams = _extends({}, innerParams, { progressSteps: progressSteps }); renderProgressSteps(this, updatedParams); privateProps.innerParams.set(this, updatedParams); } function showProgressSteps() { var domCache = privateProps.domCache.get(this); show(domCache.progressSteps); } function hideProgressSteps() { var domCache = privateProps.domCache.get(this); hide(domCache.progressSteps); } var Timer = /*#__PURE__*/ function () { function Timer(callback, delay) { _classCallCheck(this, Timer); this.callback = callback; this.remaining = delay; this.running = false; this.start(); } _createClass(Timer, [{ key: "start", value: function start() { if (!this.running) { this.running = true; this.started = new Date(); this.id = setTimeout(this.callback, this.remaining); } return this.remaining; } }, { key: "stop", value: function stop() { if (this.running) { this.running = false; clearTimeout(this.id); this.remaining -= new Date() - this.started; } return this.remaining; } }, { key: "increase", value: function increase(n) { var running = this.running; if (running) { this.stop(); } this.remaining += n; if (running) { this.start(); } return this.remaining; } }, { key: "getTimerLeft", value: function getTimerLeft() { if (this.running) { this.stop(); this.start(); } return this.remaining; } }, { key: "isRunning", value: function isRunning() { return this.running; } }]); return Timer; }(); var defaultInputValidators = { email: function email(string, validationMessage) { return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage ? validationMessage : 'Invalid email address'); }, url: function url(string, validationMessage) { // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage ? validationMessage : 'Invalid URL'); } }; /** * Set type, text and actions on popup * * @param params * @returns {boolean} */ function setParameters(params) { // Use default `inputValidator` for supported input types if not provided if (!params.inputValidator) { Object.keys(defaultInputValidators).forEach(function (key) { if (params.input === key) { params.inputValidator = defaultInputValidators[key]; } }); } // showLoaderOnConfirm && preConfirm if (params.showLoaderOnConfirm && !params.preConfirm) { warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\n' + 'https://sweetalert2.github.io/#ajax-request'); } // params.animation will be actually used in renderPopup.js // but in case when params.animation is a function, we need to call that function // before popup (re)initialization, so it'll be possible to check Swal.isVisible() // inside the params.animation function params.animation = callIfFunction(params.animation); // Determine if the custom target element is valid if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) { warn('Target parameter is not valid, defaulting to "body"'); params.target = 'body'; } // Replace newlines with <br> in title if (typeof params.title === 'string') { params.title = params.title.split('\n').join('<br />'); } var oldPopup = getPopup(); var targetElement = typeof params.target === 'string' ? document.querySelector(params.target) : params.target; if (!oldPopup || // If the model target has changed, refresh the popup oldPopup && targetElement && oldPopup.parentNode !== targetElement.parentNode) { init(params); } } function swalOpenAnimationFinished(popup, container) { popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished); container.style.overflowY = 'auto'; } /** * Open popup, add necessary classes and styles, fix scrollbar * * @param {Array} params */ var openPopup = function openPopup(params) { var container = getContainer(); var popup = getPopup(); if (params.onBeforeOpen !== null && typeof params.onBeforeOpen === 'function') { params.onBeforeOpen(popup); } if (params.animation) { addClass(popup, swalClasses.show); addClass(container, swalClasses.fade); } show(popup); // scrolling is 'hidden' until animation is done, after that 'auto' if (animationEndEvent && hasCssAnimation(popup)) { container.style.overflowY = 'hidden'; popup.addEventListener(animationEndEvent, swalOpenAnimationFinished.bind(null, popup, container)); } else { container.style.overflowY = 'auto'; } addClass([document.documentElement, document.body, container], swalClasses.shown); if (params.heightAuto && params.backdrop && !params.toast) { addClass([document.documentElement, document.body], swalClasses['height-auto']); } if (isModal()) { if (params.scrollbarPadding) { fixScrollbar(); } iOSfix(); IEfix(); setAriaHidden(); // sweetalert2/issues/1247 setTimeout(function () { container.scrollTop = 0; }); } if (!isToast() && !globalState.previousActiveElement) { globalState.previousActiveElement = document.activeElement; } if (params.onOpen !== null && typeof params.onOpen === 'function') { setTimeout(function () { params.onOpen(popup); }); } }; var _this = undefined; var handleInputOptions = function handleInputOptions(instance, params) { var content = getContent(); var processInputOptions = function processInputOptions(inputOptions) { return populateInputOptions[params.input](content, formatInputOptions(inputOptions), params); }; if (isPromise(params.inputOptions)) { showLoading(); params.inputOptions.then(function (inputOptions) { instance.hideLoading(); processInputOptions(inputOptions); }); } else if (_typeof(params.inputOptions) === 'object') { processInputOptions(params.inputOptions); } else { error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(_typeof(params.inputOptions))); } }; var handleInputValue = function handleInputValue(instance, params) { var input = instance.getInput(); hide(input); params.inputValue.then(function (inputValue) { input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : inputValue + ''; show(input); input.focus(); instance.hideLoading(); })["catch"](function (err) { error('Error in inputValue promise: ' + err); input.value = ''; show(input); input.focus(); _this.hideLoading(); }); }; var populateInputOptions = { select: function select(content, inputOptions, params) { var select = getChildByClass(content, swalClasses.select); inputOptions.forEach(function (inputOption) { var optionValue = inputOption[0]; var optionLabel = inputOption[1]; var option = document.createElement('option'); option.value = optionValue; option.innerHTML = optionLabel; if (params.inputValue.toString() === optionValue.toString()) { option.selected = true; } select.appendChild(option); }); select.focus(); }, radio: function radio(content, inputOptions, params) { var radio = getChildByClass(content, swalClasses.radio); inputOptions.forEach(function (inputOption) { var radioValue = inputOption[0]; var radioLabel = inputOption[1]; var radioInput = document.createElement('input'); var radioLabelElement = document.createElement('label'); radioInput.type = 'radio'; radioInput.name = swalClasses.radio; radioInput.value = radioValue; if (params.inputValue.toString() === radioValue.toString()) { radioInput.checked = true; } var label = document.createElement('span'); label.innerHTML = radioLabel; label.className = swalClasses.label; radioLabelElement.appendChild(radioInput); radioLabelElement.appendChild(label); radio.appendChild(radioLabelElement); }); var radios = radio.querySelectorAll('input'); if (radios.length) { radios[0].focus(); } } /** * Converts `inputOptions` into an array of `[value, label]`s * @param inputOptions */ }; var formatInputOptions = function formatInputOptions(inputOptions) { var result = []; if (typeof Map !== 'undefined' && inputOptions instanceof Map) { inputOptions.forEach(function (value, key) { result.push([key, value]); }); } else { Object.keys(inputOptions).forEach(function (key) { result.push([key, inputOptions[key]]); }); } return result; }; function _main(userParams) { var _this = this; showWarningsForParams(userParams); var innerParams = _extends({}, defaultParams, userParams); setParameters(innerParams); Object.freeze(innerParams); // clear the previous timer if (globalState.timeout) { globalState.timeout.stop(); delete globalState.timeout; } // clear the restore focus timeout clearTimeout(globalState.restoreFocusTimeout); var domCache = { popup: getPopup(), container: getContainer(), content: getContent(), actions: getActions(), confirmButton: getConfirmButton(), cancelButton: getCancelButton(), closeButton: getCloseButton(), validationMessage: getValidationMessage(), progressSteps: getProgressSteps() }; privateProps.domCache.set(this, domCache); render(this, innerParams); privateProps.innerParams.set(this, innerParams); var constructor = this.constructor; return new Promise(function (resolve) { // functions to handle all closings/dismissals var succeedWith = function succeedWith(value) { _this.closePopup({ value: value }); }; var dismissWith = function dismissWith(dismiss) { _this.closePopup({ dismiss: dismiss }); }; privateMethods.swalPromiseResolve.set(_this, resolve); // Close on timer if (innerParams.timer) { globalState.timeout = new Timer(function () { dismissWith('timer'); delete globalState.timeout; }, innerParams.timer); } // Get the value of the popup input var getInputValue = function getInputValue() { var input = _this.getInput(); if (!input) { return null; } switch (innerParams.input) { case 'checkbox': return input.checked ? 1 : 0; case 'radio': return input.checked ? input.value : null; case 'file': return input.files.length ? input.files[0] : null; default: return innerParams.inputAutoTrim ? input.value.trim() : input.value; } }; // input autofocus if (innerParams.input) { setTimeout(function () { var input = _this.getInput(); if (input) { focusInput(input); } }, 0); } var confirm = function confirm(value) { if (innerParams.showLoaderOnConfirm) { constructor.showLoading(); // TODO: make showLoading an *instance* method } if (innerParams.preConfirm) { _this.resetValidationMessage(); var preConfirmPromise = Promise.resolve().then(function () { return innerParams.preConfirm(value, innerParams.validationMessage); }); preConfirmPromise.then(function (preConfirmValue) { if (isVisible(domCache.validationMessage) || preConfirmValue === false) { _this.hideLoading(); } else { succeedWith(typeof preConfirmValue === 'undefined' ? value : preConfirmValue); } }); } else { succeedWith(value); } }; // Mouse interactions var onButtonEvent = function onButtonEvent(e) { var target = e.target; var confirmButton = domCache.confirmButton, cancelButton = domCache.cancelButton; var targetedConfirm = confirmButton && (confirmButton === target || confirmButton.contains(target)); var targetedCancel = cancelButton && (cancelButton === target || cancelButton.contains(target)); switch (e.type) { case 'click': // Clicked 'confirm' if (targetedConfirm) { _this.disableButtons(); if (innerParams.input) { var inputValue = getInputValue(); if (innerParams.inputValidator) { _this.disableInput(); var validationPromise = Promise.resolve().then(function () { return innerParams.inputValidator(inputValue, innerParams.validationMessage); }); validationPromise.then(function (validationMessage) { _this.enableButtons(); _this.enableInput(); if (validationMessage) { _this.showValidationMessage(validationMessage); } else { confirm(inputValue); } }); } else if (!_this.getInput().checkValidity()) { _this.enableButtons(); _this.showValidationMessage(innerParams.validationMessage); } else { confirm(inputValue); } } else { confirm(true); } // Clicked 'cancel' } else if (targetedCancel) { _this.disableButtons(); dismissWith(constructor.DismissReason.cancel); } break; default: } }; var buttons = domCache.popup.querySelectorAll('button'); for (var i = 0; i < buttons.length; i++) { buttons[i].onclick = onButtonEvent; buttons[i].onmouseover = onButtonEvent; buttons[i].onmouseout = onButtonEvent; buttons[i].onmousedown = onButtonEvent; } // Closing popup by close button domCache.closeButton.onclick = function () { dismissWith(constructor.DismissReason.close); }; if (innerParams.toast) { // Closing popup by internal click domCache.popup.onclick = function () { if (innerParams.showConfirmButton || innerParams.showCancelButton || innerParams.showCloseButton || innerParams.input) { return; } dismissWith(constructor.DismissReason.close); }; } else { var ignoreOutsideClick = false; // Ignore click events that had mousedown on the popup but mouseup on the container // This can happen when the user drags a slider domCache.popup.onmousedown = function () { domCache.container.onmouseup = function (e) { domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't // have any other direct children aside of the popup if (e.target === domCache.container) { ignoreOutsideClick = true; } }; }; // Ignore click events that had mousedown on the container but mouseup on the popup domCache.container.onmousedown = function () { domCache.popup.onmouseup = function (e) { domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup if (e.target === domCache.popup || domCache.popup.contains(e.target)) { ignoreOutsideClick = true; } }; }; domCache.container.onclick = function (e) { if (ignoreOutsideClick) { ignoreOutsideClick = false; return; } if (e.target !== domCache.container) { return; } if (callIfFunction(innerParams.allowOutsideClick)) { dismissWith(constructor.DismissReason.backdrop); } }; } // Reverse buttons (Confirm on the right side) if (innerParams.reverseButtons) { domCache.confirmButton.parentNode.insertBefore(domCache.cancelButton, domCache.confirmButton); } else { domCache.confirmButton.parentNode.insertBefore(domCache.confirmButton, domCache.cancelButton); } // Focus handling var setFocus = function setFocus(index, increment) { var focusableElements = getFocusableElements(innerParams.focusCancel); // search for visible elements and select the next possible match for (var _i = 0; _i < focusableElements.length; _i++) { index = index + increment; // rollover to first item if (index === focusableElements.length) { index = 0; // go to last item } else if (index === -1) { index = focusableElements.length - 1; } return focusableElements[index].focus(); } // no visible focusable elements, focus the popup domCache.popup.focus(); }; var keydownHandler = function keydownHandler(e, innerParams) { if (innerParams.stopKeydownPropagation) { e.stopPropagation(); } var arrowKeys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Left', 'Right', 'Up', 'Down' // IE11 ]; if (e.key === 'Enter' && !e.isComposing) { if (e.target && _this.getInput() && e.target.outerHTML === _this.getInput().outerHTML) { if (['textarea', 'file'].indexOf(innerParams.input) !== -1) { return; // do not submit } constructor.clickConfirm(); e.preventDefault(); } // TAB } else if (e.key === 'Tab') { var targetElement = e.target; var focusableElements = getFocusableElements(innerParams.focusCancel); var btnIndex = -1; for (var _i2 = 0; _i2 < focusableElements.length; _i2++) { if (targetElement === focusableElements[_i2]) { btnIndex = _i2; break; } } if (!e.shiftKey) { // Cycle to the next button setFocus(btnIndex, 1); } else { // Cycle to the prev button setFocus(btnIndex, -1); } e.stopPropagation(); e.preventDefault(); // ARROWS - switch focus between buttons } else if (arrowKeys.indexOf(e.key) !== -1) { // focus Cancel button if Confirm button is currently focused if (document.activeElement === domCache.confirmButton && isVisible(domCache.cancelButton)) { domCache.cancelButton.focus(); // and vice versa } else if (document.activeElement === domCache.cancelButton && isVisible(domCache.confirmButton)) { domCache.confirmButton.focus(); } // ESC } else if ((e.key === 'Escape' || e.key === 'Esc') && callIfFunction(innerParams.allowEscapeKey) === true) { e.preventDefault(); dismissWith(constructor.DismissReason.esc); } }; if (globalState.keydownTarget && globalState.keydownHandlerAdded) { globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture }); globalState.keydownHandlerAdded = false; } if (!innerParams.toast) { globalState.keydownHandler = function (e) { return keydownHandler(e, innerParams); }; globalState.keydownTarget = innerParams.keydownListenerCapture ? window : domCache.popup; globalState.keydownListenerCapture = innerParams.keydownListenerCapture; globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture }); globalState.keydownHandlerAdded = true; } _this.enableButtons(); _this.hideLoading(); _this.resetValidationMessage(); if (innerParams.toast && (innerParams.input || innerParams.footer || innerParams.showCloseButton)) { addClass(document.body, swalClasses['toast-column']); } else { removeClass(document.body, swalClasses['toast-column']); } // inputOptions, inputValue if (innerParams.input === 'select' || innerParams.input === 'radio') { handleInputOptions(_this, innerParams); } else if (['text', 'email', 'number', 'tel', 'textarea'].indexOf(innerParams.input) !== -1 && isPromise(innerParams.inputValue)) { handleInputValue(_this, innerParams); } openPopup(innerParams); if (!innerParams.toast) { if (!callIfFunction(innerParams.allowEnterKey)) { if (document.activeElement && typeof document.activeElement.blur === 'function') { document.activeElement.blur(); } } else if (innerParams.focusCancel && isVisible(domCache.cancelButton)) { domCache.cancelButton.focus(); } else if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) { domCache.confirmButton.focus(); } else { setFocus(-1, 1); } } // fix scroll domCache.container.scrollTop = 0; }); } /** * Updates popup parameters. */ function update(params) { var validUpdatableParams = {}; // assign valid params from `params` to `defaults` Object.keys(params).forEach(function (param) { if (Swal.isUpdatableParameter(param)) { validUpdatableParams[param] = params[param]; } else { warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js")); } }); var innerParams = privateProps.innerParams.get(this); var updatedParams = _extends({}, innerParams, validUpdatableParams); render(this, updatedParams); privateProps.innerParams.set(this, updatedParams); Object.defineProperties(this, { params: { value: _extends({}, this.params, params), writable: false, enumerable: true } }); } var instanceMethods = Object.freeze({ hideLoading: hideLoading, disableLoading: hideLoading, getInput: getInput$1, close: close, closePopup: close, closeModal: close, closeToast: close, enableButtons: enableButtons, disableButtons: disableButtons, enableConfirmButton: enableConfirmButton, disableConfirmButton: disableConfirmButton, enableInput: enableInput, disableInput: disableInput, showValidationMessage: showValidationMessage, resetValidationMessage: resetValidationMessage$1, getProgressSteps: getProgressSteps$1, setProgressSteps: setProgressSteps, showProgressSteps: showProgressSteps, hideProgressSteps: hideProgressSteps, _main: _main, update: update }); var currentInstance; // SweetAlert constructor function SweetAlert() { // Prevent run in Node env /* istanbul ignore if */ if (typeof window === 'undefined') { return; } // Check for the existence of Promise /* istanbul ignore if */ if (typeof Promise === 'undefined') { error('This package requires a Promise library, please include a shim to enable it in this browser (See: https://github.com/sweetalert2/sweetalert2/wiki/Migration-from-SweetAlert-to-SweetAlert2#1-ie-support)'); } currentInstance = this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var outerParams = Object.freeze(this.constructor.argsToParams(args)); Object.defineProperties(this, { params: { value: outerParams, writable: false, enumerable: true, configurable: true } }); var promise = this._main(this.params); privateProps.promise.set(this, promise); } // `catch` cannot be the name of a module export, so we define our thenable methods here instead SweetAlert.prototype.then = function (onFulfilled) { var promise = privateProps.promise.get(this); return promise.then(onFulfilled); }; SweetAlert.prototype["finally"] = function (onFinally) { var promise = privateProps.promise.get(this); return promise["finally"](onFinally); }; // Assign instance methods from src/instanceMethods/*.js to prototype _extends(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor _extends(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility Object.keys(instanceMethods).forEach(function (key) { SweetAlert[key] = function () { if (currentInstance) { var _currentInstance; return (_currentInstance = currentInstance)[key].apply(_currentInstance, arguments); } }; }); SweetAlert.DismissReason = DismissReason; SweetAlert.version = '8.11.4'; var Swal = SweetAlert; Swal["default"] = Swal; return Swal; }))); if (typeof window !== 'undefined' && window.Sweetalert2){ window.swal = window.sweetAlert = window.Swal = window.SweetAlert = window.Sweetalert2} "undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,"@charset \"UTF-8\";@-webkit-keyframes swal2-show{0%{-webkit-transform:scale(.7);transform:scale(.7)}45%{-webkit-transform:scale(1.05);transform:scale(1.05)}80%{-webkit-transform:scale(.95);transform:scale(.95)}100%{-webkit-transform:scale(1);transform:scale(1)}}@keyframes swal2-show{0%{-webkit-transform:scale(.7);transform:scale(.7)}45%{-webkit-transform:scale(1.05);transform:scale(1.05)}80%{-webkit-transform:scale(.95);transform:scale(.95)}100%{-webkit-transform:scale(1);transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}100%{-webkit-transform:scale(.5);transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}100%{-webkit-transform:scale(.5);transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.875em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.875em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}5%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}12%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}100%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}5%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}12%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}100%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}50%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}80%{margin-top:-.375em;-webkit-transform:scale(1.15);transform:scale(1.15)}100%{margin-top:0;-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}50%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}80%{margin-top:-.375em;-webkit-transform:scale(1.15);transform:scale(1.15)}100%{margin-top:0;-webkit-transform:scale(1);transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{-webkit-transform:rotateX(100deg);transform:rotateX(100deg);opacity:0}100%{-webkit-transform:rotateX(0);transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{-webkit-transform:rotateX(100deg);transform:rotateX(100deg);opacity:0}100%{-webkit-transform:rotateX(0);transform:rotateX(0);opacity:1}}body.swal2-toast-shown .swal2-container{background-color:transparent}body.swal2-toast-shown .swal2-container.swal2-shown{background-color:transparent}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}body.swal2-toast-column .swal2-toast{flex-direction:column;align-items:stretch}body.swal2-toast-column .swal2-toast .swal2-actions{flex:1;align-self:stretch;height:2.2em;margin-top:.3125em}body.swal2-toast-column .swal2-toast .swal2-loading{justify-content:center}body.swal2-toast-column .swal2-toast .swal2-input{height:2em;margin:.3125em auto;font-size:1em}body.swal2-toast-column .swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast{flex-direction:row;align-items:center;width:auto;padding:.625em;overflow-y:hidden;box-shadow:0 0 .625em #d9d9d9}.swal2-popup.swal2-toast .swal2-header{flex-direction:row}.swal2-popup.swal2-toast .swal2-title{flex-grow:1;justify-content:flex-start;margin:0 .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{position:static;width:.8em;height:.8em;line-height:.8}.swal2-popup.swal2-toast .swal2-content{justify-content:flex-start;font-size:1em}.swal2-popup.swal2-toast .swal2-icon{width:2em;min-width:2em;height:2em;margin:0}.swal2-popup.swal2-toast .swal2-icon::before{display:flex;align-items:center;font-size:2em;font-weight:700}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-popup.swal2-toast .swal2-icon::before{font-size:.25em}}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{flex-basis:auto!important;height:auto;margin:0 .3125em}.swal2-popup.swal2-toast .swal2-styled{margin:0 .3125em;padding:.3125em .625em;font-size:1em}.swal2-popup.swal2-toast .swal2-styled:focus{box-shadow:0 0 0 .0625em #fff,0 0 0 .125em rgba(50,100,150,.4)}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;-webkit-transform:rotate(45deg);transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.8em;left:-.5em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:2em 2em;transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;-webkit-transform-origin:0 1.5em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:swal2-toast-show .5s;animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:swal2-toast-hide .1s forwards;animation:swal2-toast-hide .1s forwards}.swal2-popup.swal2-toast .swal2-animate-success-icon .swal2-success-line-tip{-webkit-animation:swal2-toast-animate-success-line-tip .75s;animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-animate-success-icon .swal2-success-line-long{-webkit-animation:swal2-toast-animate-success-line-long .75s;animation:swal2-toast-animate-success-line-long .75s}@-webkit-keyframes swal2-toast-show{0%{-webkit-transform:translateY(-.625em) rotateZ(2deg);transform:translateY(-.625em) rotateZ(2deg)}33%{-webkit-transform:translateY(0) rotateZ(-2deg);transform:translateY(0) rotateZ(-2deg)}66%{-webkit-transform:translateY(.3125em) rotateZ(2deg);transform:translateY(.3125em) rotateZ(2deg)}100%{-webkit-transform:translateY(0) rotateZ(0);transform:translateY(0) rotateZ(0)}}@keyframes swal2-toast-show{0%{-webkit-transform:translateY(-.625em) rotateZ(2deg);transform:translateY(-.625em) rotateZ(2deg)}33%{-webkit-transform:translateY(0) rotateZ(-2deg);transform:translateY(0) rotateZ(-2deg)}66%{-webkit-transform:translateY(.3125em) rotateZ(2deg);transform:translateY(.3125em) rotateZ(2deg)}100%{-webkit-transform:translateY(0) rotateZ(0);transform:translateY(0) rotateZ(0)}}@-webkit-keyframes swal2-toast-hide{100%{-webkit-transform:rotateZ(1deg);transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-hide{100%{-webkit-transform:rotateZ(1deg);transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-shown{top:auto;right:auto;bottom:auto;left:auto;max-width:calc(100% - .625em * 2);background-color:transparent}body.swal2-no-backdrop .swal2-shown>.swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}body.swal2-no-backdrop .swal2-shown.swal2-top{top:0;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-top-left,body.swal2-no-backdrop .swal2-shown.swal2-top-start{top:0;left:0}body.swal2-no-backdrop .swal2-shown.swal2-top-end,body.swal2-no-backdrop .swal2-shown.swal2-top-right{top:0;right:0}body.swal2-no-backdrop .swal2-shown.swal2-center{top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}body.swal2-no-backdrop .swal2-shown.swal2-center-left,body.swal2-no-backdrop .swal2-shown.swal2-center-start{top:50%;left:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-center-end,body.swal2-no-backdrop .swal2-shown.swal2-center-right{top:50%;right:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-bottom{bottom:0;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-bottom-left,body.swal2-no-backdrop .swal2-shown.swal2-bottom-start{bottom:0;left:0}body.swal2-no-backdrop .swal2-shown.swal2-bottom-end,body.swal2-no-backdrop .swal2-shown.swal2-bottom-right{right:0;bottom:0}.swal2-container{display:flex;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;flex-direction:row;align-items:center;justify-content:center;padding:.625em;overflow-x:hidden;background-color:transparent;-webkit-overflow-scrolling:touch}.swal2-container.swal2-top{align-items:flex-start}.swal2-container.swal2-top-left,.swal2-container.swal2-top-start{align-items:flex-start;justify-content:flex-start}.swal2-container.swal2-top-end,.swal2-container.swal2-top-right{align-items:flex-start;justify-content:flex-end}.swal2-container.swal2-center{align-items:center}.swal2-container.swal2-center-left,.swal2-container.swal2-center-start{align-items:center;justify-content:flex-start}.swal2-container.swal2-center-end,.swal2-container.swal2-center-right{align-items:center;justify-content:flex-end}.swal2-container.swal2-bottom{align-items:flex-end}.swal2-container.swal2-bottom-left,.swal2-container.swal2-bottom-start{align-items:flex-end;justify-content:flex-start}.swal2-container.swal2-bottom-end,.swal2-container.swal2-bottom-right{align-items:flex-end;justify-content:flex-end}.swal2-container.swal2-bottom-end>:first-child,.swal2-container.swal2-bottom-left>:first-child,.swal2-container.swal2-bottom-right>:first-child,.swal2-container.swal2-bottom-start>:first-child,.swal2-container.swal2-bottom>:first-child{margin-top:auto}.swal2-container.swal2-grow-fullscreen>.swal2-modal{display:flex!important;flex:1;align-self:stretch;justify-content:center}.swal2-container.swal2-grow-row>.swal2-modal{display:flex!important;flex:1;align-content:center;justify-content:center}.swal2-container.swal2-grow-column{flex:1;flex-direction:column}.swal2-container.swal2-grow-column.swal2-bottom,.swal2-container.swal2-grow-column.swal2-center,.swal2-container.swal2-grow-column.swal2-top{align-items:center}.swal2-container.swal2-grow-column.swal2-bottom-left,.swal2-container.swal2-grow-column.swal2-bottom-start,.swal2-container.swal2-grow-column.swal2-center-left,.swal2-container.swal2-grow-column.swal2-center-start,.swal2-container.swal2-grow-column.swal2-top-left,.swal2-container.swal2-grow-column.swal2-top-start{align-items:flex-start}.swal2-container.swal2-grow-column.swal2-bottom-end,.swal2-container.swal2-grow-column.swal2-bottom-right,.swal2-container.swal2-grow-column.swal2-center-end,.swal2-container.swal2-grow-column.swal2-center-right,.swal2-container.swal2-grow-column.swal2-top-end,.swal2-container.swal2-grow-column.swal2-top-right{align-items:flex-end}.swal2-container.swal2-grow-column>.swal2-modal{display:flex!important;flex:1;align-content:center;justify-content:center}.swal2-container:not(.swal2-top):not(.swal2-top-start):not(.swal2-top-end):not(.swal2-top-left):not(.swal2-top-right):not(.swal2-center-start):not(.swal2-center-end):not(.swal2-center-left):not(.swal2-center-right):not(.swal2-bottom):not(.swal2-bottom-start):not(.swal2-bottom-end):not(.swal2-bottom-left):not(.swal2-bottom-right):not(.swal2-grow-fullscreen)>.swal2-modal{margin:auto}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-container .swal2-modal{margin:0!important}}.swal2-container.swal2-fade{transition:background-color .1s}.swal2-container.swal2-shown{background-color:rgba(0,0,0,.4)}.swal2-popup{display:none;position:relative;box-sizing:border-box;flex-direction:column;justify-content:center;width:32em;max-width:100%;padding:1.25em;border:none;border-radius:.3125em;background:#fff;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-header{display:flex;flex-direction:column;align-items:center}.swal2-title{position:relative;max-width:100%;margin:0 0 .4em;padding:0;color:#595959;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{z-index:1;flex-wrap:wrap;align-items:center;justify-content:center;width:100%;margin:1.25em auto 0}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-actions.swal2-loading .swal2-styled.swal2-confirm{box-sizing:border-box;width:2.5em;height:2.5em;margin:.46875em;padding:0;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border:.25em solid transparent;border-radius:100%;border-color:transparent;background-color:transparent!important;color:transparent;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-actions.swal2-loading .swal2-styled.swal2-cancel{margin-right:30px;margin-left:30px}.swal2-actions.swal2-loading :not(.swal2-styled).swal2-confirm::after{content:\"\";display:inline-block;width:15px;height:15px;margin-left:5px;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border:3px solid #999;border-radius:50%;border-right-color:transparent;box-shadow:1px 1px 1px #fff}.swal2-styled{margin:.3125em;padding:.625em 2em;box-shadow:none;font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#3085d6;color:#fff;font-size:1.0625em}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#aaa;color:#fff;font-size:1.0625em}.swal2-styled:focus{outline:0;box-shadow:0 0 0 2px #fff,0 0 0 4px rgba(50,100,150,.4)}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1.25em 0 0;padding:1em 0 0;border-top:1px solid #eee;color:#545454;font-size:1em}.swal2-image{max-width:100%;margin:1.25em auto}.swal2-close{position:absolute;top:0;right:0;justify-content:center;width:1.2em;height:1.2em;padding:0;overflow:hidden;transition:color .1s ease-out;border:none;border-radius:0;outline:initial;background:0 0;color:#ccc;font-family:serif;font-size:2.5em;line-height:1.2;cursor:pointer}.swal2-close:hover{-webkit-transform:none;transform:none;background:0 0;color:#f27474}.swal2-content{z-index:1;justify-content:center;margin:0;padding:0;color:#545454;font-size:1.125em;font-weight:300;line-height:normal;word-wrap:break-word}#swal2-content{text-align:center}.swal2-checkbox,.swal2-file,.swal2-input,.swal2-radio,.swal2-select,.swal2-textarea{margin:1em auto}.swal2-file,.swal2-input,.swal2-textarea{box-sizing:border-box;width:100%;transition:border-color .3s,box-shadow .3s;border:1px solid #d9d9d9;border-radius:.1875em;background:inherit;box-shadow:inset 0 1px 1px rgba(0,0,0,.06);color:inherit;font-size:1.125em}.swal2-file.swal2-inputerror,.swal2-input.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:0 0 3px #c4e6f5}.swal2-file::-webkit-input-placeholder,.swal2-input::-webkit-input-placeholder,.swal2-textarea::-webkit-input-placeholder{color:#ccc}.swal2-file::-moz-placeholder,.swal2-input::-moz-placeholder,.swal2-textarea::-moz-placeholder{color:#ccc}.swal2-file:-ms-input-placeholder,.swal2-input:-ms-input-placeholder,.swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-file::-ms-input-placeholder,.swal2-input::-ms-input-placeholder,.swal2-textarea::-ms-input-placeholder{color:#ccc}.swal2-file::placeholder,.swal2-input::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em auto;background:inherit}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-input[type=number]{max-width:10em}.swal2-file{background:inherit;font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:inherit;color:inherit;font-size:1.125em}.swal2-checkbox,.swal2-radio{align-items:center;justify-content:center;background:inherit;color:inherit}.swal2-checkbox label,.swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-checkbox input,.swal2-radio input{margin:0 .4em}.swal2-validation-message{display:none;align-items:center;justify-content:center;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;zoom:normal;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}@supports (-ms-accelerator:true){.swal2-range input{width:100%!important}.swal2-range output{display:none}}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-range input{width:100%!important}.swal2-range output{display:none}}@-moz-document url-prefix(){.swal2-close:focus{outline:2px solid rgba(50,100,150,.4)}}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:1.25em auto 1.875em;zoom:normal;border:.25em solid transparent;border-radius:50%;line-height:5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-icon::before{display:flex;align-items:center;height:92%;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-warning::before{content:\"!\"}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-info::before{content:\"i\"}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-question::before{content:\"?\"}.swal2-icon.swal2-question.swal2-arabic-question-mark::before{content:\"؟\"}.swal2-icon.swal2-success{border-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;-webkit-transform:rotate(45deg);transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:3.75em 3.75em;transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:0 3.75em;transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-.25em;left:-.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.875em;width:1.5625em;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.swal2-progress-steps{align-items:center;margin:0 0 1.25em;padding:0;background:inherit;font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;width:2em;height:2em;border-radius:2em;background:#3085d6;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#3085d6}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;width:2.5em;height:.4em;margin:0 -1px;background:#3085d6}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-show.swal2-noanimation{-webkit-animation:none;animation:none}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-hide.swal2-noanimation{-webkit-animation:none;animation:none}.swal2-rtl .swal2-close{right:auto;left:0}.swal2-animate-success-icon .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-animate-success-icon .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-animate-success-icon .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-animate-error-icon{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-animate-error-icon .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}@-webkit-keyframes swal2-rotate-loading{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll!important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static!important}}");
class Bird: def sing(self): print("bird sing") class sonBird(Bird): def sing(self): print("另一种鸟sing") def psing(self): self.sing() Bird.sing(self) s = sonBird() s.sing() s.psing()
#!/usr/bin/env node var fs = require("fs"), dust = require("dust"), async = require("async"), _ = require("underscore"); function Dusty(location) { this.location = location; } Dusty.prototype._compile = function(location, cb) { var self = this; fs.stat(location, function(err, stat) { if (err) { cb(err); return; } if (stat.isDirectory()) { fs.readdir(location, function(err, files) { if (err) { cb(err); return; } async.map(files, function(file, cb) { self._compile(location + "/" + file, cb); }, function(err, res) { if (err) { cb(err); return; } cb(null, res); }); }); } else if (stat.isFile() && location.match(/\.dust$/)) { var filename = location.replace(new RegExp("^" + self.location + "/(.+?)\.dust$"), "$1"); fs.readFile(location, "utf8", function(err, data) { if (err) { cb(err); return; } var compiled = dust.compile(data, filename); cb(null, {name: filename, js: compiled}); }); } else { cb(); } }, function(err, compiled) { if (err) { cb(err); return; } // Filter out empty objects caused by non-dust files cb(null, compiled); }); }; Dusty.prototype.compile = function(location, cb) { if (!cb && typeof location == "function") { cb = location; location = null; } location = location || this.location; this._compile(location, function(err, compiled) { if (err) { cb(err); return; } var templates = {}; _(compiled).chain().flatten().filter(function(e) { return e && !!e.name; }).each(function(template) { templates[template.name] = template.js; }); cb(null, templates); }); }; module.exports = Dusty;
// Load modules var Any = require('./any'); var Utils = require('./utils'); // Declare internals var internals = {}; module.exports = internals.Number = function () { Any.call(this); this._type = 'number'; this._base(function (value, state, options) { if ((typeof value === 'number' || typeof value === 'string') && !isNaN(+value)) { return null; } return Any.error('number.base', { value: value }, state); }); }; Utils.inherits(internals.Number, Any); internals.Number.prototype._convert = function (value) { if (typeof value === 'string') { var number = parseFloat(value); if (isNaN(number) || !isFinite(value)) { return NaN; } return number; } return value; }; internals.Number.prototype.min = function (limit) { Utils.assert((!isNaN(limit) && ((limit | 0) === parseFloat(limit))), 'limit must be an integer'); this._test('min', limit, function (value, state, options) { if (isNaN(value) || value >= limit) { return null; } return Any.error('number.min', { value: limit }, state); }); return this; }; internals.Number.prototype.max = function (limit) { Utils.assert((!isNaN(limit) && ((limit | 0) === parseFloat(limit))), 'limit must be an integer'); this._test('max', limit, function (value, state, options) { if (value <= limit) { return null; } return Any.error('number.max', { value: limit }, state); }); return this; }; internals.Number.prototype.integer = function () { this._test('integer', undefined, function (value, state, options) { if (!isNaN(value) && ((value | 0) === parseFloat(value))) { return null; } return Any.error('number.int', { value: value }, state); }); return this; }; internals.Number.prototype.negative = function () { this._test('negative', undefined, function (value, state, options) { if (value < 0) { return null; } return Any.error('number.negative', { value: value }, state); }); return this; }; internals.Number.prototype.positive = function () { this._test('positive', undefined, function (value, state, options) { if (value > 0) { return null; } return Any.error('number.positive', { value: value }, state); }); return this; };
import os import model import tensorflow as tf import input_data data=input_data.read_data_sets('MNIST_data',one_hot=True) with tf.variable_scope("convolutional"): x=tf.placeholder(tf.float32,[None,784],name='x') keep_prob=tf.placeholder(tf.float32) y,variables=model.convolutional(x,keep_prob) #train y_=tf.placeholder(tf.float32,[None,10],name='y') cross_entropy=-tf.reduce_sum(y_*tf.log(y)) train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) saver=tf.train.Saver(variables) with tf.Session() as sess: merged_summary_op=tf.summary.merge_all() summary_writer=tf.summary.FileWriter('/tmp/mnist_log/1',sess.graph) summary_writer.add_graph(sess.graph) sess.run(tf.global_variables_initializer()) for i in range(1000): batch=data.train.next_batch(50) if i%100==0: train_accuracy=accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0}) # print("step %d,training accuracy $g"%(i,train_accuracy)) print ("step %d, training accuracy %g" % (i, train_accuracy)) sess.run(train_step,feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5}) print(sess.run(accuracy, feed_dict={x: data.test.images, y_: data.test.labels,keep_prob:1.0})) path=saver.save( sess,os.path.join(os.path.dirname(__file__),'data','convalutional.ckpt'), write_meta_graph=False,write_state=False) print("Saved:",path)
import Vec from '../../src/vec/vec.main'; describe('Vec.forEach2()', () => { test('should throw exception if arguments are invalid', () => { expect(() => Vec.forEach2({}, new Vec(), new Vec())).toThrow(TypeError); expect(() => Vec.forEach2(function* () {}, new Vec(), new Vec())).toThrow(TypeError); expect(() => Vec.forEach2(() => {}, null, new Vec())).toThrow(TypeError); expect(() => Vec.forEach2(() => {}, new Vec(), null)).toThrow(TypeError); expect(() => Vec.forEach2(() => {}, { }, new Vec())).toThrow(TypeError); expect(() => Vec.forEach2(() => {}, new Vec(), { })).toThrow(TypeError); expect(() => Vec.forEach2(() => {}, new Vec(1, 2), Vec.of(1))).toThrow(TypeError); }); test('should iterate on both array and invoke on their elements', () => { const v1 = Vec.of(1, 2, 3, 4, 5); const v2 = Vec.of(1, 2, 3, 4, 5); const ret = new Vec(); Vec.forEach2((x, y, i) => { ret.push([x, y, i]); }, v1, v2); expect(ret).toStrictEqual(new Vec( [1, 1, 0], [2, 2, 1], [3, 3, 2], [4, 4, 3], [5, 5, 4] )); }); });
export default function within(ids, coords, qx, qy, r, nodeSize) { const stack = [0, ids.length - 1, 0]; const result = []; const r2 = r * r; // recursively search for items within radius in the kd-sorted arrays while (stack.length) { const axis = stack.pop(); const right = stack.pop(); const left = stack.pop(); // if we reached "tree node", search linearly if (right - left <= nodeSize) { for (let i = left; i <= right; i++) { if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); } continue; } // otherwise find the middle index const m = (left + right) >> 1; // include the middle item if it's in range const x = coords[2 * m]; const y = coords[2 * m + 1]; if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); // queue search in halves that intersect the query if (axis === 0 ? qx - r <= x : qy - r <= y) { stack.push(left); stack.push(m - 1); stack.push(1 - axis); } if (axis === 0 ? qx + r >= x : qy + r >= y) { stack.push(m + 1); stack.push(right); stack.push(1 - axis); } } return result; } function sqDist(ax, ay, bx, by) { const dx = ax - bx; const dy = ay - by; return dx * dx + dy * dy; }
import os from time import sleep print('***********************') a = 1 pid = os.fork() if pid < 0: print("创建进程失败") elif pid == 0: print('这是新的进程') print("a =",a) a = 10000 else: sleep(1) print("这是原有进程") print("psarent a =",a) print("演示完毕")
const { expect } = require("chai"); const { GraphQLNode, combineNodes } = require("../../src"); describe("gists/idio-scalar", async () => { it("should schema globals", async () => { const User = new GraphQLNode({ name: "User", typeDefs: ` type User { id: ID name: String age: Int timeStamps: TimeStamp } type Query { user(id: ID!): User } `, resolvers: { Query: { user: () => true } } }); const Post = new GraphQLNode({ name: "Post", typeDefs: ` type Post { id: ID title: String content: Int timeStamps: TimeStamp } type Query { post(id: ID!): Post } `, resolvers: { Query: { post: () => true } } }); const { typeDefs, resolvers } = await combineNodes([User, Post], { schemaGlobals: [ ` type TimeStamp { createdAt: String updatedAt: String } ` ] }); expect(typeDefs).to.be.a("string").to.contain("type User"); expect(typeDefs).to.be.a("string").to.contain("type Post"); expect(typeDefs).to.be.a("string").to.contain("type TimeStamp"); expect(typeDefs).to.be.a("string").to.contain("type Query"); expect(typeDefs).to.be.a("string").to.contain("schema"); expect(resolvers) .to.be.a("object") .to.have.property("Query") .to.be.a("object") .to.have.property("user") .to.be.a("function"); expect(resolvers) .to.be.a("object") .to.have.property("Query") .to.be.a("object") .to.have.property("post") .to.be.a("function"); }); });
#This is a python script used to create an Ansible Inventory hosts.yml file for Confluent Platform #This script obtains the public and private IPs of the EC2 instances belonging to the ConfluentDemo group #The public IPs are updated in the hosts.yml file accordingly #!/bin/python import os #Get public IP addresses of group ConfluentDemo, sort and input it to pubIP.txt os.system("aws ec2 describe-instances --filters 'Name=tag:Name,Values=PreDemo-Confluent' | grep PublicIpAddress | grep -o -P '\d+\.\d+\.\d+\.\d+' | grep -v '^10\.' | sort -u > pubIP.txt") #Get private IP addresses of group ConfluentDemo, sort and input it to priIP.txt os.system("aws ec2 describe-instances --filters 'Name=tag:Name,Values=PreDemo-Confluent' | grep PrivateIpAddress | grep -o -P '\d+\.\d+\.\d+\.\d+' | grep -v '^10\.' | sort -u > priIP.txt") #Open pubIP.txt in read mode f1=open("priIP.txt","r") #Create an array of all the IP addresses rd=f1.read().splitlines() #Write in the Ansible Inventory hosts.yml os.system("echo all: >> hosts.yml") os.system("echo ' vars:' >> hosts.yml") os.system("echo ' ansible_connection: ssh' >> hosts.yml") os.system("echo ' ansible_ssh_user: ec2-user' >> hosts.yml") os.system("echo ' ansible_become: true' >> hosts.yml") os.system("echo ' ansible_ssh_private_key_file: /home/ec2-user/Confluent.pem' >> hosts.yml") os.system("echo ' security_mode: plaintext' >> hosts.yml") #Get preflight host IPs os.system("echo preflight: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") x1=len(rd) for i in range(0,x1): final=rd[i] #Write the preflight host IPs into hosts.yml os.system("echo ' {}:' >> hosts.yml".format(final)) #Get ssl_CA hosts #os.system("echo ssl_CA: >> hosts.yml") #os.system("echo '\thosts:' >> hosts.yml") #for i in range(0,4): # final=rd[i] # #Write the preflight hosts into hosts.yml # os.system("echo '\t\t{}:' >> hosts.yml".format(final)) #Get zookeeper hosts os.system("echo zookeeper: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") for i in range(0,3): final=rd[i] #Write the zookeeper hosts into hosts.yml os.system("echo ' {}:' >> hosts.yml".format(final)) #Get broker hosts os.system("echo broker: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") for i in range(0,3): final=rd[i] #Write the broker hosts into host.yml os.system("echo ' {}:' >> hosts.yml".format(final)) os.system("echo ' kafka:' >> hosts.yml") os.system("echo ' broker:' >> hosts.yml") os.system("echo ' id: {}' >> hosts.yml".format(i+1)) #Get schema-registry hosts os.system("echo schema-registry: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") final=rd[3] #Write the schema-registry hosts into host.yml os.system("echo ' {}:' >> hosts.yml".format(final)) #Get control-center hosts os.system("echo control-center: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") final=rd[3] os.system("echo ' {}:' >> hosts.yml".format(final)) os.system("echo ' confluent:' >> hosts.yml") os.system("echo ' control:' >> hosts.yml") os.system("echo ' center:' >> hosts.yml") os.system("echo ' config:' >> hosts.yml") final=rd[3] os.system("echo ' confluent.controlcenter.connect.cluster: {}:8083' >> hosts.yml".format(final)) #Get connect-distributed hosts os.system("echo connect-distributed: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") final=rd[3] #Write the connect-distributed hosts into host.yml os.system("echo ' {}:' >> hosts.yml".format(final)) #Get kafka-rest hosts os.system("echo kafka-rest: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") final=rd[3] #Write the kafka-rest hosts into host.yml os.system("echo ' {}:' >> hosts.yml".format(final)) #Get ksql hosts os.system("echo ksql: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") final=rd[3] #Write the ksql hosts into host.yml os.system("echo ' {}:' >> hosts.yml".format(final)) #Get tools hosts os.system("echo tools: >> hosts.yml") os.system("echo ' hosts:' >> hosts.yml") final=rd[0] #Write the tools hosts into host.yml os.system("echo ' {}:' >> hosts.yml".format(final))
const fs = require('fs'); const path = require('path'); const Ajv = require('ajv'); const ajv = new Ajv(); // Custom formats ajv.addFormat('custom-date-time', /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/); /** * Loads all the schemas in a directory into ajv */ const loadSchemas = dir => { fs.readdirSync(dir).forEach(fileName => { // eslint-disable-next-line import/no-dynamic-require const schema = require(path.join(dir, fileName)); ajv.addSchema( schema, // Common schemas should have $id, but dynamically name raw and transformed schemas schema.$id || `${dir.split(path.sep).pop()}/${path.basename(fileName, '.js')}`, ); }); }; loadSchemas(path.join(__dirname, 'schemas', 'common')); loadSchemas(path.join(__dirname, 'schemas', 'input')); loadSchemas(path.join(__dirname, 'schemas', 'output')); module.exports = (entity, schema) => { const validate = ajv.compile(schema); const valid = validate(entity); // if (!valid) console.log(validate); return valid ? [] : validate.errors; };
import React from 'react' import { useFormContext, useFieldArray } from 'react-hook-form' import FormControlLabel from '@material-ui/core/FormControlLabel' import Accordion from '@material-ui/core/Accordion' import AccordionSummary from '@material-ui/core/AccordionSummary' import AccordionDetails from '@material-ui/core/AccordionDetails' import Typography from '@material-ui/core/Typography' import Button from '@material-ui/core/Button' import Grid from '@material-ui/core/Grid' import Tooltip from '@material-ui/core/Tooltip' import Divider from '@material-ui/core/Divider' import IconButton from '@material-ui/core/IconButton' import { makeStyles } from '@material-ui/core/styles' import ExpandMoreIcon from '@material-ui/icons/ExpandMore' import DeleteIcon from '@material-ui/icons/Delete' import TextField from '@material-ui/core/TextField' import Switch from '@material-ui/core/Switch' import styles from './ActionTemplateInputs.styles' const useStyles = makeStyles(styles) function ActionTemplateInputs() { const classes = useStyles() const { control, register, watch } = useFormContext() const name = 'inputs' const { fields, remove, append } = useFieldArray({ control, name }) function addNewInput() { append({ required: false }) } return ( <div> <Button onClick={addNewInput} color="primary" className={classes.addAction} variant="contained"> Add Input </Button> {fields.map((field, index) => { function removeInput() { return remove(index) } const input = watch(`${name}[${index}]`) return ( <Accordion key={index} data-test="action-template-input"> <AccordionSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.title}> {input?.name || `Input ${index + 1}`} </Typography> {input?.description && ( <Typography className={classes.type}> {input.description.substring(0, 100)} </Typography> )} </AccordionSummary> <AccordionDetails> <Grid container spacing={8} style={{ flexGrow: 1 }}> <Grid item xs={10} md={6} lg={4}> <TextField name={`${name}[${index}].name`} label="Name" className={classes.field} fullWidth inputRef={register} /> <TextField name={`${name}[${index}].description`} label="Description" className={classes.field} fullWidth inputRef={register} /> <div className={classes.required}> <FormControlLabel control={ <Switch name={`${name}[${index}].required`} inputRef={register} defaultChecked={input?.required} /> } label="Required" /> </div> </Grid> <Grid item xs={2} lg={1}> <div className={classes.delete}> <Tooltip placement="bottom" title="Remove Input"> <IconButton onClick={removeInput} color="secondary" className={classes.deleteButton}> <DeleteIcon /> </IconButton> </Tooltip> </div> </Grid> <Grid item xs={6} lg={2}> {input?.type === 'userInput' && ( <TextField name={`${name}[${index}].variableName`} label="Variable Name" className={classes.field} fullWidth inputRef={register} /> )} </Grid> </Grid> </AccordionDetails> <Divider /> </Accordion> ) })} </div> ) } export default ActionTemplateInputs
import attr from viberio.types.requests import ViberReqestObject @attr.s class ViberSeenRequest(ViberReqestObject): message_token: int = attr.ib() user_id: str = attr.ib()
const messageDef = ` type User { id: Int! firstName: String! lastName: String! email: String! } `; module.exports = messageDef;
/* * Dutch */ eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('1.2i=u F("z","1e","S","2g","1F","1v","1l","z");1.1d=2;1.R=u F("O","2f","20","1E","1B","1t","1o","1k","1h","1c","19","V");1.3={};1.3["Q"]="P";1.3["N"]="M G/j 1P\\n"+"(c) I.A 1z-1s / 1q: 1n 1m\\n"+"L 4 5 1f 1b 1a t: D://U.I.A/X/T/\\n"+"10 11 5 12 13. 14 D://15.16/17/18.2e 4 2a."+"\\n\\n"+"G h:\\n"+"- E 5 \\1L \\1J p 8 f r 7 v\\n"+"- E 5 "+J.w(1y)+", "+J.w(1x)+" p 8 f o 7 v\\n"+"- 1r 5 1p 9 y 5 1u p 4 f x h.";1.3["1w"]="\\n\\n"+"j h:\\n"+"- i y f 1j 1i 1A l 1g 1C 8 l 7 1D\\n"+"- k K-C 8 l 7 1H\\n"+"- k C B q 4 f x h.";1.3["W"]="1K r (9 4 g)";1.3["1M"]="1N o (9 4 g)";1.3["1O"]="L t Z";1.3["1Q"]="1R o (9 4 g)";1.3["1S"]="1T r (9 4 g)";1.3["1U"]="1V 1W";1.3["1X"]="i B q 8 7 1Y";1.3["1Z"]=" (H)";1.3["21"]="22 %s 23";1.3["24"]="0,6";1.3["25"]="2c";1.3["2b"]="(H)";1.3["29"]="(K-)i k q 8 5 28 7 27";1.3["26"]="%d-%m-%Y";1.3["2d"]="%a, %e %b %Y";1.3["1I"]="1G";1.3["2h"]="j:";',62,143,'|Calendar||_TT|voor|de||te|om|ingedrukt||||||een|menu|selectie|Klik|Tijd|of|het|||maand|knoppen|sleep|jaar||naar|new|selecteren|fromCharCode|snellere|op|Zondag|com|en|klik|http|Gebruik|Array|Datum|vandaag|dynarch|String|Shift|Ga|DHTML|ABOUT|Januari|Info|INFO|_MN|Dinsdag|calendar|www|December|PREV_YEAR|projects||Vandaag|Verspreid|onder|GNU|LGPL|Zie|gnu|org|licenses|lgpl|November|versie|recente|Oktober|_SDN_len|Maandag|meest|tijd|September|onderdeel|willekeurig|Augustus|Zaterdag|Bazon|Mihai|Juli|muis|Author|Houd|2005|Juni|genoemde|Vrijdag|ABOUT_TIME|0x203a|0x2039|2002|van|Mei|gedeelte|verhogen|April|Donderdag|wk|verlagen|WK|xbb|Vorig|xab|PREV_MONTH|Vorige|GO_TODAY|Selector|NEXT_MONTH|Volgende|NEXT_YEAR|Volgend|SEL_DATE|Selecteer|datum|DRAG_TO_MOVE|verplaatsen|PART_TODAY|Maart|DAY_FIRST|Toon|eerst|WEEKEND|CLOSE|DEF_DATE_FORMAT|veranderen|waarde|TIME_PART|details|TODAY|Sluiten|TT_DATE_FORMAT|html|Februari|Woensdag|TIME|_DN'.split('|'),0,{}))
const fs = require('fs'); const package = JSON.parse(fs.readFileSync('package.json')); const plotlyJsVersion = (package.dependencies && package.dependencies['plotly.js']) || (package.devDependencies && package.devDependencies['plotly.js']); fs.copyFile( 'node_modules/plotly.js/dist/plotly.min.js', `dash_extendable_graph/plotly.min.js`, err => { if (err) { throw err; } console.log('copied plotly.js', plotlyJsVersion); } );
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * File Name: exception-002 * ECMA Section: * Description: Tests for JavaScript Standard Exceptions * * Construct error. * * Author: christine@netscape.com * Date: 31 August 1998 */ var SECTION = "exception-002"; var VERSION = "js1_4"; var TITLE = "Tests for JavaScript Standard Exceptions: ConstructError"; startTest(); writeHeaderToLog( SECTION + " "+ TITLE); Construct_1(); test(); function Construct_1() { result = "failed: no exception thrown"; exception = null; try { result = new Math(); } catch ( e ) { result = "passed: threw exception", exception = e.toString(); } finally { new TestCase( SECTION, "new Math() [ exception is " + exception +" ]", "passed: threw exception", result ); } }
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {AccessServerAdapter} from '../amp-access-server'; import {removeFragment} from '../../../../src/url'; import * as sinon from 'sinon'; describe('AccessServerAdapter', () => { let sandbox; let clock; let validConfig; let context; let contextMock; let meta; beforeEach(() => { sandbox = sinon.sandbox.create(); clock = sandbox.useFakeTimers(); validConfig = { 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID', }; meta = document.createElement('meta'); meta.setAttribute('name', 'i-amp-access-state'); meta.setAttribute('content', 'STATE1'); document.head.appendChild(meta); context = { buildUrl: () => {}, collectUrlVars: () => {}, }; contextMock = sandbox.mock(context); }); afterEach(() => { contextMock.verify(); sandbox.restore(); if (meta.parentNode) { document.head.removeChild(meta); } }); describe('config', () => { it('should load valid config', () => { const adapter = new AccessServerAdapter(window, validConfig, context); expect(adapter.clientAdapter_.authorizationUrl_).to .equal('https://acme.com/a?rid=READER_ID'); expect(adapter.clientAdapter_.pingbackUrl_).to .equal('https://acme.com/p?rid=READER_ID'); expect(adapter.serverState_).to.equal('STATE1'); expect(adapter.isProxyOrigin_).to.be.false; }); it('should fail if config is invalid', () => { delete validConfig['authorization']; expect(() => { new AccessServerAdapter(window, validConfig, context); }).to.throw(/"authorization" URL must be specified/); }); it('should tolerate when i-amp-access-state is missing', () => { document.head.removeChild(meta); const adapter = new AccessServerAdapter(window, validConfig, context); expect(adapter.serverState_).to.be.null; }); }); describe('runtime', () => { let adapter; let clientAdapter; let clientAdapterMock; let xhrMock; let responseDoc; let targetElement1, targetElement2; beforeEach(() => { adapter = new AccessServerAdapter(window, validConfig, context); xhrMock = sandbox.mock(adapter.xhr_); clientAdapter = { getAuthorizationUrl: () => validConfig['authorization'], isAuthorizationEnabled: () => true, authorize: () => Promise.resolve({}), pingback: () => Promise.resolve(), }; clientAdapterMock = sandbox.mock(clientAdapter); adapter.clientAdapter_ = clientAdapter; adapter.isProxyOrigin_ = true; responseDoc = document.createElement('div'); const responseAccessData = document.createElement('script'); responseAccessData.setAttribute('type', 'application/json'); responseAccessData.setAttribute('id', 'amp-access-data'); responseAccessData.textContent = JSON.stringify({'access': 'A'}); responseDoc.appendChild(responseAccessData); targetElement1 = document.createElement('div'); targetElement1.setAttribute('i-amp-access-id', '1/1'); document.body.appendChild(targetElement1); targetElement2 = document.createElement('div'); targetElement2.setAttribute('i-amp-access-id', '1/2'); document.body.appendChild(targetElement2); }); afterEach(() => { clientAdapterMock.verify(); xhrMock.verify(); }); describe('authorize', () => { it('should fallback to client auth when not on proxy', () => { adapter.isProxyOrigin_ = false; const p = Promise.resolve(); clientAdapterMock.expects('authorize').returns(p).once(); xhrMock.expects('fetchDocument').never(); const result = adapter.authorize(); expect(result).to.equal(p); }); it('should fallback to client auth w/o server state', () => { adapter.serverState_ = null; const p = Promise.resolve(); clientAdapterMock.expects('authorize').returns(p).once(); xhrMock.expects('fetchDocument').never(); const result = adapter.authorize(); expect(result).to.equal(p); }); it('should execute authorize-and-fill', () => { adapter.serviceUrl_ = 'http://localhost:8000/af'; contextMock.expects('collectUrlVars') .withExactArgs( 'https://acme.com/a?rid=READER_ID', /* useAuthData */ false) .returns(Promise.resolve({ 'READER_ID': 'reader1', 'OTHER': 123, })) .once(); const request = { 'url': removeFragment(window.location.href), 'state': 'STATE1', 'vars': { 'READER_ID': 'reader1', 'OTHER': '123', }, }; xhrMock.expects('fetchDocument') .withExactArgs('http://localhost:8000/af', { method: 'POST', body: 'request=' + encodeURIComponent(JSON.stringify(request)), headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .returns(Promise.resolve(responseDoc)) .once(); const replaceSectionsStub = sandbox.stub(adapter, 'replaceSections_', () => { return Promise.resolve(); }); return adapter.authorize().then(response => { expect(response).to.exist; expect(response.access).to.equal('A'); expect(replaceSectionsStub.callCount).to.equal(1); }); }); it('should fail when XHR fails', () => { adapter.serviceUrl_ = 'http://localhost:8000/af'; contextMock.expects('collectUrlVars') .withExactArgs( 'https://acme.com/a?rid=READER_ID', /* useAuthData */ false) .returns(Promise.resolve({ 'READER_ID': 'reader1', 'OTHER': 123, })) .once(); const request = { 'url': removeFragment(window.location.href), 'state': 'STATE1', 'vars': { 'READER_ID': 'reader1', 'OTHER': '123', }, }; xhrMock.expects('fetchDocument') .withExactArgs('http://localhost:8000/af', { method: 'POST', body: 'request=' + encodeURIComponent(JSON.stringify(request)), headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .returns(Promise.reject('intentional')) .once(); return adapter.authorize().then(() => { throw new Error('must never happen'); }, error => { expect(error).to.match(/intentional/); }); }); it('should time out XHR fetch', () => { adapter.serviceUrl_ = 'http://localhost:8000/af'; contextMock.expects('collectUrlVars') .withExactArgs( 'https://acme.com/a?rid=READER_ID', /* useAuthData */ false) .returns(Promise.resolve({ 'READER_ID': 'reader1', 'OTHER': 123, })) .once(); const request = { 'url': removeFragment(window.location.href), 'state': 'STATE1', 'vars': { 'READER_ID': 'reader1', 'OTHER': '123', }, }; xhrMock.expects('fetchDocument') .withExactArgs('http://localhost:8000/af', { method: 'POST', body: 'request=' + encodeURIComponent(JSON.stringify(request)), headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .returns(new Promise(() => {})) // Never resolved. .once(); const promise = adapter.authorize(); return Promise.resolve().then(() => { clock.tick(3001); return promise; }).then(() => { throw new Error('must never happen'); }, error => { expect(error).to.match(/timeout/); }); }); it('should replace sections', () => { const responseElement1 = document.createElement('div'); responseElement1.setAttribute('i-amp-access-id', '1/1'); responseElement1.textContent = 'a1'; responseDoc.appendChild(responseElement1); const responseElement2 = document.createElement('div'); responseElement2.setAttribute('i-amp-access-id', '1/2'); responseElement2.textContent = 'a2'; responseDoc.appendChild(responseElement2); const unknownResponseElement3 = document.createElement('div'); unknownResponseElement3.setAttribute('i-amp-access-id', 'a3'); unknownResponseElement3.textContent = 'a3'; responseDoc.appendChild(unknownResponseElement3); return adapter.replaceSections_(responseDoc).then(() => { expect(document.querySelector('[i-amp-access-id="1/1"]').textContent) .to.equal('a1'); expect(document.querySelector('[i-amp-access-id="1/2"]').textContent) .to.equal('a2'); expect(document.querySelector('[i-amp-access-id=a3]')).to.be.null; }); }); }); describe('pingback', () => { it('should always send client pingback', () => { clientAdapterMock.expects('pingback') .returns(Promise.resolve()) .once(); adapter.pingback(); }); }); }); });
# Author: Moises Henrique Pereira # this class handle the interface's functions tests # command to run pytest showing print: pytest -s import pytest import os import sys from PyQt5 import QtWidgets from ui.mainTest import StaticObjects # the function initializeView expect a list type # send another type as parameter would arrise an assertionError @pytest.mark.parametrize('datasets', [1, 2.9, 'str', False, ('t1', 't2'), None]) def test_CIV_initializeView_wrong_type_parameter(datasets): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.initializeView(datasets) # the function initializeView expect a list type fill with string # send another content inside the list would arrise an assertionError @pytest.mark.parametrize('datasets', [[1], [2.9], [False], [('t1', 't2')], [None]]) def test_CIV_initializeView_wrong_array_type_parameters(datasets): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.initializeView(datasets) # the function initializeView expect a list type fill with string # a valid string inside a list would not arrise assertionError def test_CIV_initializeView_right_parameter(): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() datasetsPath = os.getcwd() datasetsPath = os.path.join(datasetsPath, '..', 'datasets') _, _, datasetsName = next(os.walk(datasetsPath)) counterfactualInterfaceView.initializeView(datasetsName) # the function getChosenDataset returns the selected dataset # to do this test lets consider that the first dataset is the selected dataset def test_CIV_getChosenDataset_right_parameter(): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() datasetsPath = os.getcwd() datasetsPath = os.path.join(datasetsPath, '..', 'datasets') _, _, datasetsName = next(os.walk(datasetsPath)) counterfactualInterfaceView.initializeView(datasetsName) chosenDataset = counterfactualInterfaceView.getChosenDataset() assert chosenDataset == datasetsName[0] # the function showOriginalClass expect a not none parameter # send none would arrise an assertionError def test_CIV_showOriginalClass_none_parameter(): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showOriginalClass(None) # the function showOriginalClass expect a not none parameter # send a different content would not arrise an assertionError @pytest.mark.parametrize('originalClass', [0, [0], (0), [(0)]]) def test_CIV_showOriginalClass_right_parameter(originalClass): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showOriginalClass(originalClass) # the function showCounterfactualClass expect a not none parameter # send none would arrise an assertionError def test_CIV_showCounterfactualClass_none_parameter(): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showCounterfactualClass(None) # the function showCounterfactualClass expect a not none parameter # send a different content would not arrise an assertionError @pytest.mark.parametrize('originalClass', [1, [1], (1), [(1)]]) def test_CIV_showCounterfactualClass_right_parameter(originalClass): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showCounterfactualClass(originalClass) # the function addFeatureWidget expect a qWidget as parameter # send another type would arrise an assertionError @pytest.mark.parametrize('featureWidget', [1, 2.9, 'str', False, ('t1', 't2'), None]) def test_CIV_addFeatureWidget_wrong_parameter(featureWidget): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.addFeatureWidget(featureWidget) # the function addFeatureWidget expect a qWidget as parameter # send it would not arrise an assertionError def test_CIV_addFeatureWidget_right_parameter(): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() widget = QtWidgets.QWidget() counterfactualInterfaceView.addFeatureWidget(widget) # the function showCounterfactualStatus expect a string as parameter # send another type would not arrise an assertionError @pytest.mark.parametrize('status', [1, 2.9, False, ('t1', 't2'), None]) def test_CIV_showCounterfactualStatus_wrong_parameter(status): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showCounterfactualStatus(status) # the function showCounterfactualStatus expect a string as parameter # send it would not arrise an assertionError def test_CIV_showCounterfactualStatus_right_parameter(): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showCounterfactualStatus('Status: OK') # the function showCounterfactualComparison expect a 2d list as parameter # where each lists inside it need to has 3 elements # send another type as parameter would arrise an assertionError @pytest.mark.parametrize('counterfactualComparison', [1, 2.9, False, ('t1', 't2'), None]) def test_CIV_showCounterfactualComparison_wrong_type_parameter(counterfactualComparison): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showCounterfactualComparison(counterfactualComparison) # the function showCounterfactualComparison expect a 2d list as parameter # where each lists inside it need to has 3 elements # send a list where each list inside it has not 3 items would arrise an assertionError @pytest.mark.parametrize('counterfactualComparison', [[[1]], [[1, 2.9]], [[1, 2.9, False, ('t1', 't2')]]]) def test_CIV_showCounterfactualComparison_wrong_length_parameter(counterfactualComparison): with pytest.raises(AssertionError): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showCounterfactualComparison(counterfactualComparison) # the function showCounterfactualComparison expect a 2d list as parameter # where each lists inside it need to has 3 elements # send it would not arrise an assertionError @pytest.mark.parametrize('counterfactualComparison', [[['feature', '0', '1']], [['feature', '0', 1]], [['feature', 0, '1']]]) def test_CIV_showCounterfactualComparison_right_parameter(counterfactualComparison): app = QtWidgets.QApplication(sys.argv) counterfactualInterfaceView = StaticObjects.staticCounterfactualInterfaceView() counterfactualInterfaceView.showCounterfactualComparison(counterfactualComparison)
(function() { /*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2017 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 2.15.0 */ var enifed, requireModule, Ember; var mainContext = this; // Used in ember-environment/lib/global.js (function() { var isNode = typeof window === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; if (!isNode) { Ember = this.Ember = this.Ember || {}; } if (typeof Ember === 'undefined') { Ember = {}; } if (typeof Ember.__loader === 'undefined') { var registry = {}; var seen = {}; enifed = function(name, deps, callback) { var value = { }; if (!callback) { value.deps = []; value.callback = deps; } else { value.deps = deps; value.callback = callback; } registry[name] = value; }; requireModule = function(name) { return internalRequire(name, null); }; // setup `require` module requireModule['default'] = requireModule; requireModule.has = function registryHas(moduleName) { return !!registry[moduleName] || !!registry[moduleName + '/index']; }; function missingModule(name, referrerName) { if (referrerName) { throw new Error('Could not find module ' + name + ' required by: ' + referrerName); } else { throw new Error('Could not find module ' + name); } } function internalRequire(_name, referrerName) { var name = _name; var mod = registry[name]; if (!mod) { name = name + '/index'; mod = registry[name]; } var exports = seen[name]; if (exports !== undefined) { return exports; } exports = seen[name] = {}; if (!mod) { missingModule(_name, referrerName); } var deps = mod.deps; var callback = mod.callback; var reified = new Array(deps.length); for (var i = 0; i < deps.length; i++) { if (deps[i] === 'exports') { reified[i] = exports; } else if (deps[i] === 'require') { reified[i] = requireModule; } else { reified[i] = internalRequire(deps[i], name); } } callback.apply(this, reified); return exports; } requireModule._eak_seen = registry; Ember.__loader = { define: enifed, require: requireModule, registry: registry }; } else { enifed = Ember.__loader.define; requireModule = Ember.__loader.require; } })(); enifed('ember-babel', ['exports'], function (exports) { 'use strict'; exports.classCallCheck = classCallCheck; exports.inherits = inherits; exports.taggedTemplateLiteralLoose = taggedTemplateLiteralLoose; exports.createClass = createClass; exports.defaults = defaults; function classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : defaults(subClass, superClass); } function taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } 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); } } function createClass(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; } function defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } var possibleConstructorReturn = exports.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError('this hasn\'t been initialized - super() hasn\'t been called'); } return call && (typeof call === 'object' || typeof call === 'function') ? call : self; }; var slice = exports.slice = Array.prototype.slice; }); enifed('ember-debug/deprecate', ['exports', 'ember-debug/error', 'ember-console', 'ember-environment', 'ember-debug/handlers'], function (exports, _error, _emberConsole, _emberEnvironment, _handlers) { 'use strict'; exports.missingOptionsUntilDeprecation = exports.missingOptionsIdDeprecation = exports.missingOptionsDeprecation = exports.registerHandler = undefined; /** @module ember @submodule ember-debug */ /** Allows for runtime registration of handler functions that override the default deprecation behavior. Deprecations are invoked by calls to [Ember.deprecate](https://emberjs.com/api/classes/Ember.html#method_deprecate). The following example demonstrates its usage by registering a handler that throws an error if the message contains the word "should", otherwise defers to the default handler. ```javascript Ember.Debug.registerDeprecationHandler((message, options, next) => { if (message.indexOf('should') !== -1) { throw new Error(`Deprecation message with should: ${message}`); } else { // defer to whatever handler was registered before this one next(message, options); } }); ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the deprecation call.</li> <li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li> <li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerDeprecationHandler @for Ember.Debug @param handler {Function} A function to handle deprecation calls. @since 2.1.0 */ var registerHandler = function () {}; /*global __fail__*/ var missingOptionsDeprecation = void 0, missingOptionsIdDeprecation = void 0, missingOptionsUntilDeprecation = void 0, deprecate = void 0; if (true) { exports.registerHandler = registerHandler = function registerHandler(handler) { (0, _handlers.registerHandler)('deprecate', handler); }; var formatMessage = function formatMessage(_message, options) { var message = _message; if (options && options.id) { message = message + (' [deprecation id: ' + options.id + ']'); } if (options && options.url) { message += ' See ' + options.url + ' for more details.'; } return message; }; registerHandler(function logDeprecationToConsole(message, options) { var updatedMessage = formatMessage(message, options); _emberConsole.default.warn('DEPRECATION: ' + updatedMessage); }); var captureErrorForStack = void 0; if (new Error().stack) { captureErrorForStack = function () { return new Error(); }; } else { captureErrorForStack = function () { try { __fail__.fail(); } catch (e) { return e; } }; } registerHandler(function logDeprecationStackTrace(message, options, next) { if (_emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION) { var stackStr = ''; var error = captureErrorForStack(); var stack = void 0; if (error.stack) { if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n'); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n'); } stackStr = '\n ' + stack.slice(2).join('\n '); } var updatedMessage = formatMessage(message, options); _emberConsole.default.warn('DEPRECATION: ' + updatedMessage + stackStr); } else { next.apply(undefined, arguments); } }); registerHandler(function raiseOnDeprecation(message, options, next) { if (_emberEnvironment.ENV.RAISE_ON_DEPRECATION) { var updatedMessage = formatMessage(message); throw new _error.default(updatedMessage); } else { next.apply(undefined, arguments); } }); exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `Ember.deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `Ember.deprecate` you must provide `id` in options.'; exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation = 'When calling `Ember.deprecate` you must provide `until` in options.'; /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method deprecate @param {String} message A description of the deprecation. @param {Boolean} test A boolean. If falsy, the deprecation will be displayed. @param {Object} options @param {String} options.id A unique id for this deprecation. The id can be used by Ember debugging tools to change the behavior (raise, log or silence) for that specific deprecation. The id should be namespaced by dots, e.g. "view.helper.select". @param {string} options.until The version of Ember when this deprecation warning will be removed. @param {String} [options.url] An optional url to the transition guide on the emberjs.com website. @for Ember @public @since 1.0.0 */ deprecate = function deprecate(message, test, options) { if (!options || !options.id && !options.until) { deprecate(missingOptionsDeprecation, false, { id: 'ember-debug.deprecate-options-missing', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.id) { deprecate(missingOptionsIdDeprecation, false, { id: 'ember-debug.deprecate-id-missing', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.until) { deprecate(missingOptionsUntilDeprecation, options && options.until, { id: 'ember-debug.deprecate-until-missing', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } _handlers.invoke.apply(undefined, ['deprecate'].concat(Array.prototype.slice.call(arguments))); }; } exports.default = deprecate; exports.registerHandler = registerHandler; exports.missingOptionsDeprecation = missingOptionsDeprecation; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation; }); enifed("ember-debug/error", ["exports", "ember-babel"], function (exports, _emberBabel) { "use strict"; function ExtendBuiltin(klass) { function ExtendableBuiltin() { klass.apply(this, arguments); } ExtendableBuiltin.prototype = Object.create(klass.prototype); ExtendableBuiltin.prototype.constructor = ExtendableBuiltin; return ExtendableBuiltin; } /** A subclass of the JavaScript Error object for use in Ember. @class Error @namespace Ember @extends Error @constructor @public */ var EmberError = function (_ExtendBuiltin) { (0, _emberBabel.inherits)(EmberError, _ExtendBuiltin); function EmberError(message) { (0, _emberBabel.classCallCheck)(this, EmberError); var _this = (0, _emberBabel.possibleConstructorReturn)(this, _ExtendBuiltin.call(this)); if (!(_this instanceof EmberError)) { var _ret; return _ret = new EmberError(message), (0, _emberBabel.possibleConstructorReturn)(_this, _ret); } var error = Error.call(_this, message); _this.stack = error.stack; _this.description = error.description; _this.fileName = error.fileName; _this.lineNumber = error.lineNumber; _this.message = error.message; _this.name = error.name; _this.number = error.number; _this.code = error.code; return _this; } return EmberError; }(ExtendBuiltin(Error)); exports.default = EmberError; }); enifed('ember-debug/features', ['exports', 'ember-environment', 'ember/features'], function (exports, _emberEnvironment, _features) { 'use strict'; exports.default = isEnabled; var FEATURES = _features.FEATURES; /** The hash of enabled Canary features. Add to this, any canary features before creating your application. Alternatively (and recommended), you can also define `EmberENV.FEATURES` if you need to enable features flagged at runtime. @class FEATURES @namespace Ember @static @since 1.1.0 @public */ // Auto-generated /** Determine whether the specified `feature` is enabled. Used by Ember's build tools to exclude experimental features from beta/stable builds. You can define the following configuration options: * `EmberENV.ENABLE_OPTIONAL_FEATURES` - enable any features that have not been explicitly enabled/disabled. @method isEnabled @param {String} feature The feature to check @return {Boolean} @for Ember.FEATURES @since 1.1.0 @public */ function isEnabled(feature) { var featureValue = FEATURES[feature]; if (featureValue === true || featureValue === false || featureValue === undefined) { return featureValue; } else if (_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES) { return true; } else { return false; } } }); enifed('ember-debug/handlers', ['exports'], function (exports) { 'use strict'; var HANDLERS = exports.HANDLERS = {}; var registerHandler = function () {}; var invoke = function () {}; if (true) { exports.registerHandler = registerHandler = function registerHandler(type, callback) { var nextHandler = HANDLERS[type] || function () {}; HANDLERS[type] = function (message, options) { callback(message, options, nextHandler); }; }; exports.invoke = invoke = function invoke(type, message, test, options) { if (test) { return; } var handlerForType = HANDLERS[type]; if (handlerForType) { handlerForType(message, options); } }; } exports.registerHandler = registerHandler; exports.invoke = invoke; }); enifed('ember-debug/index', ['exports', 'ember-debug/warn', 'ember-debug/deprecate', 'ember-debug/features', 'ember-debug/error', 'ember-debug/testing', 'ember-environment', 'ember-console', 'ember/features'], function (exports, _warn2, _deprecate2, _features, _error, _testing, _emberEnvironment, _emberConsole, _features2) { 'use strict'; exports._warnIfUsingStrippedFeatureFlags = exports.getDebugFunction = exports.setDebugFunction = exports.deprecateFunc = exports.runInDebug = exports.debugFreeze = exports.debugSeal = exports.deprecate = exports.debug = exports.warn = exports.info = exports.assert = exports.setTesting = exports.isTesting = exports.Error = exports.isFeatureEnabled = exports.registerDeprecationHandler = exports.registerWarnHandler = undefined; Object.defineProperty(exports, 'registerWarnHandler', { enumerable: true, get: function () { return _warn2.registerHandler; } }); Object.defineProperty(exports, 'registerDeprecationHandler', { enumerable: true, get: function () { return _deprecate2.registerHandler; } }); Object.defineProperty(exports, 'isFeatureEnabled', { enumerable: true, get: function () { return _features.default; } }); Object.defineProperty(exports, 'Error', { enumerable: true, get: function () { return _error.default; } }); Object.defineProperty(exports, 'isTesting', { enumerable: true, get: function () { return _testing.isTesting; } }); Object.defineProperty(exports, 'setTesting', { enumerable: true, get: function () { return _testing.setTesting; } }); var DEFAULT_FEATURES = _features2.DEFAULT_FEATURES, FEATURES = _features2.FEATURES; // These are the default production build versions: var noop = function () {}; var assert = noop; var info = noop; var warn = noop; var debug = noop; var deprecate = noop; var debugSeal = noop; var debugFreeze = noop; var runInDebug = noop; var setDebugFunction = noop; var getDebugFunction = noop; var deprecateFunc = function () { return arguments[arguments.length - 1]; }; if (true) { exports.setDebugFunction = setDebugFunction = function (type, callback) { switch (type) { case 'assert': return exports.assert = assert = callback; case 'info': return exports.info = info = callback; case 'warn': return exports.warn = warn = callback; case 'debug': return exports.debug = debug = callback; case 'deprecate': return exports.deprecate = deprecate = callback; case 'debugSeal': return exports.debugSeal = debugSeal = callback; case 'debugFreeze': return exports.debugFreeze = debugFreeze = callback; case 'runInDebug': return exports.runInDebug = runInDebug = callback; case 'deprecateFunc': return exports.deprecateFunc = deprecateFunc = callback; } }; exports.getDebugFunction = getDebugFunction = function (type) { switch (type) { case 'assert': return assert; case 'info': return info; case 'warn': return warn; case 'debug': return debug; case 'deprecate': return deprecate; case 'debugSeal': return debugSeal; case 'debugFreeze': return debugFreeze; case 'runInDebug': return runInDebug; case 'deprecateFunc': return deprecateFunc; } }; } /** @module ember @submodule ember-debug */ /** @class Ember @public */ if (true) { /** Define an assertion that will throw an exception if the condition is not met. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript // Test for truthiness Ember.assert('Must pass a valid object', obj); // Fail unconditionally Ember.assert('This code path should never be run'); ``` @method assert @param {String} desc A description of the assertion. This will become the text of the Error thrown if the assertion fails. @param {Boolean} test Must be truthy for the assertion to pass. If falsy, an exception will be thrown. @public @since 1.0.0 */ setDebugFunction('assert', function assert(desc, test) { if (!test) { throw new _error.default('Assertion Failed: ' + desc); } }); /** Display a debug notice. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript Ember.debug('I\'m a debug notice!'); ``` @method debug @param {String} message A debug message to display. @public */ setDebugFunction('debug', function debug(message) { _emberConsole.default.debug('DEBUG: ' + message); }); /** Display an info notice. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method info @private */ setDebugFunction('info', function info() { _emberConsole.default.info.apply(undefined, arguments); }); /** Alias an old, deprecated method with its new counterpart. Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the assigned method is called. * In a production build, this method is defined as an empty function (NOP). ```javascript Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod); ``` @method deprecateFunc @param {String} message A description of the deprecation. @param {Object} [options] The options object for Ember.deprecate. @param {Function} func The new function called to replace its deprecated counterpart. @return {Function} A new function that wraps the original function with a deprecation warning @private */ setDebugFunction('deprecateFunc', function deprecateFunc() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 3) { var message = args[0], options = args[1], func = args[2]; return function () { deprecate(message, false, options); return func.apply(this, arguments); }; } else { var _message = args[0], _func = args[1]; return function () { deprecate(_message); return _func.apply(this, arguments); }; } }); /** Run a function meant for debugging. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript Ember.runInDebug(() => { Ember.Component.reopen({ didInsertElement() { console.log("I'm happy"); } }); }); ``` @method runInDebug @param {Function} func The function to be executed. @since 1.5.0 @public */ setDebugFunction('runInDebug', function runInDebug(func) { func(); }); setDebugFunction('debugSeal', function debugSeal(obj) { Object.seal(obj); }); setDebugFunction('debugFreeze', function debugFreeze(obj) { Object.freeze(obj); }); setDebugFunction('deprecate', _deprecate2.default); setDebugFunction('warn', _warn2.default); } var _warnIfUsingStrippedFeatureFlags = void 0; if (true && !(0, _testing.isTesting)()) { /** Will call `Ember.warn()` if ENABLE_OPTIONAL_FEATURES or any specific FEATURES flag is truthy. This method is called automatically in debug canary builds. @private @method _warnIfUsingStrippedFeatureFlags @return {void} */ exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags = function _warnIfUsingStrippedFeatureFlags(FEATURES, knownFeatures, featuresWereStripped) { if (featuresWereStripped) { warn('Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.', !_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES, { id: 'ember-debug.feature-flag-with-features-stripped' }); var keys = Object.keys(FEATURES || {}); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key === 'isEnabled' || !(key in knownFeatures)) { continue; } warn('FEATURE["' + key + '"] is set as enabled, but FEATURE flags are only available in canary builds.', !FEATURES[key], { id: 'ember-debug.feature-flag-with-features-stripped' }); } } }; // Complain if they're using FEATURE flags in builds other than canary FEATURES['features-stripped-test'] = true; var featuresWereStripped = true; if ((0, _features.default)('features-stripped-test')) { featuresWereStripped = false; } delete FEATURES['features-stripped-test']; _warnIfUsingStrippedFeatureFlags(_emberEnvironment.ENV.FEATURES, DEFAULT_FEATURES, featuresWereStripped); // Inform the developer about the Ember Inspector if not installed. var isFirefox = _emberEnvironment.environment.isFirefox; var isChrome = _emberEnvironment.environment.isChrome; if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) { window.addEventListener('load', function () { if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) { var downloadURL = void 0; if (isChrome) { downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi'; } else if (isFirefox) { downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/'; } debug('For more advanced debugging, install the Ember Inspector from ' + downloadURL); } }, false); } } exports.assert = assert; exports.info = info; exports.warn = warn; exports.debug = debug; exports.deprecate = deprecate; exports.debugSeal = debugSeal; exports.debugFreeze = debugFreeze; exports.runInDebug = runInDebug; exports.deprecateFunc = deprecateFunc; exports.setDebugFunction = setDebugFunction; exports.getDebugFunction = getDebugFunction; exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; }); enifed("ember-debug/testing", ["exports"], function (exports) { "use strict"; exports.isTesting = isTesting; exports.setTesting = setTesting; var testing = false; function isTesting() { return testing; } function setTesting(value) { testing = !!value; } }); enifed('ember-debug/warn', ['exports', 'ember-console', 'ember-debug/deprecate', 'ember-debug/handlers'], function (exports, _emberConsole, _deprecate, _handlers) { 'use strict'; exports.missingOptionsDeprecation = exports.missingOptionsIdDeprecation = exports.registerHandler = undefined; var registerHandler = function () {}; var warn = function () {}; var missingOptionsDeprecation = void 0, missingOptionsIdDeprecation = void 0; /** @module ember @submodule ember-debug */ if (true) { /** Allows for runtime registration of handler functions that override the default warning behavior. Warnings are invoked by calls made to [Ember.warn](https://emberjs.com/api/classes/Ember.html#method_warn). The following example demonstrates its usage by registering a handler that does nothing overriding Ember's default warning behavior. ```javascript // next is not called, so no warnings get the default behavior Ember.Debug.registerWarnHandler(() => {}); ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the warn call. </li> <li> <code>options</code> - An object passed in with the warn call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerWarnHandler @for Ember.Debug @param handler {Function} A function to handle warnings. @since 2.1.0 */ exports.registerHandler = registerHandler = function registerHandler(handler) { (0, _handlers.registerHandler)('warn', handler); }; registerHandler(function logWarning(message, options) { _emberConsole.default.warn('WARNING: ' + message); if ('trace' in _emberConsole.default) { _emberConsole.default.trace(); } }); exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `Ember.warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `Ember.warn` you must provide `id` in options.'; /** Display a warning with the provided message. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method warn @param {String} message A warning to display. @param {Boolean} test An optional boolean. If falsy, the warning will be displayed. @param {Object} options An object that can be used to pass a unique `id` for this warning. The `id` can be used by Ember debugging tools to change the behavior (raise, log, or silence) for that specific warning. The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped" @for Ember @public @since 1.0.0 */ warn = function warn(message, test, options) { if (arguments.length === 2 && typeof test === 'object') { options = test; test = false; } if (!options) { (0, _deprecate.default)(missingOptionsDeprecation, false, { id: 'ember-debug.warn-options-missing', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.id) { (0, _deprecate.default)(missingOptionsIdDeprecation, false, { id: 'ember-debug.warn-id-missing', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } (0, _handlers.invoke)('warn', message, test, options); }; } exports.default = warn; exports.registerHandler = registerHandler; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; exports.missingOptionsDeprecation = missingOptionsDeprecation; }); enifed('ember-testing/adapters/adapter', ['exports', 'ember-runtime'], function (exports, _emberRuntime) { 'use strict'; function K() { return this; } /** @module ember @submodule ember-testing */ /** The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks. @class Adapter @namespace Ember.Test @public */ exports.default = _emberRuntime.Object.extend({ /** This callback will be called whenever an async operation is about to start. Override this to call your framework's methods that handle async operations. @public @method asyncStart */ asyncStart: K, /** This callback will be called whenever an async operation has completed. @public @method asyncEnd */ asyncEnd: K, /** Override this method with your testing framework's false assertion. This function is called whenever an exception occurs causing the testing promise to fail. QUnit example: ```javascript exception: function(error) { ok(false, error); }; ``` @public @method exception @param {String} error The exception to be raised. */ exception: function (error) { throw error; } }); }); enifed('ember-testing/adapters/qunit', ['exports', 'ember-utils', 'ember-testing/adapters/adapter'], function (exports, _emberUtils, _adapter) { 'use strict'; exports.default = _adapter.default.extend({ asyncStart: function () { QUnit.stop(); }, asyncEnd: function () { QUnit.start(); }, exception: function (error) { ok(false, (0, _emberUtils.inspect)(error)); } }); }); enifed('ember-testing/events', ['exports', 'ember-views', 'ember-metal'], function (exports, _emberViews, _emberMetal) { 'use strict'; exports.focus = focus; exports.fireEvent = fireEvent; var DEFAULT_EVENT_OPTIONS = { canBubble: true, cancelable: true }; var KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup']; var MOUSE_EVENT_TYPES = ['click', 'mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover']; function focus(el) { if (!el) { return; } var $el = (0, _emberViews.jQuery)(el); if ($el.is(':input, [contenteditable=true]')) { var type = $el.prop('type'); if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') { (0, _emberMetal.run)(null, function () { // Firefox does not trigger the `focusin` event if the window // does not have focus. If the document doesn't have focus just // use trigger('focusin') instead. if (!document.hasFocus || document.hasFocus()) { el.focus(); } else { $el.trigger('focusin'); } }); } } } function fireEvent(element, type) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (!element) { return; } var event = void 0; if (KEYBOARD_EVENT_TYPES.indexOf(type) > -1) { event = buildKeyboardEvent(type, options); } else if (MOUSE_EVENT_TYPES.indexOf(type) > -1) { var rect = element.getBoundingClientRect(); var x = rect.left + 1; var y = rect.top + 1; var simulatedCoordinates = { screenX: x + 5, screenY: y + 95, clientX: x, clientY: y }; event = buildMouseEvent(type, _emberViews.jQuery.extend(simulatedCoordinates, options)); } else { event = buildBasicEvent(type, options); } element.dispatchEvent(event); } function buildBasicEvent(type) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var event = document.createEvent('Events'); event.initEvent(type, true, true); _emberViews.jQuery.extend(event, options); return event; } function buildMouseEvent(type) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var event = void 0; try { event = document.createEvent('MouseEvents'); var eventOpts = _emberViews.jQuery.extend({}, DEFAULT_EVENT_OPTIONS, options); event.initMouseEvent(type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.detail, eventOpts.screenX, eventOpts.screenY, eventOpts.clientX, eventOpts.clientY, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.button, eventOpts.relatedTarget); } catch (e) { event = buildBasicEvent(type, options); } return event; } function buildKeyboardEvent(type) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var event = void 0; try { event = document.createEvent('KeyEvents'); var eventOpts = _emberViews.jQuery.extend({}, DEFAULT_EVENT_OPTIONS, options); event.initKeyEvent(type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.keyCode, eventOpts.charCode); } catch (e) { event = buildBasicEvent(type, options); } return event; } }); enifed('ember-testing/ext/application', ['ember-application', 'ember-testing/setup_for_testing', 'ember-testing/test/helpers', 'ember-testing/test/promise', 'ember-testing/test/run', 'ember-testing/test/on_inject_helpers', 'ember-testing/test/adapter'], function (_emberApplication, _setup_for_testing, _helpers, _promise, _run, _on_inject_helpers, _adapter) { 'use strict'; _emberApplication.Application.reopen({ /** This property contains the testing helpers for the current application. These are created once you call `injectTestHelpers` on your `Ember.Application` instance. The included helpers are also available on the `window` object by default, but can be used from this object on the individual application also. @property testHelpers @type {Object} @default {} @public */ testHelpers: {}, /** This property will contain the original methods that were registered on the `helperContainer` before `injectTestHelpers` is called. When `removeTestHelpers` is called, these methods are restored to the `helperContainer`. @property originalMethods @type {Object} @default {} @private @since 1.3.0 */ originalMethods: {}, /** This property indicates whether or not this application is currently in testing mode. This is set when `setupForTesting` is called on the current application. @property testing @type {Boolean} @default false @since 1.3.0 @public */ testing: false, setupForTesting: function () { (0, _setup_for_testing.default)(); this.testing = true; this.resolveRegistration('router:main').reopen({ location: 'none' }); }, /** This will be used as the container to inject the test helpers into. By default the helpers are injected into `window`. @property helperContainer @type {Object} The object to be used for test helpers. @default window @since 1.2.0 @private */ helperContainer: null, injectTestHelpers: function (helperContainer) { if (helperContainer) { this.helperContainer = helperContainer; } else { this.helperContainer = window; } this.reopen({ willDestroy: function () { this._super.apply(this, arguments); this.removeTestHelpers(); } }); this.testHelpers = {}; for (var name in _helpers.helpers) { this.originalMethods[name] = this.helperContainer[name]; this.testHelpers[name] = this.helperContainer[name] = helper(this, name); protoWrap(_promise.default.prototype, name, helper(this, name), _helpers.helpers[name].meta.wait); } (0, _on_inject_helpers.invokeInjectHelpersCallbacks)(this); }, removeTestHelpers: function () { if (!this.helperContainer) { return; } for (var name in _helpers.helpers) { this.helperContainer[name] = this.originalMethods[name]; delete _promise.default.prototype[name]; delete this.testHelpers[name]; delete this.originalMethods[name]; } } }); // This method is no longer needed // But still here for backwards compatibility // of helper chaining function protoWrap(proto, name, callback, isAsync) { proto[name] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (isAsync) { return callback.apply(this, args); } else { return this.then(function () { return callback.apply(this, args); }); } }; } function helper(app, name) { var fn = _helpers.helpers[name].method; var meta = _helpers.helpers[name].meta; if (!meta.wait) { return function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return fn.apply(app, [app].concat(args)); }; } return function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } var lastPromise = (0, _run.default)(function () { return (0, _promise.resolve)((0, _promise.getLastPromise)()); }); // wait for last helper's promise to resolve and then // execute. To be safe, we need to tell the adapter we're going // asynchronous here, because fn may not be invoked before we // return. (0, _adapter.asyncStart)(); return lastPromise.then(function () { return fn.apply(app, [app].concat(args)); }).finally(_adapter.asyncEnd); }; } }); enifed('ember-testing/ext/rsvp', ['exports', 'ember-runtime', 'ember-metal', 'ember-debug', 'ember-testing/test/adapter'], function (exports, _emberRuntime, _emberMetal, _emberDebug, _adapter) { 'use strict'; _emberRuntime.RSVP.configure('async', function (callback, promise) { // if schedule will cause autorun, we need to inform adapter if ((0, _emberDebug.isTesting)() && !_emberMetal.run.backburner.currentInstance) { (0, _adapter.asyncStart)(); _emberMetal.run.backburner.schedule('actions', function () { (0, _adapter.asyncEnd)(); callback(promise); }); } else { _emberMetal.run.backburner.schedule('actions', function () { return callback(promise); }); } }); exports.default = _emberRuntime.RSVP; }); enifed('ember-testing/helpers', ['ember-testing/test/helpers', 'ember-testing/helpers/and_then', 'ember-testing/helpers/click', 'ember-testing/helpers/current_path', 'ember-testing/helpers/current_route_name', 'ember-testing/helpers/current_url', 'ember-testing/helpers/fill_in', 'ember-testing/helpers/find', 'ember-testing/helpers/find_with_assert', 'ember-testing/helpers/key_event', 'ember-testing/helpers/pause_test', 'ember-testing/helpers/trigger_event', 'ember-testing/helpers/visit', 'ember-testing/helpers/wait'], function (_helpers, _and_then, _click, _current_path, _current_route_name, _current_url, _fill_in, _find, _find_with_assert, _key_event, _pause_test, _trigger_event, _visit, _wait) { 'use strict'; (0, _helpers.registerAsyncHelper)('visit', _visit.default); (0, _helpers.registerAsyncHelper)('click', _click.default); (0, _helpers.registerAsyncHelper)('keyEvent', _key_event.default); (0, _helpers.registerAsyncHelper)('fillIn', _fill_in.default); (0, _helpers.registerAsyncHelper)('wait', _wait.default); (0, _helpers.registerAsyncHelper)('andThen', _and_then.default); (0, _helpers.registerAsyncHelper)('pauseTest', _pause_test.pauseTest); (0, _helpers.registerAsyncHelper)('triggerEvent', _trigger_event.default); (0, _helpers.registerHelper)('find', _find.default); (0, _helpers.registerHelper)('findWithAssert', _find_with_assert.default); (0, _helpers.registerHelper)('currentRouteName', _current_route_name.default); (0, _helpers.registerHelper)('currentPath', _current_path.default); (0, _helpers.registerHelper)('currentURL', _current_url.default); (0, _helpers.registerHelper)('resumeTest', _pause_test.resumeTest); }); enifed("ember-testing/helpers/and_then", ["exports"], function (exports) { "use strict"; exports.default = andThen; /** @module ember @submodule ember-testing */ function andThen(app, callback) { return app.testHelpers.wait(callback(app)); } }); enifed('ember-testing/helpers/click', ['exports', 'ember-testing/events'], function (exports, _events) { 'use strict'; exports.default = click; /** Clicks an element and triggers any actions triggered by the element's `click` event. Example: ```javascript click('.some-jQuery-selector').then(function() { // assert something }); ``` @method click @param {String} selector jQuery selector for finding element on the DOM @param {Object} context A DOM Element, Document, or jQuery to use as context @return {RSVP.Promise<undefined>} @public */ function click(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); var el = $el[0]; (0, _events.fireEvent)(el, 'mousedown'); (0, _events.focus)(el); (0, _events.fireEvent)(el, 'mouseup'); (0, _events.fireEvent)(el, 'click'); return app.testHelpers.wait(); } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/current_path', ['exports', 'ember-metal'], function (exports, _emberMetal) { 'use strict'; exports.default = currentPath; /** Returns the current path. Example: ```javascript function validateURL() { equal(currentPath(), 'some.path.index', "correct path was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentPath @return {Object} The currently active path. @since 1.5.0 @public */ function currentPath(app) { var routingService = app.__container__.lookup('service:-routing'); return (0, _emberMetal.get)(routingService, 'currentPath'); } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/current_route_name', ['exports', 'ember-metal'], function (exports, _emberMetal) { 'use strict'; exports.default = currentRouteName; /** Returns the currently active route name. Example: ```javascript function validateRouteName() { equal(currentRouteName(), 'some.path', "correct route was transitioned into."); } visit('/some/path').then(validateRouteName) ``` @method currentRouteName @return {Object} The name of the currently active route. @since 1.5.0 @public */ function currentRouteName(app) { var routingService = app.__container__.lookup('service:-routing'); return (0, _emberMetal.get)(routingService, 'currentRouteName'); } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/current_url', ['exports', 'ember-metal'], function (exports, _emberMetal) { 'use strict'; exports.default = currentURL; /** Returns the current URL. Example: ```javascript function validateURL() { equal(currentURL(), '/some/path', "correct URL was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentURL @return {Object} The currently active URL. @since 1.5.0 @public */ function currentURL(app) { var router = app.__container__.lookup('router:main'); return (0, _emberMetal.get)(router, 'location').getURL(); } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/fill_in', ['exports', 'ember-testing/events'], function (exports, _events) { 'use strict'; exports.default = fillIn; /** Fills in an input element with some text. Example: ```javascript fillIn('#email', 'you@example.com').then(function() { // assert something }); ``` @method fillIn @param {String} selector jQuery selector finding an input element on the DOM to fill text with @param {String} text text to place inside the input element @return {RSVP.Promise<undefined>} @public */ function fillIn(app, selector, contextOrText, text) { var $el = void 0, el = void 0, context = void 0; if (text === undefined) { text = contextOrText; } else { context = contextOrText; } $el = app.testHelpers.findWithAssert(selector, context); el = $el[0]; (0, _events.focus)(el); $el.eq(0).val(text); (0, _events.fireEvent)(el, 'input'); (0, _events.fireEvent)(el, 'change'); return app.testHelpers.wait(); } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/find', ['exports', 'ember-metal'], function (exports, _emberMetal) { 'use strict'; exports.default = find; /** Finds an element in the context of the app's container element. A simple alias for `app.$(selector)`. Example: ```javascript var $el = find('.my-selector'); ``` With the `context` param: ```javascript var $el = find('.my-selector', '.parent-element-class'); ``` @method find @param {String} selector jQuery string selector for element lookup @param {String} [context] (optional) jQuery selector that will limit the selector argument to find only within the context's children @return {Object} jQuery object representing the results of the query @public */ function find(app, selector, context) { var $el = void 0; context = context || (0, _emberMetal.get)(app, 'rootElement'); $el = app.$(selector, context); return $el; } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/find_with_assert', ['exports'], function (exports) { 'use strict'; exports.default = findWithAssert; /** @module ember @submodule ember-testing */ /** Like `find`, but throws an error if the element selector returns no results. Example: ```javascript var $el = findWithAssert('.doesnt-exist'); // throws error ``` With the `context` param: ```javascript var $el = findWithAssert('.selector-id', '.parent-element-class'); // assert will pass ``` @method findWithAssert @param {String} selector jQuery selector string for finding an element within the DOM @param {String} [context] (optional) jQuery selector that will limit the selector argument to find only within the context's children @return {Object} jQuery object representing the results of the query @throws {Error} throws error if jQuery object returned has a length of 0 @public */ function findWithAssert(app, selector, context) { var $el = app.testHelpers.find(selector, context); if ($el.length === 0) { throw new Error('Element ' + selector + ' not found.'); } return $el; } }); enifed("ember-testing/helpers/key_event", ["exports"], function (exports) { "use strict"; exports.default = keyEvent; /** @module ember @submodule ember-testing */ /** Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode Example: ```javascript keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() { // assert something }); ``` @method keyEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup` @param {Number} keyCode the keyCode of the simulated key event @return {RSVP.Promise<undefined>} @since 1.5.0 @public */ function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) { var context = void 0, type = void 0; if (keyCode === undefined) { context = null; keyCode = typeOrKeyCode; type = contextOrType; } else { context = contextOrType; type = typeOrKeyCode; } return app.testHelpers.triggerEvent(selector, context, type, { keyCode: keyCode, which: keyCode }); } }); enifed('ember-testing/helpers/pause_test', ['exports', 'ember-runtime', 'ember-console', 'ember-debug'], function (exports, _emberRuntime, _emberConsole, _emberDebug) { 'use strict'; exports.resumeTest = resumeTest; exports.pauseTest = pauseTest; var resume = void 0; /** Resumes a test paused by `pauseTest`. @method resumeTest @return {void} @public */ /** @module ember @submodule ember-testing */ function resumeTest() { (true && !(resume) && (0, _emberDebug.assert)('Testing has not been paused. There is nothing to resume.', resume)); resume(); resume = undefined; } /** Pauses the current test - this is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. Example (The test will pause before clicking the button): ```javascript visit('/') return pauseTest(); click('.btn'); ``` @since 1.9.0 @method pauseTest @return {Object} A promise that will never resolve @public */ function pauseTest() { _emberConsole.default.info('Testing paused. Use `resumeTest()` to continue.'); return new _emberRuntime.RSVP.Promise(function (resolve) { resume = resolve; }, 'TestAdapter paused promise'); } }); enifed('ember-testing/helpers/trigger_event', ['exports', 'ember-testing/events'], function (exports, _events) { 'use strict'; exports.default = triggerEvent; /** Triggers the given DOM event on the element identified by the provided selector. Example: ```javascript triggerEvent('#some-elem-id', 'blur'); ``` This is actually used internally by the `keyEvent` helper like so: ```javascript triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 }); ``` @method triggerEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} [context] jQuery selector that will limit the selector argument to find only within the context's children @param {String} type The event type to be triggered. @param {Object} [options] The options to be passed to jQuery.Event. @return {RSVP.Promise<undefined>} @since 1.5.0 @public */ function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) { var arity = arguments.length; var context = void 0, type = void 0, options = void 0; if (arity === 3) { // context and options are optional, so this is // app, selector, type context = null; type = contextOrType; options = {}; } else if (arity === 4) { // context and options are optional, so this is if (typeof typeOrOptions === 'object') { // either // app, selector, type, options context = null; type = contextOrType; options = typeOrOptions; } else { // or // app, selector, context, type context = contextOrType; type = typeOrOptions; options = {}; } } else { context = contextOrType; type = typeOrOptions; options = possibleOptions; } var $el = app.testHelpers.findWithAssert(selector, context); var el = $el[0]; (0, _events.fireEvent)(el, type, options); return app.testHelpers.wait(); } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/visit', ['exports', 'ember-metal'], function (exports, _emberMetal) { 'use strict'; exports.default = visit; /** Loads a route, sets up any controllers, and renders any templates associated with the route as though a real user had triggered the route change while using your app. Example: ```javascript visit('posts/index').then(function() { // assert something }); ``` @method visit @param {String} url the name of the route @return {RSVP.Promise<undefined>} @public */ function visit(app, url) { var router = app.__container__.lookup('router:main'); var shouldHandleURL = false; app.boot().then(function () { router.location.setURL(url); if (shouldHandleURL) { (0, _emberMetal.run)(app.__deprecatedInstance__, 'handleURL', url); } }); if (app._readinessDeferrals > 0) { router['initialURL'] = url; (0, _emberMetal.run)(app, 'advanceReadiness'); delete router['initialURL']; } else { shouldHandleURL = true; } return app.testHelpers.wait(); } /** @module ember @submodule ember-testing */ }); enifed('ember-testing/helpers/wait', ['exports', 'ember-testing/test/waiters', 'ember-runtime', 'ember-metal', 'ember-testing/test/pending_requests'], function (exports, _waiters, _emberRuntime, _emberMetal, _pending_requests) { 'use strict'; exports.default = wait; /** Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). However, there is a method to register a test helper which utilizes this method without the need to actually call `wait()` in your helpers. The `wait` helper is built into `registerAsyncHelper` by default. You will not need to `return app.testHelpers.wait();` - the wait behavior is provided for you. Example: ```javascript Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit'); }); ``` @method wait @param {Object} value The value to be returned. @return {RSVP.Promise<any>} Promise that resolves to the passed value. @public @since 1.0.0 */ /** @module ember @submodule ember-testing */ function wait(app, value) { return new _emberRuntime.RSVP.Promise(function (resolve) { var router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished var watcher = setInterval(function () { // 1. If the router is loading, keep polling var routerIsLoading = router._routerMicrolib && !!router._routerMicrolib.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if ((0, _pending_requests.pendingRequests)()) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if (_emberMetal.run.hasScheduledTimers() || _emberMetal.run.currentRunLoop) { return; } if ((0, _waiters.checkWaiters)()) { return; } // Stop polling clearInterval(watcher); // Synchronously resolve the promise (0, _emberMetal.run)(null, resolve, value); }, 10); }); } }); enifed('ember-testing/index', ['exports', 'ember-testing/test', 'ember-testing/adapters/adapter', 'ember-testing/setup_for_testing', 'ember-testing/adapters/qunit', 'ember-testing/support', 'ember-testing/ext/application', 'ember-testing/ext/rsvp', 'ember-testing/helpers', 'ember-testing/initializers'], function (exports, _test, _adapter, _setup_for_testing, _qunit) { 'use strict'; exports.QUnitAdapter = exports.setupForTesting = exports.Adapter = exports.Test = undefined; Object.defineProperty(exports, 'Test', { enumerable: true, get: function () { return _test.default; } }); Object.defineProperty(exports, 'Adapter', { enumerable: true, get: function () { return _adapter.default; } }); Object.defineProperty(exports, 'setupForTesting', { enumerable: true, get: function () { return _setup_for_testing.default; } }); Object.defineProperty(exports, 'QUnitAdapter', { enumerable: true, get: function () { return _qunit.default; } }); }); enifed('ember-testing/initializers', ['ember-runtime'], function (_emberRuntime) { 'use strict'; var name = 'deferReadiness in `testing` mode'; (0, _emberRuntime.onLoad)('Ember.Application', function (Application) { if (!Application.initializers[name]) { Application.initializer({ name: name, initialize: function (application) { if (application.testing) { application.deferReadiness(); } } }); } }); }); enifed('ember-testing/setup_for_testing', ['exports', 'ember-debug', 'ember-views', 'ember-testing/test/adapter', 'ember-testing/test/pending_requests', 'ember-testing/adapters/adapter', 'ember-testing/adapters/qunit'], function (exports, _emberDebug, _emberViews, _adapter, _pending_requests, _adapter2, _qunit) { 'use strict'; exports.default = setupForTesting; /** Sets Ember up for testing. This is useful to perform basic setup steps in order to unit test. Use `App.setupForTesting` to perform integration tests (full application testing). @method setupForTesting @namespace Ember @since 1.5.0 @private */ /* global self */ function setupForTesting() { (0, _emberDebug.setTesting)(true); var adapter = (0, _adapter.getAdapter)(); // if adapter is not manually set default to QUnit if (!adapter) { (0, _adapter.setAdapter)(typeof self.QUnit === 'undefined' ? new _adapter2.default() : new _qunit.default()); } if (_emberViews.jQuery) { (0, _emberViews.jQuery)(document).off('ajaxSend', _pending_requests.incrementPendingRequests); (0, _emberViews.jQuery)(document).off('ajaxComplete', _pending_requests.decrementPendingRequests); (0, _pending_requests.clearPendingRequests)(); (0, _emberViews.jQuery)(document).on('ajaxSend', _pending_requests.incrementPendingRequests); (0, _emberViews.jQuery)(document).on('ajaxComplete', _pending_requests.decrementPendingRequests); } } }); enifed('ember-testing/support', ['ember-debug', 'ember-views', 'ember-environment'], function (_emberDebug, _emberViews, _emberEnvironment) { 'use strict'; /** @module ember @submodule ember-testing */ var $ = _emberViews.jQuery; /** This method creates a checkbox and triggers the click event to fire the passed in handler. It is used to correct for a bug in older versions of jQuery (e.g 1.8.3). @private @method testCheckboxClick */ function testCheckboxClick(handler) { var input = document.createElement('input'); $(input).attr('type', 'checkbox').css({ position: 'absolute', left: '-1000px', top: '-1000px' }).appendTo('body').on('click', handler).trigger('click').remove(); } if (_emberEnvironment.environment.hasDOM && typeof $ === 'function') { $(function () { /* Determine whether a checkbox checked using jQuery's "click" method will have the correct value for its checked property. If we determine that the current jQuery version exhibits this behavior, patch it to work correctly as in the commit for the actual fix: https://github.com/jquery/jquery/commit/1fb2f92. */ testCheckboxClick(function () { if (!this.checked && !$.event.special.click) { $.event.special.click = { trigger: function () { if ($.nodeName(this, 'input') && this.type === 'checkbox' && this.click) { this.click(); return false; } } }; } }); // Try again to verify that the patch took effect or blow up. testCheckboxClick(function () { (true && (0, _emberDebug.warn)('clicked checkboxes should be checked! the jQuery patch didn\'t work', this.checked, { id: 'ember-testing.test-checkbox-click' })); }); }); } }); enifed('ember-testing/test', ['exports', 'ember-testing/test/helpers', 'ember-testing/test/on_inject_helpers', 'ember-testing/test/promise', 'ember-testing/test/waiters', 'ember-testing/test/adapter'], function (exports, _helpers, _on_inject_helpers, _promise, _waiters, _adapter) { 'use strict'; /** This is a container for an assortment of testing related functionality: * Choose your default test adapter (for your framework of choice). * Register/Unregister additional test helpers. * Setup callbacks to be fired when the test helpers are injected into your application. @class Test @namespace Ember @public */ var Test = { /** Hash containing all known test helpers. @property _helpers @private @since 1.7.0 */ _helpers: _helpers.helpers, registerHelper: _helpers.registerHelper, registerAsyncHelper: _helpers.registerAsyncHelper, unregisterHelper: _helpers.unregisterHelper, onInjectHelpers: _on_inject_helpers.onInjectHelpers, Promise: _promise.default, promise: _promise.promise, resolve: _promise.resolve, registerWaiter: _waiters.registerWaiter, unregisterWaiter: _waiters.unregisterWaiter, checkWaiters: _waiters.checkWaiters }; /** Used to allow ember-testing to communicate with a specific testing framework. You can manually set it before calling `App.setupForTesting()`. Example: ```javascript Ember.Test.adapter = MyCustomAdapter.create() ``` If you do not set it, ember-testing will default to `Ember.Test.QUnitAdapter`. @public @for Ember.Test @property adapter @type {Class} The adapter to be used. @default Ember.Test.QUnitAdapter */ /** @module ember @submodule ember-testing */ Object.defineProperty(Test, 'adapter', { get: _adapter.getAdapter, set: _adapter.setAdapter }); exports.default = Test; }); enifed('ember-testing/test/adapter', ['exports', 'ember-console', 'ember-metal'], function (exports, _emberConsole, _emberMetal) { 'use strict'; exports.getAdapter = getAdapter; exports.setAdapter = setAdapter; exports.asyncStart = asyncStart; exports.asyncEnd = asyncEnd; var adapter = void 0; function getAdapter() { return adapter; } function setAdapter(value) { adapter = value; if (value) { (0, _emberMetal.setDispatchOverride)(adapterDispatch); } else { (0, _emberMetal.setDispatchOverride)(null); } } function asyncStart() { if (adapter) { adapter.asyncStart(); } } function asyncEnd() { if (adapter) { adapter.asyncEnd(); } } function adapterDispatch(error) { adapter.exception(error); _emberConsole.default.error(error.stack); } }); enifed('ember-testing/test/helpers', ['exports', 'ember-testing/test/promise'], function (exports, _promise) { 'use strict'; exports.helpers = undefined; exports.registerHelper = registerHelper; exports.registerAsyncHelper = registerAsyncHelper; exports.unregisterHelper = unregisterHelper; var helpers = exports.helpers = {}; /** `registerHelper` is used to register a test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` This helper can later be called without arguments because it will be called with `app` as the first parameter. ```javascript App = Ember.Application.create(); App.injectTestHelpers(); boot(); ``` @public @for Ember.Test @method registerHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @param options {Object} */ function registerHelper(name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: false } }; } /** `registerAsyncHelper` is used to register an async test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerAsyncHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` The advantage of an async helper is that it will not run until the last async helper has completed. All async helpers after it will wait for it complete before running. For example: ```javascript Ember.Test.registerAsyncHelper('deletePost', function(app, postId) { click('.delete-' + postId); }); // ... in your test visit('/post/2'); deletePost(2); visit('/post/3'); deletePost(3); ``` @public @for Ember.Test @method registerAsyncHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @since 1.2.0 */ function registerAsyncHelper(name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: true } }; } /** Remove a previously added helper method. Example: ```javascript Ember.Test.unregisterHelper('wait'); ``` @public @method unregisterHelper @param {String} name The helper to remove. */ function unregisterHelper(name) { delete helpers[name]; delete _promise.default.prototype[name]; } }); enifed("ember-testing/test/on_inject_helpers", ["exports"], function (exports) { "use strict"; exports.onInjectHelpers = onInjectHelpers; exports.invokeInjectHelpersCallbacks = invokeInjectHelpersCallbacks; var callbacks = exports.callbacks = []; /** Used to register callbacks to be fired whenever `App.injectTestHelpers` is called. The callback will receive the current application as an argument. Example: ```javascript Ember.Test.onInjectHelpers(function() { Ember.$(document).ajaxSend(function() { Test.pendingRequests++; }); Ember.$(document).ajaxComplete(function() { Test.pendingRequests--; }); }); ``` @public @for Ember.Test @method onInjectHelpers @param {Function} callback The function to be called. */ function onInjectHelpers(callback) { callbacks.push(callback); } function invokeInjectHelpersCallbacks(app) { for (var i = 0; i < callbacks.length; i++) { callbacks[i](app); } } }); enifed("ember-testing/test/pending_requests", ["exports"], function (exports) { "use strict"; exports.pendingRequests = pendingRequests; exports.clearPendingRequests = clearPendingRequests; exports.incrementPendingRequests = incrementPendingRequests; exports.decrementPendingRequests = decrementPendingRequests; var requests = []; function pendingRequests() { return requests.length; } function clearPendingRequests() { requests.length = 0; } function incrementPendingRequests(_, xhr) { requests.push(xhr); } function decrementPendingRequests(_, xhr) { for (var i = 0; i < requests.length; i++) { if (xhr === requests[i]) { requests.splice(i, 1); break; } } } }); enifed('ember-testing/test/promise', ['exports', 'ember-babel', 'ember-runtime', 'ember-testing/test/run'], function (exports, _emberBabel, _emberRuntime, _run) { 'use strict'; exports.promise = promise; exports.resolve = resolve; exports.getLastPromise = getLastPromise; var lastPromise = void 0; var TestPromise = function (_RSVP$Promise) { (0, _emberBabel.inherits)(TestPromise, _RSVP$Promise); function TestPromise() { (0, _emberBabel.classCallCheck)(this, TestPromise); var _this = (0, _emberBabel.possibleConstructorReturn)(this, _RSVP$Promise.apply(this, arguments)); lastPromise = _this; return _this; } TestPromise.prototype.then = function then(_onFulfillment) { var _RSVP$Promise$prototy; var onFulfillment = typeof _onFulfillment === 'function' ? function (result) { return isolate(_onFulfillment, result); } : undefined; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return (_RSVP$Promise$prototy = _RSVP$Promise.prototype.then).call.apply(_RSVP$Promise$prototy, [this, onFulfillment].concat(args)); }; return TestPromise; }(_emberRuntime.RSVP.Promise); exports.default = TestPromise; /** This returns a thenable tailored for testing. It catches failed `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` callback in the last chained then. This method should be returned by async helpers such as `wait`. @public @for Ember.Test @method promise @param {Function} resolver The function used to resolve the promise. @param {String} label An optional string for identifying the promise. */ function promise(resolver, label) { var fullLabel = 'Ember.Test.promise: ' + (label || '<Unknown Promise>'); return new TestPromise(resolver, fullLabel); } /** Replacement for `Ember.RSVP.resolve` The only difference is this uses an instance of `Ember.Test.Promise` @public @for Ember.Test @method resolve @param {Mixed} The value to resolve @since 1.2.0 */ function resolve(result, label) { return TestPromise.resolve(result, label); } function getLastPromise() { return lastPromise; } // This method isolates nested async methods // so that they don't conflict with other last promises. // // 1. Set `Ember.Test.lastPromise` to null // 2. Invoke method // 3. Return the last promise created during method function isolate(onFulfillment, result) { // Reset lastPromise for nested helpers lastPromise = null; var value = onFulfillment(result); var promise = lastPromise; lastPromise = null; // If the method returned a promise // return that promise. If not, // return the last async helper's promise if (value && value instanceof TestPromise || !promise) { return value; } else { return (0, _run.default)(function () { return resolve(promise).then(function () { return value; }); }); } } }); enifed('ember-testing/test/run', ['exports', 'ember-metal'], function (exports, _emberMetal) { 'use strict'; exports.default = run; function run(fn) { if (!_emberMetal.run.currentRunLoop) { return (0, _emberMetal.run)(fn); } else { return fn(); } } }); enifed('ember-testing/test/waiters', ['exports', 'ember-debug'], function (exports, _emberDebug) { 'use strict'; exports.registerWaiter = registerWaiter; exports.unregisterWaiter = unregisterWaiter; exports.checkWaiters = checkWaiters; var contexts = []; var callbacks = []; /** This allows ember-testing to play nicely with other asynchronous events, such as an application that is waiting for a CSS3 transition or an IndexDB transaction. The waiter runs periodically after each async helper (i.e. `click`, `andThen`, `visit`, etc) has executed, until the returning result is truthy. After the waiters finish, the next async helper is executed and the process repeats. For example: ```javascript Ember.Test.registerWaiter(function() { return myPendingTransactions() == 0; }); ``` The `context` argument allows you to optionally specify the `this` with which your callback will be invoked. For example: ```javascript Ember.Test.registerWaiter(MyDB, MyDB.hasPendingTransactions); ``` @public @for Ember.Test @method registerWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ function registerWaiter(context, callback) { if (arguments.length === 1) { callback = context; context = null; } if (indexOf(context, callback) > -1) { return; } contexts.push(context); callbacks.push(callback); } /** `unregisterWaiter` is used to unregister a callback that was registered with `registerWaiter`. @public @for Ember.Test @method unregisterWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ function unregisterWaiter(context, callback) { if (!callbacks.length) { return; } if (arguments.length === 1) { callback = context; context = null; } var i = indexOf(context, callback); if (i === -1) { return; } contexts.splice(i, 1); callbacks.splice(i, 1); } /** Iterates through each registered test waiter, and invokes its callback. If any waiter returns false, this method will return true indicating that the waiters have not settled yet. This is generally used internally from the acceptance/integration test infrastructure. @public @for Ember.Test @static @method checkWaiters */ function checkWaiters() { if (!callbacks.length) { return false; } for (var i = 0; i < callbacks.length; i++) { var context = contexts[i]; var callback = callbacks[i]; if (!callback.call(context)) { return true; } } return false; } function indexOf(context, callback) { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback && contexts[i] === context) { return i; } } return -1; } }); enifed('node-module', ['exports'], function(_exports) { var IS_NODE = typeof module === 'object' && typeof module.require === 'function'; if (IS_NODE) { _exports.require = module.require; _exports.module = module; _exports.IS_NODE = IS_NODE } else { _exports.require = null; _exports.module = null; _exports.IS_NODE = IS_NODE } }); var testing = requireModule('ember-testing'); Ember.Test = testing.Test; Ember.Test.Adapter = testing.Adapter; Ember.Test.QUnitAdapter = testing.QUnitAdapter; Ember.setupForTesting = testing.setupForTesting; }()); /*! * QUnit 2.4.0 * https://qunitjs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2017-07-08T15:20Z */ (function (global$1) { 'use strict'; global$1 = global$1 && 'default' in global$1 ? global$1['default'] : global$1; var window = global$1.window; var self$1 = global$1.self; var console = global$1.console; var setTimeout = global$1.setTimeout; var clearTimeout = global$1.clearTimeout; var document = window && window.document; var navigator = window && window.navigator; var localSessionStorage = function () { var x = "qunit-test-string"; try { global$1.sessionStorage.setItem(x, x); global$1.sessionStorage.removeItem(x); return global$1.sessionStorage; } catch (e) { return undefined; } }(); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; var toString = Object.prototype.toString; var hasOwn = Object.prototype.hasOwnProperty; var now = Date.now || function () { return new Date().getTime(); }; var defined = { document: window && window.document !== undefined, setTimeout: setTimeout !== undefined }; // Returns a new Array with the elements that are in a but not in b function diff(a, b) { var i, j, result = a.slice(); for (i = 0; i < result.length; i++) { for (j = 0; j < b.length; j++) { if (result[i] === b[j]) { result.splice(i, 1); i--; break; } } } return result; } /** * Determines whether an element exists in a given array or not. * * @method inArray * @param {Any} elem * @param {Array} array * @return {Boolean} */ function inArray(elem, array) { return array.indexOf(elem) !== -1; } /** * Makes a clone of an object using only Array or Object as base, * and copies over the own enumerable properties. * * @param {Object} obj * @return {Object} New object with only the own properties (recursively). */ function objectValues(obj) { var key, val, vals = is("array", obj) ? [] : {}; for (key in obj) { if (hasOwn.call(obj, key)) { val = obj[key]; vals[key] = val === Object(val) ? objectValues(val) : val; } } return vals; } function extend(a, b, undefOnly) { for (var prop in b) { if (hasOwn.call(b, prop)) { if (b[prop] === undefined) { delete a[prop]; } else if (!(undefOnly && typeof a[prop] !== "undefined")) { a[prop] = b[prop]; } } } return a; } function objectType(obj) { if (typeof obj === "undefined") { return "undefined"; } // Consider: typeof null === object if (obj === null) { return "null"; } var match = toString.call(obj).match(/^\[object\s(.*)\]$/), type = match && match[1]; switch (type) { case "Number": if (isNaN(obj)) { return "nan"; } return "number"; case "String": case "Boolean": case "Array": case "Set": case "Map": case "Date": case "RegExp": case "Function": case "Symbol": return type.toLowerCase(); default: return typeof obj === "undefined" ? "undefined" : _typeof(obj); } } // Safe object type checking function is(type, obj) { return objectType(obj) === type; } // Based on Java's String.hashCode, a simple but not // rigorously collision resistant hashing function function generateHash(module, testName) { var str = module + "\x1C" + testName; var hash = 0; for (var i = 0; i < str.length; i++) { hash = (hash << 5) - hash + str.charCodeAt(i); hash |= 0; } // Convert the possibly negative integer hash code into an 8 character hex string, which isn't // strictly necessary but increases user understanding that the id is a SHA-like hash var hex = (0x100000000 + hash).toString(16); if (hex.length < 8) { hex = "0000000" + hex; } return hex.slice(-8); } // Test for equality any JavaScript type. // Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org> var equiv = (function () { // Value pairs queued for comparison. Used for breadth-first processing order, recursion // detection and avoiding repeated comparison (see below for details). // Elements are { a: val, b: val }. var pairs = []; var getProto = Object.getPrototypeOf || function (obj) { return obj.__proto__; }; function useStrictEquality(a, b) { // This only gets called if a and b are not strict equal, and is used to compare on // the primitive values inside object wrappers. For example: // `var i = 1;` // `var j = new Number(1);` // Neither a nor b can be null, as a !== b and they have the same type. if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") { a = a.valueOf(); } if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") { b = b.valueOf(); } return a === b; } function compareConstructors(a, b) { var protoA = getProto(a); var protoB = getProto(b); // Comparing constructors is more strict than using `instanceof` if (a.constructor === b.constructor) { return true; } // Ref #851 // If the obj prototype descends from a null constructor, treat it // as a null prototype. if (protoA && protoA.constructor === null) { protoA = null; } if (protoB && protoB.constructor === null) { protoB = null; } // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) { return true; } return false; } function getRegExpFlags(regexp) { return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0]; } function isContainer(val) { return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1; } function breadthFirstCompareChild(a, b) { // If a is a container not reference-equal to b, postpone the comparison to the // end of the pairs queue -- unless (a, b) has been seen before, in which case skip // over the pair. if (a === b) { return true; } if (!isContainer(a)) { return typeEquiv(a, b); } if (pairs.every(function (pair) { return pair.a !== a || pair.b !== b; })) { // Not yet started comparing this pair pairs.push({ a: a, b: b }); } return true; } var callbacks = { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "symbol": useStrictEquality, "date": useStrictEquality, "nan": function nan() { return true; }, "regexp": function regexp(a, b) { return a.source === b.source && // Include flags in the comparison getRegExpFlags(a) === getRegExpFlags(b); }, // abort (identical references / instance methods were skipped earlier) "function": function _function() { return false; }, "array": function array(a, b) { var i, len; len = a.length; if (len !== b.length) { // Safe and faster return false; } for (i = 0; i < len; i++) { // Compare non-containers; queue non-reference-equal containers if (!breadthFirstCompareChild(a[i], b[i])) { return false; } } return true; }, // Define sets a and b to be equivalent if for each element aVal in a, there // is some element bVal in b such that aVal and bVal are equivalent. Element // repetitions are not counted, so these are equivalent: // a = new Set( [ {}, [], [] ] ); // b = new Set( [ {}, {}, [] ] ); "set": function set$$1(a, b) { var innerEq, outerEq = true; if (a.size !== b.size) { // This optimization has certain quirks because of the lack of // repetition counting. For instance, adding the same // (reference-identical) element to two equivalent sets can // make them non-equivalent. return false; } a.forEach(function (aVal) { // Short-circuit if the result is already known. (Using for...of // with a break clause would be cleaner here, but it would cause // a syntax error on older Javascript implementations even if // Set is unused) if (!outerEq) { return; } innerEq = false; b.forEach(function (bVal) { var parentPairs; // Likewise, short-circuit if the result is already known if (innerEq) { return; } // Swap out the global pairs list, as the nested call to // innerEquiv will clobber its contents parentPairs = pairs; if (innerEquiv(bVal, aVal)) { innerEq = true; } // Replace the global pairs list pairs = parentPairs; }); if (!innerEq) { outerEq = false; } }); return outerEq; }, // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal) // in a, there is some key-value pair (bKey, bVal) in b such that // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not // counted, so these are equivalent: // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] ); // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] ); "map": function map(a, b) { var innerEq, outerEq = true; if (a.size !== b.size) { // This optimization has certain quirks because of the lack of // repetition counting. For instance, adding the same // (reference-identical) key-value pair to two equivalent maps // can make them non-equivalent. return false; } a.forEach(function (aVal, aKey) { // Short-circuit if the result is already known. (Using for...of // with a break clause would be cleaner here, but it would cause // a syntax error on older Javascript implementations even if // Map is unused) if (!outerEq) { return; } innerEq = false; b.forEach(function (bVal, bKey) { var parentPairs; // Likewise, short-circuit if the result is already known if (innerEq) { return; } // Swap out the global pairs list, as the nested call to // innerEquiv will clobber its contents parentPairs = pairs; if (innerEquiv([bVal, bKey], [aVal, aKey])) { innerEq = true; } // Replace the global pairs list pairs = parentPairs; }); if (!innerEq) { outerEq = false; } }); return outerEq; }, "object": function object(a, b) { var i, aProperties = [], bProperties = []; if (compareConstructors(a, b) === false) { return false; } // Be strict: don't ensure hasOwnProperty and go deep for (i in a) { // Collect a's properties aProperties.push(i); // Skip OOP methods that look the same if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) { continue; } // Compare non-containers; queue non-reference-equal containers if (!breadthFirstCompareChild(a[i], b[i])) { return false; } } for (i in b) { // Collect b's properties bProperties.push(i); } // Ensures identical properties name return typeEquiv(aProperties.sort(), bProperties.sort()); } }; function typeEquiv(a, b) { var type = objectType(a); // Callbacks for containers will append to the pairs queue to achieve breadth-first // search order. The pairs queue is also used to avoid reprocessing any pair of // containers that are reference-equal to a previously visited pair (a special case // this being recursion detection). // // Because of this approach, once typeEquiv returns a false value, it should not be // called again without clearing the pair queue else it may wrongly report a visited // pair as being equivalent. return objectType(b) === type && callbacks[type](a, b); } function innerEquiv(a, b) { var i, pair; // We're done when there's nothing more to compare if (arguments.length < 2) { return true; } // Clear the global pair queue and add the top-level values being compared pairs = [{ a: a, b: b }]; for (i = 0; i < pairs.length; i++) { pair = pairs[i]; // Perform type-specific comparison on any pairs that are not strictly // equal. For container types, that comparison will postpone comparison // of any sub-container pair to the end of the pair queue. This gives // breadth-first search order. It also avoids the reprocessing of // reference-equal siblings, cousins etc, which can have a significant speed // impact when comparing a container of small objects each of which has a // reference to the same (singleton) large object. if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) { return false; } } // ...across all consecutive argument pairs return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1)); } return function () { var result = innerEquiv.apply(undefined, arguments); // Release any retained objects pairs.length = 0; return result; }; })(); /** * Config object: Maintain internal state * Later exposed as QUnit.config * `config` initialized at top of scope */ var config = { // The queue of tests to run queue: [], // Block until document ready blocking: true, // By default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // By default, modify document.title when suite is done altertitle: true, // HTML Reporter: collapse every test except the first failing test // If false, all failing tests will be expanded collapse: true, // By default, scroll to top of the page when suite is done scrolltop: true, // Depth up-to which object will be dumped maxDepth: 5, // When enabled, all tests must call expect() requireExpects: false, // Placeholder for user-configurable form-exposed URL parameters urlConfig: [], // Set of all modules. modules: [], // The first unnamed module currentModule: { name: "", tests: [], childModules: [], testsRun: 0, unskippedTestsRun: 0, hooks: { before: [], beforeEach: [], afterEach: [], after: [] } }, callbacks: {}, // The storage module to use for reordering tests storage: localSessionStorage }; // take a predefined QUnit.config and extend the defaults var globalConfig = window && window.QUnit && window.QUnit.config; // only extend the global config if there is no QUnit overload if (window && window.QUnit && !window.QUnit.version) { extend(config, globalConfig); } // Push a loose unnamed module to the modules collection config.modules.push(config.currentModule); // Based on jsDump by Ariel Flesler // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html var dump = (function () { function quote(str) { return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\""; } function literal(o) { return o + ""; } function join(pre, arr, post) { var s = dump.separator(), base = dump.indent(), inner = dump.indent(1); if (arr.join) { arr = arr.join("," + s + inner); } if (!arr) { return pre + post; } return [pre, inner + arr, base + post].join(s); } function array(arr, stack) { var i = arr.length, ret = new Array(i); if (dump.maxDepth && dump.depth > dump.maxDepth) { return "[object Array]"; } this.up(); while (i--) { ret[i] = this.parse(arr[i], undefined, stack); } this.down(); return join("[", ret, "]"); } function isArray(obj) { return ( //Native Arrays toString.call(obj) === "[object Array]" || // NodeList objects typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined) ); } var reName = /^function (\w+)/, dump = { // The objType is used mostly internally, you can fix a (custom) type in advance parse: function parse(obj, objType, stack) { stack = stack || []; var res, parser, parserType, objIndex = stack.indexOf(obj); if (objIndex !== -1) { return "recursion(" + (objIndex - stack.length) + ")"; } objType = objType || this.typeOf(obj); parser = this.parsers[objType]; parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser); if (parserType === "function") { stack.push(obj); res = parser.call(this, obj, stack); stack.pop(); return res; } return parserType === "string" ? parser : this.parsers.error; }, typeOf: function typeOf(obj) { var type; if (obj === null) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (is("regexp", obj)) { type = "regexp"; } else if (is("date", obj)) { type = "date"; } else if (is("function", obj)) { type = "function"; } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if (isArray(obj)) { type = "array"; } else if (obj.constructor === Error.prototype.constructor) { type = "error"; } else { type = typeof obj === "undefined" ? "undefined" : _typeof(obj); } return type; }, separator: function separator() { if (this.multiline) { return this.HTML ? "<br />" : "\n"; } else { return this.HTML ? "&#160;" : " "; } }, // Extra can be a number, shortcut for increasing-calling-decreasing indent: function indent(extra) { if (!this.multiline) { return ""; } var chr = this.indentChar; if (this.HTML) { chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;"); } return new Array(this.depth + (extra || 0)).join(chr); }, up: function up(a) { this.depth += a || 1; }, down: function down(a) { this.depth -= a || 1; }, setParser: function setParser(name, parser) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote: quote, literal: literal, join: join, depth: 1, maxDepth: config.maxDepth, // This is the list of parsers, to modify them, use dump.setParser parsers: { window: "[Window]", document: "[Document]", error: function error(_error) { return "Error(\"" + _error.message + "\")"; }, unknown: "[Unknown]", "null": "null", "undefined": "undefined", "function": function _function(fn) { var ret = "function", // Functions never have name in IE name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1]; if (name) { ret += " " + name; } ret += "("; ret = [ret, dump.parse(fn, "functionArgs"), "){"].join(""); return join(ret, dump.parse(fn, "functionCode"), "}"); }, array: array, nodelist: array, "arguments": array, object: function object(map, stack) { var keys, key, val, i, nonEnumerableProperties, ret = []; if (dump.maxDepth && dump.depth > dump.maxDepth) { return "[object Object]"; } dump.up(); keys = []; for (key in map) { keys.push(key); } // Some properties are not always enumerable on Error objects. nonEnumerableProperties = ["message", "name"]; for (i in nonEnumerableProperties) { key = nonEnumerableProperties[i]; if (key in map && !inArray(key, keys)) { keys.push(key); } } keys.sort(); for (i = 0; i < keys.length; i++) { key = keys[i]; val = map[key]; ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack)); } dump.down(); return join("{", ret, "}"); }, node: function node(_node) { var len, i, val, open = dump.HTML ? "&lt;" : "<", close = dump.HTML ? "&gt;" : ">", tag = _node.nodeName.toLowerCase(), ret = open + tag, attrs = _node.attributes; if (attrs) { for (i = 0, len = attrs.length; i < len; i++) { val = attrs[i].nodeValue; // IE6 includes all attributes in .attributes, even ones not explicitly // set. Those have values like undefined, null, 0, false, "" or // "inherit". if (val && val !== "inherit") { ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute"); } } } ret += close; // Show content of TextNode or CDATASection if (_node.nodeType === 3 || _node.nodeType === 4) { ret += _node.nodeValue; } return ret + open + "/" + tag + close; }, // Function calls it internally, it's the arguments part of the function functionArgs: function functionArgs(fn) { var args, l = fn.length; if (!l) { return ""; } args = new Array(l); while (l--) { // 97 is 'a' args[l] = String.fromCharCode(97 + l); } return " " + args.join(", ") + " "; }, // Object calls it internally, the key part of an item in a map key: quote, // Function calls it internally, it's the content of the function functionCode: "[code]", // Node calls it internally, it's a html attribute value attribute: quote, string: quote, date: quote, regexp: literal, number: literal, "boolean": literal, symbol: function symbol(sym) { return sym.toString(); } }, // If true, entities are escaped ( <, >, \t, space and \n ) HTML: false, // Indentation unit indentChar: " ", // If true, items in a collection, are separated by a \n, else just a space. multiline: true }; return dump; })(); var LISTENERS = Object.create(null); var SUPPORTED_EVENTS = ["runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"]; /** * Emits an event with the specified data to all currently registered listeners. * Callbacks will fire in the order in which they are registered (FIFO). This * function is not exposed publicly; it is used by QUnit internals to emit * logging events. * * @private * @method emit * @param {String} eventName * @param {Object} data * @return {Void} */ function emit(eventName, data) { if (objectType(eventName) !== "string") { throw new TypeError("eventName must be a string when emitting an event"); } // Clone the callbacks in case one of them registers a new callback var originalCallbacks = LISTENERS[eventName]; var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : []; for (var i = 0; i < callbacks.length; i++) { callbacks[i](data); } } /** * Registers a callback as a listener to the specified event. * * @public * @method on * @param {String} eventName * @param {Function} callback * @return {Void} */ function on(eventName, callback) { if (objectType(eventName) !== "string") { throw new TypeError("eventName must be a string when registering a listener"); } else if (!inArray(eventName, SUPPORTED_EVENTS)) { var events = SUPPORTED_EVENTS.join(", "); throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + "."); } else if (objectType(callback) !== "function") { throw new TypeError("callback must be a function when registering a listener"); } if (!LISTENERS[eventName]) { LISTENERS[eventName] = []; } // Don't register the same callback more than once if (!inArray(callback, LISTENERS[eventName])) { LISTENERS[eventName].push(callback); } } // Register logging callbacks function registerLoggingCallbacks(obj) { var i, l, key, callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"]; function registerLoggingCallback(key) { var loggingCallback = function loggingCallback(callback) { if (objectType(callback) !== "function") { throw new Error("QUnit logging methods require a callback function as their first parameters."); } config.callbacks[key].push(callback); }; return loggingCallback; } for (i = 0, l = callbackNames.length; i < l; i++) { key = callbackNames[i]; // Initialize key collection of logging callback if (objectType(config.callbacks[key]) === "undefined") { config.callbacks[key] = []; } obj[key] = registerLoggingCallback(key); } } function runLoggingCallbacks(key, args) { var i, l, callbacks; callbacks = config.callbacks[key]; for (i = 0, l = callbacks.length; i < l; i++) { callbacks[i](args); } } // Doesn't support IE9, it will return undefined on these browsers // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, ""); function extractStacktrace(e, offset) { offset = offset === undefined ? 4 : offset; var stack, include, i; if (e && e.stack) { stack = e.stack.split("\n"); if (/^error$/i.test(stack[0])) { stack.shift(); } if (fileName) { include = []; for (i = offset; i < stack.length; i++) { if (stack[i].indexOf(fileName) !== -1) { break; } include.push(stack[i]); } if (include.length) { return include.join("\n"); } } return stack[offset]; } } function sourceFromStacktrace(offset) { var error = new Error(); // Support: Safari <=7 only, IE <=10 - 11 only // Not all browsers generate the `stack` property for `new Error()`, see also #636 if (!error.stack) { try { throw error; } catch (err) { error = err; } } return extractStacktrace(error, offset); } var priorityCount = 0; var unitSampler = void 0; /** * Advances the ProcessingQueue to the next item if it is ready. * @param {Boolean} last */ function advance() { var start = now(); config.depth = (config.depth || 0) + 1; while (config.queue.length && !config.blocking) { var elapsedTime = now() - start; if (!defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate) { if (priorityCount > 0) { priorityCount--; } config.queue.shift()(); } else { setTimeout(advance, 13); break; } } config.depth--; if (!config.blocking && !config.queue.length && config.depth === 0) { done(); } } function addToQueueImmediate(callback) { if (objectType(callback) === "array") { while (callback.length) { addToQueueImmediate(callback.pop()); } return; } config.queue.unshift(callback); priorityCount++; } /** * Adds a function to the ProcessingQueue for execution. * @param {Function|Array} callback * @param {Boolean} priority * @param {String} seed */ function addToQueue(callback, prioritize, seed) { if (prioritize) { config.queue.splice(priorityCount++, 0, callback); } else if (seed) { if (!unitSampler) { unitSampler = unitSamplerGenerator(seed); } // Insert into a random position after all prioritized items var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1)); config.queue.splice(priorityCount + index, 0, callback); } else { config.queue.push(callback); } } /** * Creates a seeded "sample" generator which is used for randomizing tests. */ function unitSamplerGenerator(seed) { // 32-bit xorshift, requires only a nonzero seed // http://excamera.com/sphinx/article-xorshift.html var sample = parseInt(generateHash(seed), 16) || -1; return function () { sample ^= sample << 13; sample ^= sample >>> 17; sample ^= sample << 5; // ECMAScript has no unsigned number type if (sample < 0) { sample += 0x100000000; } return sample / 0x100000000; }; } /** * This function is called when the ProcessingQueue is done processing all * items. It handles emitting the final run events. */ function done() { var storage = config.storage; ProcessingQueue.finished = true; var runtime = now() - config.started; var passed = config.stats.all - config.stats.bad; emit("runEnd", globalSuite.end(true)); runLoggingCallbacks("done", { passed: passed, failed: config.stats.bad, total: config.stats.all, runtime: runtime }); // Clear own storage items if all tests passed if (storage && config.stats.bad === 0) { for (var i = storage.length - 1; i >= 0; i--) { var key = storage.key(i); if (key.indexOf("qunit-test-") === 0) { storage.removeItem(key); } } } } var ProcessingQueue = { finished: false, add: addToQueue, addImmediate: addToQueueImmediate, advance: advance }; var TestReport = function () { function TestReport(name, suite, options) { classCallCheck(this, TestReport); this.name = name; this.suiteName = suite.name; this.fullName = suite.fullName.concat(name); this.runtime = 0; this.assertions = []; this.skipped = !!options.skip; this.todo = !!options.todo; this.valid = options.valid; this._startTime = 0; this._endTime = 0; suite.pushTest(this); } createClass(TestReport, [{ key: "start", value: function start(recordTime) { if (recordTime) { this._startTime = Date.now(); } return { name: this.name, suiteName: this.suiteName, fullName: this.fullName.slice() }; } }, { key: "end", value: function end(recordTime) { if (recordTime) { this._endTime = Date.now(); } return extend(this.start(), { runtime: this.getRuntime(), status: this.getStatus(), errors: this.getFailedAssertions(), assertions: this.getAssertions() }); } }, { key: "pushAssertion", value: function pushAssertion(assertion) { this.assertions.push(assertion); } }, { key: "getRuntime", value: function getRuntime() { return this._endTime - this._startTime; } }, { key: "getStatus", value: function getStatus() { if (this.skipped) { return "skipped"; } var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo; if (!testPassed) { return "failed"; } else if (this.todo) { return "todo"; } else { return "passed"; } } }, { key: "getFailedAssertions", value: function getFailedAssertions() { return this.assertions.filter(function (assertion) { return !assertion.passed; }); } }, { key: "getAssertions", value: function getAssertions() { return this.assertions.slice(); } // Remove actual and expected values from assertions. This is to prevent // leaking memory throughout a test suite. }, { key: "slimAssertions", value: function slimAssertions() { this.assertions = this.assertions.map(function (assertion) { delete assertion.actual; delete assertion.expected; return assertion; }); } }]); return TestReport; }(); var focused$1 = false; function Test(settings) { var i, l; ++Test.count; this.expected = null; this.assertions = []; this.semaphore = 0; this.module = config.currentModule; this.stack = sourceFromStacktrace(3); this.steps = []; this.timeout = undefined; // If a module is skipped, all its tests and the tests of the child suites // should be treated as skipped even if they are defined as `only` or `todo`. // As for `todo` module, all its tests will be treated as `todo` except for // tests defined as `skip` which will be left intact. // // So, if a test is defined as `todo` and is inside a skipped module, we should // then treat that test as if was defined as `skip`. if (this.module.skip) { settings.skip = true; settings.todo = false; // Skipped tests should be left intact } else if (this.module.todo && !settings.skip) { settings.todo = true; } extend(this, settings); this.testReport = new TestReport(settings.testName, this.module.suiteReport, { todo: settings.todo, skip: settings.skip, valid: this.valid() }); // Register unique strings for (i = 0, l = this.module.tests; i < l.length; i++) { if (this.module.tests[i].name === this.testName) { this.testName += " "; } } this.testId = generateHash(this.module.name, this.testName); this.module.tests.push({ name: this.testName, testId: this.testId, skip: !!settings.skip }); if (settings.skip) { // Skipped tests will fully ignore any sent callback this.callback = function () {}; this.async = false; this.expected = 0; } else { this.assert = new Assert(this); } } Test.count = 0; function getNotStartedModules(startModule) { var module = startModule, modules = []; while (module && module.testsRun === 0) { modules.push(module); module = module.parentModule; } return modules; } Test.prototype = { before: function before() { var i, startModule, module = this.module, notStartedModules = getNotStartedModules(module); for (i = notStartedModules.length - 1; i >= 0; i--) { startModule = notStartedModules[i]; startModule.stats = { all: 0, bad: 0, started: now() }; emit("suiteStart", startModule.suiteReport.start(true)); runLoggingCallbacks("moduleStart", { name: startModule.name, tests: startModule.tests }); } config.current = this; this.testEnvironment = extend({}, module.testEnvironment); this.started = now(); emit("testStart", this.testReport.start(true)); runLoggingCallbacks("testStart", { name: this.testName, module: module.name, testId: this.testId, previousFailure: this.previousFailure }); if (!config.pollution) { saveGlobal(); } }, run: function run() { var promise; config.current = this; this.callbackStarted = now(); if (config.notrycatch) { runTest(this); return; } try { runTest(this); } catch (e) { this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0)); // Else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if (config.blocking) { internalRecover(this); } } function runTest(test) { promise = test.callback.call(test.testEnvironment, test.assert); test.resolvePromise(promise); // If the test has a "lock" on it, but the timeout is 0, then we push a // failure as the test should be synchronous. if (test.timeout === 0 && test.semaphore !== 0) { pushFailure("Test did not finish synchronously even though assert.timeout( 0 ) was used.", sourceFromStacktrace(2)); } } }, after: function after() { checkPollution(); }, queueHook: function queueHook(hook, hookName, hookOwner) { var _this = this; var callHook = function callHook() { var promise = hook.call(_this.testEnvironment, _this.assert); _this.resolvePromise(promise, hookName); }; var runHook = function runHook() { if (hookName === "before") { if (hookOwner.unskippedTestsRun !== 0) { return; } _this.preserveEnvironment = true; } if (hookName === "after" && hookOwner.unskippedTestsRun !== numberOfUnskippedTests(hookOwner) - 1 && config.queue.length > 2) { return; } config.current = _this; if (config.notrycatch) { callHook(); return; } try { callHook(); } catch (error) { _this.pushFailure(hookName + " failed on " + _this.testName + ": " + (error.message || error), extractStacktrace(error, 0)); } }; return runHook; }, // Currently only used for module level hooks, can be used to add global level ones hooks: function hooks(handler) { var hooks = []; function processHooks(test, module) { if (module.parentModule) { processHooks(test, module.parentModule); } if (module.hooks[handler].length) { for (var i = 0; i < module.hooks[handler].length; i++) { hooks.push(test.queueHook(module.hooks[handler][i], handler, module)); } } } // Hooks are ignored on skipped tests if (!this.skip) { processHooks(this, this.module); } return hooks; }, finish: function finish() { config.current = this; if (config.requireExpects && this.expected === null) { this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack); } else if (this.expected !== null && this.expected !== this.assertions.length) { this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack); } else if (this.expected === null && !this.assertions.length) { this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack); } var i, module = this.module, moduleName = module.name, testName = this.testName, skipped = !!this.skip, todo = !!this.todo, bad = 0, storage = config.storage; this.runtime = now() - this.started; config.stats.all += this.assertions.length; module.stats.all += this.assertions.length; for (i = 0; i < this.assertions.length; i++) { if (!this.assertions[i].result) { bad++; config.stats.bad++; module.stats.bad++; } } notifyTestsRan(module, skipped); // Store result when possible if (storage) { if (bad) { storage.setItem("qunit-test-" + moduleName + "-" + testName, bad); } else { storage.removeItem("qunit-test-" + moduleName + "-" + testName); } } // After emitting the js-reporters event we cleanup the assertion data to // avoid leaking it. It is not used by the legacy testDone callbacks. emit("testEnd", this.testReport.end(true)); this.testReport.slimAssertions(); runLoggingCallbacks("testDone", { name: testName, module: moduleName, skipped: skipped, todo: todo, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length, runtime: skipped ? 0 : this.runtime, // HTML Reporter use assertions: this.assertions, testId: this.testId, // Source of Test source: this.stack }); if (module.testsRun === numberOfTests(module)) { logSuiteEnd(module); // Check if the parent modules, iteratively, are done. If that the case, // we emit the `suiteEnd` event and trigger `moduleDone` callback. var parent = module.parentModule; while (parent && parent.testsRun === numberOfTests(parent)) { logSuiteEnd(parent); parent = parent.parentModule; } } config.current = undefined; function logSuiteEnd(module) { emit("suiteEnd", module.suiteReport.end(true)); runLoggingCallbacks("moduleDone", { name: module.name, tests: module.tests, failed: module.stats.bad, passed: module.stats.all - module.stats.bad, total: module.stats.all, runtime: now() - module.stats.started }); } }, preserveTestEnvironment: function preserveTestEnvironment() { if (this.preserveEnvironment) { this.module.testEnvironment = this.testEnvironment; this.testEnvironment = extend({}, this.module.testEnvironment); } }, queue: function queue() { var test = this; if (!this.valid()) { return; } function runTest() { // Each of these can by async ProcessingQueue.addImmediate([function () { test.before(); }, test.hooks("before"), function () { test.preserveTestEnvironment(); }, test.hooks("beforeEach"), function () { test.run(); }, test.hooks("afterEach").reverse(), test.hooks("after").reverse(), function () { test.after(); }, function () { test.finish(); }]); } var previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName); // Prioritize previously failed tests, detected from storage var prioritize = config.reorder && !!previousFailCount; this.previousFailure = !!previousFailCount; ProcessingQueue.add(runTest, prioritize, config.seed); // If the queue has already finished, we manually process the new test if (ProcessingQueue.finished) { ProcessingQueue.advance(); } }, pushResult: function pushResult(resultInfo) { if (this !== config.current) { throw new Error("Assertion occured after test had finished."); } // Destructure of resultInfo = { result, actual, expected, message, negative } var source, details = { module: this.module.name, name: this.testName, result: resultInfo.result, message: resultInfo.message, actual: resultInfo.actual, expected: resultInfo.expected, testId: this.testId, negative: resultInfo.negative || false, runtime: now() - this.started, todo: !!this.todo }; if (!resultInfo.result) { source = resultInfo.source || sourceFromStacktrace(); if (source) { details.source = source; } } this.logAssertion(details); this.assertions.push({ result: !!resultInfo.result, message: resultInfo.message }); }, pushFailure: function pushFailure(message, source, actual) { if (!(this instanceof Test)) { throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2)); } this.pushResult({ result: false, message: message || "error", actual: actual || null, expected: null, source: source }); }, /** * Log assertion details using both the old QUnit.log interface and * QUnit.on( "assertion" ) interface. * * @private */ logAssertion: function logAssertion(details) { runLoggingCallbacks("log", details); var assertion = { passed: details.result, actual: details.actual, expected: details.expected, message: details.message, stack: details.source, todo: details.todo }; this.testReport.pushAssertion(assertion); emit("assertion", assertion); }, resolvePromise: function resolvePromise(promise, phase) { var then, resume, message, test = this; if (promise != null) { then = promise.then; if (objectType(then) === "function") { resume = internalStop(test); then.call(promise, function () { resume(); }, function (error) { message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error); test.pushFailure(message, extractStacktrace(error, 0)); // Else next test will carry the responsibility saveGlobal(); // Unblock resume(); }); } } }, valid: function valid() { var filter = config.filter, regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter), module = config.module && config.module.toLowerCase(), fullName = this.module.name + ": " + this.testName; function moduleChainNameMatch(testModule) { var testModuleName = testModule.name ? testModule.name.toLowerCase() : null; if (testModuleName === module) { return true; } else if (testModule.parentModule) { return moduleChainNameMatch(testModule.parentModule); } else { return false; } } function moduleChainIdMatch(testModule) { return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule); } // Internally-generated tests are always valid if (this.callback && this.callback.validTest) { return true; } if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) { return false; } if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) { return false; } if (module && !moduleChainNameMatch(this.module)) { return false; } if (!filter) { return true; } return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName); }, regexFilter: function regexFilter(exclude, pattern, flags, fullName) { var regex = new RegExp(pattern, flags); var match = regex.test(fullName); return match !== exclude; }, stringFilter: function stringFilter(filter, fullName) { filter = filter.toLowerCase(); fullName = fullName.toLowerCase(); var include = filter.charAt(0) !== "!"; if (!include) { filter = filter.slice(1); } // If the filter matches, we need to honour include if (fullName.indexOf(filter) !== -1) { return include; } // Otherwise, do the opposite return !include; } }; function pushFailure() { if (!config.current) { throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2)); } // Gets current test obj var currentTest = config.current; return currentTest.pushFailure.apply(currentTest, arguments); } function saveGlobal() { config.pollution = []; if (config.noglobals) { for (var key in global$1) { if (hasOwn.call(global$1, key)) { // In Opera sometimes DOM element ids show up here, ignore them if (/^qunit-test-output/.test(key)) { continue; } config.pollution.push(key); } } } } function checkPollution() { var newGlobals, deletedGlobals, old = config.pollution; saveGlobal(); newGlobals = diff(config.pollution, old); if (newGlobals.length > 0) { pushFailure("Introduced global variable(s): " + newGlobals.join(", ")); } deletedGlobals = diff(old, config.pollution); if (deletedGlobals.length > 0) { pushFailure("Deleted global variable(s): " + deletedGlobals.join(", ")); } } // Will be exposed as QUnit.test function test(testName, callback) { if (focused$1) { return; } var newTest = new Test({ testName: testName, callback: callback }); newTest.queue(); } function todo(testName, callback) { if (focused$1) { return; } var newTest = new Test({ testName: testName, callback: callback, todo: true }); newTest.queue(); } // Will be exposed as QUnit.skip function skip(testName) { if (focused$1) { return; } var test = new Test({ testName: testName, skip: true }); test.queue(); } // Will be exposed as QUnit.only function only(testName, callback) { if (focused$1) { return; } config.queue.length = 0; focused$1 = true; var newTest = new Test({ testName: testName, callback: callback }); newTest.queue(); } // Put a hold on processing and return a function that will release it. function internalStop(test) { test.semaphore += 1; config.blocking = true; // Set a recovery timeout, if so configured. if (defined.setTimeout) { var timeoutDuration = void 0; if (typeof test.timeout === "number") { timeoutDuration = test.timeout; } else if (typeof config.testTimeout === "number") { timeoutDuration = config.testTimeout; } if (typeof timeoutDuration === "number" && timeoutDuration > 0) { clearTimeout(config.timeout); config.timeout = setTimeout(function () { pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2)); internalRecover(test); }, timeoutDuration); } } var released = false; return function resume() { if (released) { return; } released = true; test.semaphore -= 1; internalStart(test); }; } // Forcefully release all processing holds. function internalRecover(test) { test.semaphore = 0; internalStart(test); } // Release a processing hold, scheduling a resumption attempt if no holds remain. function internalStart(test) { // If semaphore is non-numeric, throw error if (isNaN(test.semaphore)) { test.semaphore = 0; pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2)); return; } // Don't start until equal number of stop-calls if (test.semaphore > 0) { return; } // Throw an Error if start is called more often than stop if (test.semaphore < 0) { test.semaphore = 0; pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2)); return; } // Add a slight delay to allow more assertions etc. if (defined.setTimeout) { if (config.timeout) { clearTimeout(config.timeout); } config.timeout = setTimeout(function () { if (test.semaphore > 0) { return; } if (config.timeout) { clearTimeout(config.timeout); } begin(); }, 13); } else { begin(); } } function collectTests(module) { var tests = [].concat(module.tests); var modules = [].concat(toConsumableArray(module.childModules)); // Do a breadth-first traversal of the child modules while (modules.length) { var nextModule = modules.shift(); tests.push.apply(tests, nextModule.tests); modules.push.apply(modules, toConsumableArray(nextModule.childModules)); } return tests; } function numberOfTests(module) { return collectTests(module).length; } function numberOfUnskippedTests(module) { return collectTests(module).filter(function (test) { return !test.skip; }).length; } function notifyTestsRan(module, skipped) { module.testsRun++; if (!skipped) { module.unskippedTestsRun++; } while (module = module.parentModule) { module.testsRun++; if (!skipped) { module.unskippedTestsRun++; } } } /** * Returns a function that proxies to the given method name on the globals * console object. The proxy will also detect if the console doesn't exist and * will appropriately no-op. This allows support for IE9, which doesn't have a * console if the developer tools are not open. */ function consoleProxy(method) { return function () { if (console) { console[method].apply(console, arguments); } }; } var Logger = { warn: consoleProxy("warn") }; var Assert = function () { function Assert(testContext) { classCallCheck(this, Assert); this.test = testContext; } // Assert helpers createClass(Assert, [{ key: "timeout", value: function timeout(duration) { if (typeof duration !== "number") { throw new Error("You must pass a number as the duration to assert.timeout"); } this.test.timeout = duration; } // Documents a "step", which is a string value, in a test as a passing assertion }, { key: "step", value: function step(message) { var result = !!message; this.test.steps.push(message); return this.pushResult({ result: result, message: message || "You must provide a message to assert.step" }); } // Verifies the steps in a test match a given array of string values }, { key: "verifySteps", value: function verifySteps(steps, message) { this.deepEqual(this.test.steps, steps, message); } // Specify the number of expected assertions to guarantee that failed test // (no assertions are run at all) don't slip through. }, { key: "expect", value: function expect(asserts) { if (arguments.length === 1) { this.test.expected = asserts; } else { return this.test.expected; } } // Put a hold on processing and return a function that will release it a maximum of once. }, { key: "async", value: function async(count) { var test$$1 = this.test; var popped = false, acceptCallCount = count; if (typeof acceptCallCount === "undefined") { acceptCallCount = 1; } var resume = internalStop(test$$1); return function done() { if (config.current !== test$$1) { throw Error("assert.async callback called after test finished."); } if (popped) { test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2)); return; } acceptCallCount -= 1; if (acceptCallCount > 0) { return; } popped = true; resume(); }; } // Exports test.push() to the user API // Alias of pushResult. }, { key: "push", value: function push(result, actual, expected, message, negative) { Logger.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult)."); var currentAssert = this instanceof Assert ? this : config.current.assert; return currentAssert.pushResult({ result: result, actual: actual, expected: expected, message: message, negative: negative }); } }, { key: "pushResult", value: function pushResult(resultInfo) { // Destructure of resultInfo = { result, actual, expected, message, negative } var assert = this; var currentTest = assert instanceof Assert && assert.test || config.current; // Backwards compatibility fix. // Allows the direct use of global exported assertions and QUnit.assert.* // Although, it's use is not recommended as it can leak assertions // to other tests from async tests, because we only get a reference to the current test, // not exactly the test where assertion were intended to be called. if (!currentTest) { throw new Error("assertion outside test context, in " + sourceFromStacktrace(2)); } if (!(assert instanceof Assert)) { assert = currentTest.assert; } return assert.test.pushResult(resultInfo); } }, { key: "ok", value: function ok(result, message) { if (!message) { message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result); } this.pushResult({ result: !!result, actual: result, expected: true, message: message }); } }, { key: "notOk", value: function notOk(result, message) { if (!message) { message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result); } this.pushResult({ result: !result, actual: result, expected: false, message: message }); } }, { key: "equal", value: function equal(actual, expected, message) { // eslint-disable-next-line eqeqeq var result = expected == actual; this.pushResult({ result: result, actual: actual, expected: expected, message: message }); } }, { key: "notEqual", value: function notEqual(actual, expected, message) { // eslint-disable-next-line eqeqeq var result = expected != actual; this.pushResult({ result: result, actual: actual, expected: expected, message: message, negative: true }); } }, { key: "propEqual", value: function propEqual(actual, expected, message) { actual = objectValues(actual); expected = objectValues(expected); this.pushResult({ result: equiv(actual, expected), actual: actual, expected: expected, message: message }); } }, { key: "notPropEqual", value: function notPropEqual(actual, expected, message) { actual = objectValues(actual); expected = objectValues(expected); this.pushResult({ result: !equiv(actual, expected), actual: actual, expected: expected, message: message, negative: true }); } }, { key: "deepEqual", value: function deepEqual(actual, expected, message) { this.pushResult({ result: equiv(actual, expected), actual: actual, expected: expected, message: message }); } }, { key: "notDeepEqual", value: function notDeepEqual(actual, expected, message) { this.pushResult({ result: !equiv(actual, expected), actual: actual, expected: expected, message: message, negative: true }); } }, { key: "strictEqual", value: function strictEqual(actual, expected, message) { this.pushResult({ result: expected === actual, actual: actual, expected: expected, message: message }); } }, { key: "notStrictEqual", value: function notStrictEqual(actual, expected, message) { this.pushResult({ result: expected !== actual, actual: actual, expected: expected, message: message, negative: true }); } }, { key: "throws", value: function throws(block, expected, message) { var actual = void 0, result = false; var currentTest = this instanceof Assert && this.test || config.current; // 'expected' is optional unless doing string comparison if (objectType(expected) === "string") { if (message == null) { message = expected; expected = null; } else { throw new Error("throws/raises does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. regExp) instead if it's necessary."); } } currentTest.ignoreGlobalErrors = true; try { block.call(currentTest.testEnvironment); } catch (e) { actual = e; } currentTest.ignoreGlobalErrors = false; if (actual) { var expectedType = objectType(expected); // We don't want to validate thrown error if (!expected) { result = true; expected = null; // Expected is a regexp } else if (expectedType === "regexp") { result = expected.test(errorString(actual)); // Expected is a constructor, maybe an Error constructor } else if (expectedType === "function" && actual instanceof expected) { result = true; // Expected is an Error object } else if (expectedType === "object") { result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message; // Expected is a validation function which returns true if validation passed } else if (expectedType === "function" && expected.call({}, actual) === true) { expected = null; result = true; } } currentTest.assert.pushResult({ result: result, actual: actual, expected: expected, message: message }); } }]); return Assert; }(); // Provide an alternative to assert.throws(), for environments that consider throws a reserved word // Known to us are: Closure Compiler, Narwhal // eslint-disable-next-line dot-notation Assert.prototype.raises = Assert.prototype["throws"]; /** * Converts an error into a simple string for comparisons. * * @param {Error} error * @return {String} */ function errorString(error) { var resultErrorString = error.toString(); if (resultErrorString.substring(0, 7) === "[object") { var name = error.name ? error.name.toString() : "Error"; var message = error.message ? error.message.toString() : ""; if (name && message) { return name + ": " + message; } else if (name) { return name; } else if (message) { return message; } else { return "Error"; } } else { return resultErrorString; } } /* global module, exports, define */ function exportQUnit(QUnit) { if (defined.document) { // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined. if (window.QUnit && window.QUnit.version) { throw new Error("QUnit has already been defined."); } window.QUnit = QUnit; } // For nodejs if (typeof module !== "undefined" && module && module.exports) { module.exports = QUnit; // For consistency with CommonJS environments' exports module.exports.QUnit = QUnit; } // For CommonJS with exports, but without module.exports, like Rhino if (typeof exports !== "undefined" && exports) { exports.QUnit = QUnit; } if (typeof define === "function" && define.amd) { define(function () { return QUnit; }); QUnit.config.autostart = false; } // For Web/Service Workers if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) { self$1.QUnit = QUnit; } } var SuiteReport = function () { function SuiteReport(name, parentSuite) { classCallCheck(this, SuiteReport); this.name = name; this.fullName = parentSuite ? parentSuite.fullName.concat(name) : []; this.tests = []; this.childSuites = []; if (parentSuite) { parentSuite.pushChildSuite(this); } } createClass(SuiteReport, [{ key: "start", value: function start(recordTime) { if (recordTime) { this._startTime = Date.now(); } return { name: this.name, fullName: this.fullName.slice(), tests: this.tests.map(function (test) { return test.start(); }), childSuites: this.childSuites.map(function (suite) { return suite.start(); }), testCounts: { total: this.getTestCounts().total } }; } }, { key: "end", value: function end(recordTime) { if (recordTime) { this._endTime = Date.now(); } return { name: this.name, fullName: this.fullName.slice(), tests: this.tests.map(function (test) { return test.end(); }), childSuites: this.childSuites.map(function (suite) { return suite.end(); }), testCounts: this.getTestCounts(), runtime: this.getRuntime(), status: this.getStatus() }; } }, { key: "pushChildSuite", value: function pushChildSuite(suite) { this.childSuites.push(suite); } }, { key: "pushTest", value: function pushTest(test) { this.tests.push(test); } }, { key: "getRuntime", value: function getRuntime() { return this._endTime - this._startTime; } }, { key: "getTestCounts", value: function getTestCounts() { var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 }; counts = this.tests.reduce(function (counts, test) { if (test.valid) { counts[test.getStatus()]++; counts.total++; } return counts; }, counts); return this.childSuites.reduce(function (counts, suite) { return suite.getTestCounts(counts); }, counts); } }, { key: "getStatus", value: function getStatus() { var _getTestCounts = this.getTestCounts(), total = _getTestCounts.total, failed = _getTestCounts.failed, skipped = _getTestCounts.skipped, todo = _getTestCounts.todo; if (failed) { return "failed"; } else { if (skipped === total) { return "skipped"; } else if (todo === total) { return "todo"; } else { return "passed"; } } } }]); return SuiteReport; }(); // Handle an unhandled exception. By convention, returns true if further // error handling should be suppressed and false otherwise. // In this case, we will only suppress further error handling if the // "ignoreGlobalErrors" configuration option is enabled. function onError(error) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (config.current) { if (config.current.ignoreGlobalErrors) { return true; } pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args)); } else { test("global failure", extend(function () { pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args)); }, { validTest: true })); } return false; } var focused = false; var QUnit = {}; var globalSuite = new SuiteReport(); // The initial "currentModule" represents the global (or top-level) module that // is not explicitly defined by the user, therefore we add the "globalSuite" to // it since each module has a suiteReport associated with it. config.currentModule.suiteReport = globalSuite; var moduleStack = []; var globalStartCalled = false; var runStarted = false; // Figure out if we're running the tests from a server or not QUnit.isLocal = !(defined.document && window.location.protocol !== "file:"); // Expose the current QUnit version QUnit.version = "2.4.0"; function createModule(name, testEnvironment, modifiers) { var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null; var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name; var parentSuite = parentModule ? parentModule.suiteReport : globalSuite; var skip$$1 = parentModule !== null && parentModule.skip || modifiers.skip; var todo$$1 = parentModule !== null && parentModule.todo || modifiers.todo; var module = { name: moduleName, parentModule: parentModule, tests: [], moduleId: generateHash(moduleName), testsRun: 0, unskippedTestsRun: 0, childModules: [], suiteReport: new SuiteReport(name, parentSuite), // Pass along `skip` and `todo` properties from parent module, in case // there is one, to childs. And use own otherwise. // This property will be used to mark own tests and tests of child suites // as either `skipped` or `todo`. skip: skip$$1, todo: skip$$1 ? false : todo$$1 }; var env = {}; if (parentModule) { parentModule.childModules.push(module); extend(env, parentModule.testEnvironment); } extend(env, testEnvironment); module.testEnvironment = env; config.modules.push(module); return module; } function processModule(name, options, executeNow) { var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var module = createModule(name, options, modifiers); // Move any hooks to a 'hooks' object var testEnvironment = module.testEnvironment; var hooks = module.hooks = {}; setHookFromEnvironment(hooks, testEnvironment, "before"); setHookFromEnvironment(hooks, testEnvironment, "beforeEach"); setHookFromEnvironment(hooks, testEnvironment, "afterEach"); setHookFromEnvironment(hooks, testEnvironment, "after"); function setHookFromEnvironment(hooks, environment, name) { var potentialHook = environment[name]; hooks[name] = typeof potentialHook === "function" ? [potentialHook] : []; delete environment[name]; } var moduleFns = { before: setHookFunction(module, "before"), beforeEach: setHookFunction(module, "beforeEach"), afterEach: setHookFunction(module, "afterEach"), after: setHookFunction(module, "after") }; var currentModule = config.currentModule; if (objectType(executeNow) === "function") { moduleStack.push(module); config.currentModule = module; executeNow.call(module.testEnvironment, moduleFns); moduleStack.pop(); module = module.parentModule || currentModule; } config.currentModule = module; } // TODO: extract this to a new file alongside its related functions function module$1(name, options, executeNow) { if (focused) { return; } if (arguments.length === 2) { if (objectType(options) === "function") { executeNow = options; options = undefined; } } processModule(name, options, executeNow); } module$1.only = function () { if (focused) { return; } config.modules.length = 0; config.queue.length = 0; module$1.apply(undefined, arguments); focused = true; }; module$1.skip = function (name, options, executeNow) { if (focused) { return; } if (arguments.length === 2) { if (objectType(options) === "function") { executeNow = options; options = undefined; } } processModule(name, options, executeNow, { skip: true }); }; module$1.todo = function (name, options, executeNow) { if (focused) { return; } if (arguments.length === 2) { if (objectType(options) === "function") { executeNow = options; options = undefined; } } processModule(name, options, executeNow, { todo: true }); }; extend(QUnit, { on: on, module: module$1, test: test, todo: todo, skip: skip, only: only, start: function start(count) { var globalStartAlreadyCalled = globalStartCalled; if (!config.current) { globalStartCalled = true; if (runStarted) { throw new Error("Called start() while test already started running"); } else if (globalStartAlreadyCalled || count > 1) { throw new Error("Called start() outside of a test context too many times"); } else if (config.autostart) { throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true"); } else if (!config.pageLoaded) { // The page isn't completely loaded yet, so we set autostart and then // load if we're in Node or wait for the browser's load event. config.autostart = true; // Starts from Node even if .load was not previously called. We still return // early otherwise we'll wind up "beginning" twice. if (!defined.document) { QUnit.load(); } return; } } else { throw new Error("QUnit.start cannot be called inside a test context."); } scheduleBegin(); }, config: config, is: is, objectType: objectType, extend: extend, load: function load() { config.pageLoaded = true; // Initialize the configuration options extend(config, { stats: { all: 0, bad: 0 }, started: 0, updateRate: 1000, autostart: true, filter: "" }, true); if (!runStarted) { config.blocking = false; if (config.autostart) { scheduleBegin(); } } }, stack: function stack(offset) { offset = (offset || 0) + 2; return sourceFromStacktrace(offset); }, onError: onError }); QUnit.pushFailure = pushFailure; QUnit.assert = Assert.prototype; QUnit.equiv = equiv; QUnit.dump = dump; registerLoggingCallbacks(QUnit); function scheduleBegin() { runStarted = true; // Add a slight delay to allow definition of more modules and tests. if (defined.setTimeout) { setTimeout(function () { begin(); }, 13); } else { begin(); } } function begin() { var i, l, modulesLog = []; // If the test run hasn't officially begun yet if (!config.started) { // Record the time of the test run's beginning config.started = now(); // Delete the loose unnamed module if unused. if (config.modules[0].name === "" && config.modules[0].tests.length === 0) { config.modules.shift(); } // Avoid unnecessary information by not logging modules' test environments for (i = 0, l = config.modules.length; i < l; i++) { modulesLog.push({ name: config.modules[i].name, tests: config.modules[i].tests }); } // The test run is officially beginning now emit("runStart", globalSuite.start(true)); runLoggingCallbacks("begin", { totalTests: Test.count, modules: modulesLog }); } config.blocking = false; ProcessingQueue.advance(); } function setHookFunction(module, hookName) { return function setHook(callback) { module.hooks[hookName].push(callback); }; } exportQUnit(QUnit); (function () { if (typeof window === "undefined" || typeof document === "undefined") { return; } var config = QUnit.config, hasOwn = Object.prototype.hasOwnProperty; // Stores fixture HTML for resetting later function storeFixture() { // Avoid overwriting user-defined values if (hasOwn.call(config, "fixture")) { return; } var fixture = document.getElementById("qunit-fixture"); if (fixture) { config.fixture = fixture.innerHTML; } } QUnit.begin(storeFixture); // Resets the fixture DOM element if available. function resetFixture() { if (config.fixture == null) { return; } var fixture = document.getElementById("qunit-fixture"); if (fixture) { fixture.innerHTML = config.fixture; } } QUnit.testStart(resetFixture); })(); (function () { // Only interact with URLs via window.location var location = typeof window !== "undefined" && window.location; if (!location) { return; } var urlParams = getUrlParams(); QUnit.urlParams = urlParams; // Match module/test by inclusion in an array QUnit.config.moduleId = [].concat(urlParams.moduleId || []); QUnit.config.testId = [].concat(urlParams.testId || []); // Exact case-insensitive match of the module name QUnit.config.module = urlParams.module; // Regular expression or case-insenstive substring match against "moduleName: testName" QUnit.config.filter = urlParams.filter; // Test order randomization if (urlParams.seed === true) { // Generate a random seed if the option is specified without a value QUnit.config.seed = Math.random().toString(36).slice(2); } else if (urlParams.seed) { QUnit.config.seed = urlParams.seed; } // Add URL-parameter-mapped config values with UI form rendering data QUnit.config.urlConfig.push({ id: "hidepassed", label: "Hide passed tests", tooltip: "Only show tests and assertions that fail. Stored as query-strings." }, { id: "noglobals", label: "Check for Globals", tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings." }, { id: "notrycatch", label: "No try-catch", tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings." }); QUnit.begin(function () { var i, option, urlConfig = QUnit.config.urlConfig; for (i = 0; i < urlConfig.length; i++) { // Options can be either strings or objects with nonempty "id" properties option = QUnit.config.urlConfig[i]; if (typeof option !== "string") { option = option.id; } if (QUnit.config[option] === undefined) { QUnit.config[option] = urlParams[option]; } } }); function getUrlParams() { var i, param, name, value; var urlParams = Object.create(null); var params = location.search.slice(1).split("&"); var length = params.length; for (i = 0; i < length; i++) { if (params[i]) { param = params[i].split("="); name = decodeQueryParam(param[0]); // Allow just a key to turn on a flag, e.g., test.html?noglobals value = param.length === 1 || decodeQueryParam(param.slice(1).join("=")); if (name in urlParams) { urlParams[name] = [].concat(urlParams[name], value); } else { urlParams[name] = value; } } } return urlParams; } function decodeQueryParam(param) { return decodeURIComponent(param.replace(/\+/g, "%20")); } })(); var stats = { passedTests: 0, failedTests: 0, skippedTests: 0, todoTests: 0 }; // Escape text for attribute or text content. function escapeText(s) { if (!s) { return ""; } s = s + ""; // Both single quotes and double quotes (for attributes) return s.replace(/['"<>&]/g, function (s) { switch (s) { case "'": return "&#039;"; case "\"": return "&quot;"; case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; } }); } (function () { // Don't load the HTML Reporter on non-browser environments if (typeof window === "undefined" || !window.document) { return; } var config = QUnit.config, document$$1 = window.document, collapseNext = false, hasOwn = Object.prototype.hasOwnProperty, unfilteredUrl = setUrl({ filter: undefined, module: undefined, moduleId: undefined, testId: undefined }), modulesList = []; function addEvent(elem, type, fn) { elem.addEventListener(type, fn, false); } function removeEvent(elem, type, fn) { elem.removeEventListener(type, fn, false); } function addEvents(elems, type, fn) { var i = elems.length; while (i--) { addEvent(elems[i], type, fn); } } function hasClass(elem, name) { return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0; } function addClass(elem, name) { if (!hasClass(elem, name)) { elem.className += (elem.className ? " " : "") + name; } } function toggleClass(elem, name, force) { if (force || typeof force === "undefined" && !hasClass(elem, name)) { addClass(elem, name); } else { removeClass(elem, name); } } function removeClass(elem, name) { var set = " " + elem.className + " "; // Class name may appear multiple times while (set.indexOf(" " + name + " ") >= 0) { set = set.replace(" " + name + " ", " "); } // Trim for prettiness elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, ""); } function id(name) { return document$$1.getElementById && document$$1.getElementById(name); } function abortTests() { var abortButton = id("qunit-abort-tests-button"); if (abortButton) { abortButton.disabled = true; abortButton.innerHTML = "Aborting..."; } QUnit.config.queue.length = 0; return false; } function interceptNavigation(ev) { applyUrlParams(); if (ev && ev.preventDefault) { ev.preventDefault(); } return false; } function getUrlConfigHtml() { var i, j, val, escaped, escapedTooltip, selection = false, urlConfig = config.urlConfig, urlConfigHtml = ""; for (i = 0; i < urlConfig.length; i++) { // Options can be either strings or objects with nonempty "id" properties val = config.urlConfig[i]; if (typeof val === "string") { val = { id: val, label: val }; } escaped = escapeText(val.id); escapedTooltip = escapeText(val.tooltip); if (!val.value || typeof val.value === "string") { urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'><input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + (val.value ? " value='" + escapeText(val.value) + "'" : "") + (config[val.id] ? " checked='checked'" : "") + " title='" + escapedTooltip + "' />" + escapeText(val.label) + "</label>"; } else { urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>"; if (QUnit.is("array", val.value)) { for (j = 0; j < val.value.length; j++) { escaped = escapeText(val.value[j]); urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>"; } } else { for (j in val.value) { if (hasOwn.call(val.value, j)) { urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>"; } } } if (config[val.id] && !selection) { escaped = escapeText(config[val.id]); urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>"; } urlConfigHtml += "</select>"; } } return urlConfigHtml; } // Handle "click" events on toolbar checkboxes and "change" for select menus. // Updates the URL with the new state of `config.urlConfig` values. function toolbarChanged() { var updatedUrl, value, tests, field = this, params = {}; // Detect if field is a select menu or a checkbox if ("selectedIndex" in field) { value = field.options[field.selectedIndex].value || undefined; } else { value = field.checked ? field.defaultValue || true : undefined; } params[field.name] = value; updatedUrl = setUrl(params); // Check if we can apply the change without a page refresh if ("hidepassed" === field.name && "replaceState" in window.history) { QUnit.urlParams[field.name] = value; config[field.name] = value || false; tests = id("qunit-tests"); if (tests) { toggleClass(tests, "hidepass", value || false); } window.history.replaceState(null, "", updatedUrl); } else { window.location = updatedUrl; } } function setUrl(params) { var key, arrValue, i, querystring = "?", location = window.location; params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params); for (key in params) { // Skip inherited or undefined properties if (hasOwn.call(params, key) && params[key] !== undefined) { // Output a parameter for each value of this key (but usually just one) arrValue = [].concat(params[key]); for (i = 0; i < arrValue.length; i++) { querystring += encodeURIComponent(key); if (arrValue[i] !== true) { querystring += "=" + encodeURIComponent(arrValue[i]); } querystring += "&"; } } } return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1); } function applyUrlParams() { var i, selectedModules = [], modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"), filter = id("qunit-filter-input").value; for (i = 0; i < modulesList.length; i++) { if (modulesList[i].checked) { selectedModules.push(modulesList[i].value); } } window.location = setUrl({ filter: filter === "" ? undefined : filter, moduleId: selectedModules.length === 0 ? undefined : selectedModules, // Remove module and testId filter module: undefined, testId: undefined }); } function toolbarUrlConfigContainer() { var urlConfigContainer = document$$1.createElement("span"); urlConfigContainer.innerHTML = getUrlConfigHtml(); addClass(urlConfigContainer, "qunit-url-config"); addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged); addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged); return urlConfigContainer; } function abortTestsButton() { var button = document$$1.createElement("button"); button.id = "qunit-abort-tests-button"; button.innerHTML = "Abort"; addEvent(button, "click", abortTests); return button; } function toolbarLooseFilter() { var filter = document$$1.createElement("form"), label = document$$1.createElement("label"), input = document$$1.createElement("input"), button = document$$1.createElement("button"); addClass(filter, "qunit-filter"); label.innerHTML = "Filter: "; input.type = "text"; input.value = config.filter || ""; input.name = "filter"; input.id = "qunit-filter-input"; button.innerHTML = "Go"; label.appendChild(input); filter.appendChild(label); filter.appendChild(document$$1.createTextNode(" ")); filter.appendChild(button); addEvent(filter, "submit", interceptNavigation); return filter; } function moduleListHtml() { var i, checked, html = ""; for (i = 0; i < config.modules.length; i++) { if (config.modules[i].name !== "") { checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1; html += "<li><label class='clickable" + (checked ? " checked" : "") + "'><input type='checkbox' " + "value='" + config.modules[i].moduleId + "'" + (checked ? " checked='checked'" : "") + " />" + escapeText(config.modules[i].name) + "</label></li>"; } } return html; } function toolbarModuleFilter() { var allCheckbox, commit, reset, moduleFilter = document$$1.createElement("form"), label = document$$1.createElement("label"), moduleSearch = document$$1.createElement("input"), dropDown = document$$1.createElement("div"), actions = document$$1.createElement("span"), dropDownList = document$$1.createElement("ul"), dirty = false; moduleSearch.id = "qunit-modulefilter-search"; addEvent(moduleSearch, "input", searchInput); addEvent(moduleSearch, "input", searchFocus); addEvent(moduleSearch, "focus", searchFocus); addEvent(moduleSearch, "click", searchFocus); label.id = "qunit-modulefilter-search-container"; label.innerHTML = "Module: "; label.appendChild(moduleSearch); actions.id = "qunit-modulefilter-actions"; actions.innerHTML = "<button style='display:none'>Apply</button>" + "<button type='reset' style='display:none'>Reset</button>" + "<label class='clickable" + (config.moduleId.length ? "" : " checked") + "'><input type='checkbox'" + (config.moduleId.length ? "" : " checked='checked'") + ">All modules</label>"; allCheckbox = actions.lastChild.firstChild; commit = actions.firstChild; reset = commit.nextSibling; addEvent(commit, "click", applyUrlParams); dropDownList.id = "qunit-modulefilter-dropdown-list"; dropDownList.innerHTML = moduleListHtml(); dropDown.id = "qunit-modulefilter-dropdown"; dropDown.style.display = "none"; dropDown.appendChild(actions); dropDown.appendChild(dropDownList); addEvent(dropDown, "change", selectionChange); selectionChange(); moduleFilter.id = "qunit-modulefilter"; moduleFilter.appendChild(label); moduleFilter.appendChild(dropDown); addEvent(moduleFilter, "submit", interceptNavigation); addEvent(moduleFilter, "reset", function () { // Let the reset happen, then update styles window.setTimeout(selectionChange); }); // Enables show/hide for the dropdown function searchFocus() { if (dropDown.style.display !== "none") { return; } dropDown.style.display = "block"; addEvent(document$$1, "click", hideHandler); addEvent(document$$1, "keydown", hideHandler); // Hide on Escape keydown or outside-container click function hideHandler(e) { var inContainer = moduleFilter.contains(e.target); if (e.keyCode === 27 || !inContainer) { if (e.keyCode === 27 && inContainer) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent(document$$1, "click", hideHandler); removeEvent(document$$1, "keydown", hideHandler); moduleSearch.value = ""; searchInput(); } } } // Processes module search box input function searchInput() { var i, item, searchText = moduleSearch.value.toLowerCase(), listItems = dropDownList.children; for (i = 0; i < listItems.length; i++) { item = listItems[i]; if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) { item.style.display = ""; } else { item.style.display = "none"; } } } // Processes selection changes function selectionChange(evt) { var i, item, checkbox = evt && evt.target || allCheckbox, modulesList = dropDownList.getElementsByTagName("input"), selectedNames = []; toggleClass(checkbox.parentNode, "checked", checkbox.checked); dirty = false; if (checkbox.checked && checkbox !== allCheckbox) { allCheckbox.checked = false; removeClass(allCheckbox.parentNode, "checked"); } for (i = 0; i < modulesList.length; i++) { item = modulesList[i]; if (!evt) { toggleClass(item.parentNode, "checked", item.checked); } else if (checkbox === allCheckbox && checkbox.checked) { item.checked = false; removeClass(item.parentNode, "checked"); } dirty = dirty || item.checked !== item.defaultChecked; if (item.checked) { selectedNames.push(item.parentNode.textContent); } } commit.style.display = reset.style.display = dirty ? "" : "none"; moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent; moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent); } return moduleFilter; } function appendToolbar() { var toolbar = id("qunit-testrunner-toolbar"); if (toolbar) { toolbar.appendChild(toolbarUrlConfigContainer()); toolbar.appendChild(toolbarModuleFilter()); toolbar.appendChild(toolbarLooseFilter()); toolbar.appendChild(document$$1.createElement("div")).className = "clearfix"; } } function appendHeader() { var header = id("qunit-header"); if (header) { header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> "; } } function appendBanner() { var banner = id("qunit-banner"); if (banner) { banner.className = ""; } } function appendTestResults() { var tests = id("qunit-tests"), result = id("qunit-testresult"), controls; if (result) { result.parentNode.removeChild(result); } if (tests) { tests.innerHTML = ""; result = document$$1.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore(result, tests); result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br />&#160;</div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>"; controls = id("qunit-testresult-controls"); } if (controls) { controls.appendChild(abortTestsButton()); } } function appendFilteredTest() { var testId = QUnit.config.testId; if (!testId || testId.length <= 0) { return ""; } return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>"; } function appendUserAgent() { var userAgent = id("qunit-userAgent"); if (userAgent) { userAgent.innerHTML = ""; userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent)); } } function appendInterface() { var qunit = id("qunit"); if (qunit) { qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText(document$$1.title) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + appendFilteredTest() + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>"; } appendHeader(); appendBanner(); appendTestResults(); appendUserAgent(); appendToolbar(); } function appendTestsList(modules) { var i, l, x, z, test, moduleObj; for (i = 0, l = modules.length; i < l; i++) { moduleObj = modules[i]; for (x = 0, z = moduleObj.tests.length; x < z; x++) { test = moduleObj.tests[x]; appendTest(test.name, test.testId, moduleObj.name); } } } function appendTest(name, testId, moduleName) { var title, rerunTrigger, testBlock, assertList, tests = id("qunit-tests"); if (!tests) { return; } title = document$$1.createElement("strong"); title.innerHTML = getNameHtml(name, moduleName); rerunTrigger = document$$1.createElement("a"); rerunTrigger.innerHTML = "Rerun"; rerunTrigger.href = setUrl({ testId: testId }); testBlock = document$$1.createElement("li"); testBlock.appendChild(title); testBlock.appendChild(rerunTrigger); testBlock.id = "qunit-test-output-" + testId; assertList = document$$1.createElement("ol"); assertList.className = "qunit-assert-list"; testBlock.appendChild(assertList); tests.appendChild(testBlock); } // HTML Reporter initialization and load QUnit.begin(function (details) { var i, moduleObj, tests; // Sort modules by name for the picker for (i = 0; i < details.modules.length; i++) { moduleObj = details.modules[i]; if (moduleObj.name) { modulesList.push(moduleObj.name); } } modulesList.sort(function (a, b) { return a.localeCompare(b); }); // Initialize QUnit elements appendInterface(); appendTestsList(details.modules); tests = id("qunit-tests"); if (tests && config.hidepassed) { addClass(tests, "hidepass"); } }); QUnit.done(function (details) { var banner = id("qunit-banner"), tests = id("qunit-tests"), abortButton = id("qunit-abort-tests-button"), totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests, html = [totalTests, " tests completed in ", details.runtime, " milliseconds, with ", stats.failedTests, " failed, ", stats.skippedTests, " skipped, and ", stats.todoTests, " todo.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed."].join(""), test, assertLi, assertList; // Update remaing tests to aborted if (abortButton && abortButton.disabled) { html = "Tests aborted after " + details.runtime + " milliseconds."; for (var i = 0; i < tests.children.length; i++) { test = tests.children[i]; if (test.className === "" || test.className === "running") { test.className = "aborted"; assertList = test.getElementsByTagName("ol")[0]; assertLi = document$$1.createElement("li"); assertLi.className = "fail"; assertLi.innerHTML = "Test aborted."; assertList.appendChild(assertLi); } } } if (banner && (!abortButton || abortButton.disabled === false)) { banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass"; } if (abortButton) { abortButton.parentNode.removeChild(abortButton); } if (tests) { id("qunit-testresult-display").innerHTML = html; } if (config.altertitle && document$$1.title) { // Show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document$$1.title = [stats.failedTests ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" "); } // Scroll back to top to show results if (config.scrolltop && window.scrollTo) { window.scrollTo(0, 0); } }); function getNameHtml(name, module) { var nameHtml = ""; if (module) { nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: "; } nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>"; return nameHtml; } QUnit.testStart(function (details) { var running, testBlock, bad; testBlock = id("qunit-test-output-" + details.testId); if (testBlock) { testBlock.className = "running"; } else { // Report later registered tests appendTest(details.name, details.testId, details.module); } running = id("qunit-testresult-display"); if (running) { bad = QUnit.config.reorder && details.previousFailure; running.innerHTML = (bad ? "Rerunning previously failed test: <br />" : "Running: <br />") + getNameHtml(details.name, details.module); } }); function stripHtml(string) { // Strip tags, html entity and whitespaces return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\&quot;/g, "").replace(/\s+/g, ""); } QUnit.log(function (details) { var assertList, assertLi, message, expected, actual, diff, showDiff = false, testItem = id("qunit-test-output-" + details.testId); if (!testItem) { return; } message = escapeText(details.message) || (details.result ? "okay" : "failed"); message = "<span class='test-message'>" + message + "</span>"; message += "<span class='runtime'>@ " + details.runtime + " ms</span>"; // The pushFailure doesn't provide details.expected // when it calls, it's implicit to also not show expected and diff stuff // Also, we need to check details.expected existence, as it can exist and be undefined if (!details.result && hasOwn.call(details, "expected")) { if (details.negative) { expected = "NOT " + QUnit.dump.parse(details.expected); } else { expected = QUnit.dump.parse(details.expected); } actual = QUnit.dump.parse(details.actual); message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>"; if (actual !== expected) { message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>"; if (typeof details.actual === "number" && typeof details.expected === "number") { if (!isNaN(details.actual) && !isNaN(details.expected)) { showDiff = true; diff = details.actual - details.expected; diff = (diff > 0 ? "+" : "") + diff; } } else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") { diff = QUnit.diff(expected, actual); // don't show diff if there is zero overlap showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length; } if (showDiff) { message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>"; } } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) { message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the depth of object is more than current max depth (" + QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " + " run with a higher max depth or <a href='" + escapeText(setUrl({ maxDepth: -1 })) + "'>" + "Rerun</a> without max depth.</p></td></tr>"; } else { message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>"; } if (details.source) { message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>"; } message += "</table>"; // This occurs when pushFailure is set and we have an extracted stack trace } else if (!details.result && details.source) { message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>"; } assertList = testItem.getElementsByTagName("ol")[0]; assertLi = document$$1.createElement("li"); assertLi.className = details.result ? "pass" : "fail"; assertLi.innerHTML = message; assertList.appendChild(assertLi); }); QUnit.testDone(function (details) { var testTitle, time, testItem, assertList, good, bad, testCounts, skipped, sourceName, tests = id("qunit-tests"); if (!tests) { return; } testItem = id("qunit-test-output-" + details.testId); assertList = testItem.getElementsByTagName("ol")[0]; good = details.passed; bad = details.failed; // This test passed if it has no unexpected failed assertions var testPassed = details.failed > 0 ? details.todo : !details.todo; if (testPassed) { // Collapse the passing tests addClass(assertList, "qunit-collapsed"); } else if (config.collapse) { if (!collapseNext) { // Skip collapsing the first failing test collapseNext = true; } else { // Collapse remaining tests addClass(assertList, "qunit-collapsed"); } } // The testItem.firstChild is the test name testTitle = testItem.firstChild; testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : ""; testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>"; if (details.skipped) { stats.skippedTests++; testItem.className = "skipped"; skipped = document$$1.createElement("em"); skipped.className = "qunit-skipped-label"; skipped.innerHTML = "skipped"; testItem.insertBefore(skipped, testTitle); } else { addEvent(testTitle, "click", function () { toggleClass(assertList, "qunit-collapsed"); }); testItem.className = testPassed ? "pass" : "fail"; if (details.todo) { var todoLabel = document$$1.createElement("em"); todoLabel.className = "qunit-todo-label"; todoLabel.innerHTML = "todo"; testItem.className += " todo"; testItem.insertBefore(todoLabel, testTitle); } time = document$$1.createElement("span"); time.className = "runtime"; time.innerHTML = details.runtime + " ms"; testItem.insertBefore(time, assertList); if (!testPassed) { stats.failedTests++; } else if (details.todo) { stats.todoTests++; } else { stats.passedTests++; } } // Show the source of the test when showing assertions if (details.source) { sourceName = document$$1.createElement("p"); sourceName.innerHTML = "<strong>Source: </strong>" + details.source; addClass(sourceName, "qunit-source"); if (testPassed) { addClass(sourceName, "qunit-collapsed"); } addEvent(testTitle, "click", function () { toggleClass(sourceName, "qunit-collapsed"); }); testItem.appendChild(sourceName); } }); // Avoid readyState issue with phantomjs // Ref: #818 var notPhantom = function (p) { return !(p && p.version && p.version.major > 0); }(window.phantom); if (notPhantom && document$$1.readyState === "complete") { QUnit.load(); } else { addEvent(window, "load", QUnit.load); } // Wrap window.onerror. We will call the original window.onerror to see if // the existing handler fully handles the error; if not, we will call the // QUnit.onError function. var originalWindowOnError = window.onerror; // Cover uncaught exceptions // Returning true will suppress the default browser handler, // returning false will let it run. window.onerror = function (message, fileName, lineNumber) { var ret = false; if (originalWindowOnError) { for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { args[_key - 3] = arguments[_key]; } ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber].concat(args)); } // Treat return value as window.onerror itself does, // Only do our handling if not suppressed. if (ret !== true) { var error = { message: message, fileName: fileName, lineNumber: lineNumber }; ret = QUnit.onError(error); } return ret; }; })(); /* * This file is a modified version of google-diff-match-patch's JavaScript implementation * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js), * modifications are licensed as more fully set forth in LICENSE.txt. * * The original source of google-diff-match-patch is attributable and licensed as follows: * * Copyright 2006 Google Inc. * https://code.google.com/p/google-diff-match-patch/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * More Info: * https://code.google.com/p/google-diff-match-patch/ * * Usage: QUnit.diff(expected, actual) * */ QUnit.diff = function () { function DiffMatchPatch() {} // DIFF FUNCTIONS /** * The data structure representing a diff is an array of tuples: * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] * which means: delete 'Hello', add 'Goodbye' and keep ' world.' */ var DIFF_DELETE = -1, DIFF_INSERT = 1, DIFF_EQUAL = 0; /** * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean=} optChecklines Optional speedup flag. If present and false, * then don't run a line-level diff first to identify the changed areas. * Defaults to true, which does a faster, slightly less optimal diff. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. */ DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) { var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs; // The diff must be complete in up to 1 second. deadline = new Date().getTime() + 1000; // Check for null inputs. if (text1 === null || text2 === null) { throw new Error("Null input. (DiffMain)"); } // Check for equality (speedup). if (text1 === text2) { if (text1) { return [[DIFF_EQUAL, text1]]; } return []; } if (typeof optChecklines === "undefined") { optChecklines = true; } checklines = optChecklines; // Trim off common prefix (speedup). commonlength = this.diffCommonPrefix(text1, text2); commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); // Trim off common suffix (speedup). commonlength = this.diffCommonSuffix(text1, text2); commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); // Compute the diff on the middle block. diffs = this.diffCompute(text1, text2, checklines, deadline); // Restore the prefix and suffix. if (commonprefix) { diffs.unshift([DIFF_EQUAL, commonprefix]); } if (commonsuffix) { diffs.push([DIFF_EQUAL, commonsuffix]); } this.diffCleanupMerge(diffs); return diffs; }; /** * Reduce the number of edits by eliminating operationally trivial equalities. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. */ DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) { var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel; changes = false; equalities = []; // Stack of indices where equalities are found. equalitiesLength = 0; // Keeping our own length var is faster in JS. /** @type {?string} */ lastequality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1] pointer = 0; // Index of current position. // Is there an insertion operation before the last equality. preIns = false; // Is there a deletion operation before the last equality. preDel = false; // Is there an insertion operation after the last equality. postIns = false; // Is there a deletion operation after the last equality. postDel = false; while (pointer < diffs.length) { // Equality found. if (diffs[pointer][0] === DIFF_EQUAL) { if (diffs[pointer][1].length < 4 && (postIns || postDel)) { // Candidate found. equalities[equalitiesLength++] = pointer; preIns = postIns; preDel = postDel; lastequality = diffs[pointer][1]; } else { // Not a candidate, and can never become one. equalitiesLength = 0; lastequality = null; } postIns = postDel = false; // An insertion or deletion. } else { if (diffs[pointer][0] === DIFF_DELETE) { postDel = true; } else { postIns = true; } /* * Five types to be split: * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> * <ins>A</ins>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<ins>C</ins> * <ins>A</del>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<del>C</del> */ if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) { // Duplicate record. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); // Change second copy to insert. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; equalitiesLength--; // Throw away the equality we just deleted; lastequality = null; if (preIns && preDel) { // No changes made which could affect previous entry, keep going. postIns = postDel = true; equalitiesLength = 0; } else { equalitiesLength--; // Throw away the previous equality. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; postIns = postDel = false; } changes = true; } } pointer++; } if (changes) { this.diffCleanupMerge(diffs); } }; /** * Convert a diff array into a pretty HTML report. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. * @param {integer} string to be beautified. * @return {string} HTML representation. */ DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) { var op, data, x, html = []; for (x = 0; x < diffs.length; x++) { op = diffs[x][0]; // Operation (insert, delete, equal) data = diffs[x][1]; // Text of change. switch (op) { case DIFF_INSERT: html[x] = "<ins>" + escapeText(data) + "</ins>"; break; case DIFF_DELETE: html[x] = "<del>" + escapeText(data) + "</del>"; break; case DIFF_EQUAL: html[x] = "<span>" + escapeText(data) + "</span>"; break; } } return html.join(""); }; /** * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. */ DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) { var pointermid, pointermax, pointermin, pointerstart; // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0; pointermax = Math.min(text1.length, text2.length); pointermid = pointermax; pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. */ DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) { var pointermid, pointermax, pointermin, pointerend; // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0; pointermax = Math.min(text1.length, text2.length); pointermid = pointermax; pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} checklines Speedup flag. If false, then don't run a * line-level diff first to identify the changed areas. * If true, then run a faster, slightly less optimal diff. * @param {number} deadline Time when the diff should be complete by. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. * @private */ DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) { var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB; if (!text1) { // Just add some text (speedup). return [[DIFF_INSERT, text2]]; } if (!text2) { // Just delete some text (speedup). return [[DIFF_DELETE, text1]]; } longtext = text1.length > text2.length ? text1 : text2; shorttext = text1.length > text2.length ? text2 : text1; i = longtext.indexOf(shorttext); if (i !== -1) { // Shorter text is inside the longer text (speedup). diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; // Swap insertions for deletions if diff is reversed. if (text1.length > text2.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE; } return diffs; } if (shorttext.length === 1) { // Single character string. // After the previous speedup, the character can't be an equality. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; } // Check to see if the problem can be split in two. hm = this.diffHalfMatch(text1, text2); if (hm) { // A half-match was found, sort out the return data. text1A = hm[0]; text1B = hm[1]; text2A = hm[2]; text2B = hm[3]; midCommon = hm[4]; // Send both pairs off for separate processing. diffsA = this.DiffMain(text1A, text2A, checklines, deadline); diffsB = this.DiffMain(text1B, text2B, checklines, deadline); // Merge the results. return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB); } if (checklines && text1.length > 100 && text2.length > 100) { return this.diffLineMode(text1, text2, deadline); } return this.diffBisect(text1, text2, deadline); }; /** * Do the two texts share a substring which is at least half the length of the * longer text? * This speedup can produce non-minimal diffs. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {Array.<string>} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or null if there was no match. * @private */ DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) { var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm; longtext = text1.length > text2.length ? text1 : text2; shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; // Pointless. } dmp = this; // 'this' becomes 'window' in a closure. /** * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * Closure, but does not reference any external variables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {Array.<string>} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or null if there was no match. * @private */ function diffHalfMatchI(longtext, shorttext, i) { var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; // Start with a 1/4 length substring at position i as a seed. seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); j = -1; bestCommon = ""; while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j)); suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); if (bestCommon.length < suffixLength + prefixLength) { bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); bestLongtextA = longtext.substring(0, i - suffixLength); bestLongtextB = longtext.substring(i + prefixLength); bestShorttextA = shorttext.substring(0, j - suffixLength); bestShorttextB = shorttext.substring(j + prefixLength); } } if (bestCommon.length * 2 >= longtext.length) { return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon]; } else { return null; } } // First check if the second quarter is the seed for a half-match. hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4)); // Check again based on the third quarter. hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2)); if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { // Both matched. Select the longest. hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } // A half-match was found, sort out the return data. if (text1.length > text2.length) { text1A = hm[0]; text1B = hm[1]; text2A = hm[2]; text2B = hm[3]; } else { text2A = hm[0]; text2B = hm[1]; text1A = hm[2]; text1B = hm[3]; } midCommon = hm[4]; return [text1A, text1B, text2A, text2B, midCommon]; }; /** * Do a quick line-level diff on both strings, then rediff the parts for * greater accuracy. * This speedup can produce non-minimal diffs. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time when the diff should be complete by. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. * @private */ DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) { var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j; // Scan the text on a line-by-line basis first. a = this.diffLinesToChars(text1, text2); text1 = a.chars1; text2 = a.chars2; linearray = a.lineArray; diffs = this.DiffMain(text1, text2, false, deadline); // Convert the diff back to original text. this.diffCharsToLines(diffs, linearray); // Eliminate freak matches (e.g. blank lines) this.diffCleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. diffs.push([DIFF_EQUAL, ""]); pointer = 0; countDelete = 0; countInsert = 0; textDelete = ""; textInsert = ""; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: countInsert++; textInsert += diffs[pointer][1]; break; case DIFF_DELETE: countDelete++; textDelete += diffs[pointer][1]; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (countDelete >= 1 && countInsert >= 1) { // Delete the offending records and add the merged ones. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert); pointer = pointer - countDelete - countInsert; a = this.DiffMain(textDelete, textInsert, false, deadline); for (j = a.length - 1; j >= 0; j--) { diffs.splice(pointer, 0, a[j]); } pointer = pointer + a.length; } countInsert = 0; countDelete = 0; textDelete = ""; textInsert = ""; break; } pointer++; } diffs.pop(); // Remove the dummy entry at the end. return diffs; }; /** * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time at which to bail if not yet complete. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. * @private */ DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) { var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2; // Cache the text lengths to prevent multiple calls. text1Length = text1.length; text2Length = text2.length; maxD = Math.ceil((text1Length + text2Length) / 2); vOffset = maxD; vLength = 2 * maxD; v1 = new Array(vLength); v2 = new Array(vLength); // Setting all elements to -1 is faster in Chrome & Firefox than mixing // integers and undefined. for (x = 0; x < vLength; x++) { v1[x] = -1; v2[x] = -1; } v1[vOffset + 1] = 0; v2[vOffset + 1] = 0; delta = text1Length - text2Length; // If the total number of characters is odd, then the front path will collide // with the reverse path. front = delta % 2 !== 0; // Offsets for start and end of k loop. // Prevents mapping of space beyond the grid. k1start = 0; k1end = 0; k2start = 0; k2end = 0; for (d = 0; d < maxD; d++) { // Bail out if deadline is reached. if (new Date().getTime() > deadline) { break; } // Walk the front path one step. for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { k1Offset = vOffset + k1; if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) { x1 = v1[k1Offset + 1]; } else { x1 = v1[k1Offset - 1] + 1; } y1 = x1 - k1; while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) { x1++; y1++; } v1[k1Offset] = x1; if (x1 > text1Length) { // Ran off the right of the graph. k1end += 2; } else if (y1 > text2Length) { // Ran off the bottom of the graph. k1start += 2; } else if (front) { k2Offset = vOffset + delta - k1; if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) { // Mirror x2 onto top-left coordinate system. x2 = text1Length - v2[k2Offset]; if (x1 >= x2) { // Overlap detected. return this.diffBisectSplit(text1, text2, x1, y1, deadline); } } } } // Walk the reverse path one step. for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { k2Offset = vOffset + k2; if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) { x2 = v2[k2Offset + 1]; } else { x2 = v2[k2Offset - 1] + 1; } y2 = x2 - k2; while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) { x2++; y2++; } v2[k2Offset] = x2; if (x2 > text1Length) { // Ran off the left of the graph. k2end += 2; } else if (y2 > text2Length) { // Ran off the top of the graph. k2start += 2; } else if (!front) { k1Offset = vOffset + delta - k2; if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) { x1 = v1[k1Offset]; y1 = vOffset + x1 - k1Offset; // Mirror x2 onto top-left coordinate system. x2 = text1Length - x2; if (x1 >= x2) { // Overlap detected. return this.diffBisectSplit(text1, text2, x1, y1, deadline); } } } } } // Diff took too long and hit the deadline or // number of diffs equals number of characters, no commonality at all. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; }; /** * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @param {number} deadline Time at which to bail if not yet complete. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. * @private */ DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) { var text1a, text1b, text2a, text2b, diffs, diffsb; text1a = text1.substring(0, x); text2a = text2.substring(0, y); text1b = text1.substring(x); text2b = text2.substring(y); // Compute both diffs serially. diffs = this.DiffMain(text1a, text2a, false, deadline); diffsb = this.DiffMain(text1b, text2b, false, deadline); return diffs.concat(diffsb); }; /** * Reduce the number of edits by eliminating semantically trivial equalities. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. */ DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) { var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2; changes = false; equalities = []; // Stack of indices where equalities are found. equalitiesLength = 0; // Keeping our own length var is faster in JS. /** @type {?string} */ lastequality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1] pointer = 0; // Index of current position. // Number of characters that changed prior to the equality. lengthInsertions1 = 0; lengthDeletions1 = 0; // Number of characters that changed after the equality. lengthInsertions2 = 0; lengthDeletions2 = 0; while (pointer < diffs.length) { if (diffs[pointer][0] === DIFF_EQUAL) { // Equality found. equalities[equalitiesLength++] = pointer; lengthInsertions1 = lengthInsertions2; lengthDeletions1 = lengthDeletions2; lengthInsertions2 = 0; lengthDeletions2 = 0; lastequality = diffs[pointer][1]; } else { // An insertion or deletion. if (diffs[pointer][0] === DIFF_INSERT) { lengthInsertions2 += diffs[pointer][1].length; } else { lengthDeletions2 += diffs[pointer][1].length; } // Eliminate an equality that is smaller or equal to the edits on both // sides of it. if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) { // Duplicate record. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); // Change second copy to insert. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; // Throw away the equality we just deleted. equalitiesLength--; // Throw away the previous equality (it needs to be reevaluated). equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; // Reset the counters. lengthInsertions1 = 0; lengthDeletions1 = 0; lengthInsertions2 = 0; lengthDeletions2 = 0; lastequality = null; changes = true; } } pointer++; } // Normalize the diff. if (changes) { this.diffCleanupMerge(diffs); } // Find any overlaps between deletions and insertions. // e.g: <del>abcxxx</del><ins>xxxdef</ins> // -> <del>abc</del>xxx<ins>def</ins> // e.g: <del>xxxabc</del><ins>defxxx</ins> // -> <ins>def</ins>xxx<del>abc</del> // Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 1; while (pointer < diffs.length) { if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { deletion = diffs[pointer - 1][1]; insertion = diffs[pointer][1]; overlapLength1 = this.diffCommonOverlap(deletion, insertion); overlapLength2 = this.diffCommonOverlap(insertion, deletion); if (overlapLength1 >= overlapLength2) { if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) { // Overlap found. Insert an equality and trim the surrounding edits. diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]); diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1); diffs[pointer + 1][1] = insertion.substring(overlapLength1); pointer++; } } else { if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) { // Reverse overlap found. // Insert an equality and swap and trim the surrounding edits. diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]); diffs[pointer - 1][0] = DIFF_INSERT; diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2); diffs[pointer + 1][0] = DIFF_DELETE; diffs[pointer + 1][1] = deletion.substring(overlapLength2); pointer++; } } pointer++; } pointer++; } }; /** * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private */ DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) { var text1Length, text2Length, textLength, best, length, pattern, found; // Cache the text lengths to prevent multiple calls. text1Length = text1.length; text2Length = text2.length; // Eliminate the null case. if (text1Length === 0 || text2Length === 0) { return 0; } // Truncate the longer string. if (text1Length > text2Length) { text1 = text1.substring(text1Length - text2Length); } else if (text1Length < text2Length) { text2 = text2.substring(0, text1Length); } textLength = Math.min(text1Length, text2Length); // Quick check for the worst case. if (text1 === text2) { return textLength; } // Start by looking for a single character match // and increase length until no match is found. // Performance analysis: https://neil.fraser.name/news/2010/11/04/ best = 0; length = 1; while (true) { pattern = text1.substring(textLength - length); found = text2.indexOf(pattern); if (found === -1) { return best; } length += found; if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) { best = length; length++; } } }; /** * Split two texts into an array of strings. Reduce the texts to a string of * hashes where each Unicode character represents one line. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}} * An object containing the encoded text1, the encoded text2 and * the array of unique strings. * The zeroth element of the array of unique strings is intentionally blank. * @private */ DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) { var lineArray, lineHash, chars1, chars2; lineArray = []; // E.g. lineArray[4] === 'Hello\n' lineHash = {}; // E.g. lineHash['Hello\n'] === 4 // '\x00' is a valid character, but various debuggers don't like it. // So we'll insert a junk entry to avoid generating a null character. lineArray[0] = ""; /** * Split a text into an array of strings. Reduce the texts to a string of * hashes where each Unicode character represents one line. * Modifies linearray and linehash through being a closure. * @param {string} text String to encode. * @return {string} Encoded string. * @private */ function diffLinesToCharsMunge(text) { var chars, lineStart, lineEnd, lineArrayLength, line; chars = ""; // Walk the text, pulling out a substring for each line. // text.split('\n') would would temporarily double our memory footprint. // Modifying text would create many large strings to garbage collect. lineStart = 0; lineEnd = -1; // Keeping our own length variable is faster than looking it up. lineArrayLength = lineArray.length; while (lineEnd < text.length - 1) { lineEnd = text.indexOf("\n", lineStart); if (lineEnd === -1) { lineEnd = text.length - 1; } line = text.substring(lineStart, lineEnd + 1); lineStart = lineEnd + 1; if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined) { chars += String.fromCharCode(lineHash[line]); } else { chars += String.fromCharCode(lineArrayLength); lineHash[line] = lineArrayLength; lineArray[lineArrayLength++] = line; } } return chars; } chars1 = diffLinesToCharsMunge(text1); chars2 = diffLinesToCharsMunge(text2); return { chars1: chars1, chars2: chars2, lineArray: lineArray }; }; /** * Rehydrate the text in a diff from a string of line hashes to real lines of * text. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. * @param {!Array.<string>} lineArray Array of unique strings. * @private */ DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) { var x, chars, text, y; for (x = 0; x < diffs.length; x++) { chars = diffs[x][1]; text = []; for (y = 0; y < chars.length; y++) { text[y] = lineArray[chars.charCodeAt(y)]; } diffs[x][1] = text.join(""); } }; /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. */ DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) { var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position; diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end. pointer = 0; countDelete = 0; countInsert = 0; textDelete = ""; textInsert = ""; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: countInsert++; textInsert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: countDelete++; textDelete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (countDelete + countInsert > 1) { if (countDelete !== 0 && countInsert !== 0) { // Factor out any common prefixes. commonlength = this.diffCommonPrefix(textInsert, textDelete); if (commonlength !== 0) { if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) { diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength); } else { diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]); pointer++; } textInsert = textInsert.substring(commonlength); textDelete = textDelete.substring(commonlength); } // Factor out any common suffixies. commonlength = this.diffCommonSuffix(textInsert, textDelete); if (commonlength !== 0) { diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1]; textInsert = textInsert.substring(0, textInsert.length - commonlength); textDelete = textDelete.substring(0, textDelete.length - commonlength); } } // Delete the offending records and add the merged ones. if (countDelete === 0) { diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]); } else if (countInsert === 0) { diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]); } else { diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]); } pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1; } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { // Merge this equality with the previous one. diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } countInsert = 0; countDelete = 0; textDelete = ""; textInsert = ""; break; } } if (diffs[diffs.length - 1][1] === "") { diffs.pop(); // Remove the dummy entry at the end. } // Second pass: look for single edits surrounded on both sides by equalities // which can be shifted sideways to eliminate an equality. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC changes = false; pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { diffPointer = diffs[pointer][1]; position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length); // This is a single edit surrounded by equalities. if (position === diffs[pointer - 1][1]) { // Shift the edit over the previous equality. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { // Shift the edit over the next equality. diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { this.diffCleanupMerge(diffs); } }; return function (o, n) { var diff, output, text; diff = new DiffMatchPatch(); output = diff.DiffMain(o, n); diff.diffCleanupEfficiency(output); text = diff.diffPrettyHtml(output); return text; }; }(); }((function() { return this; }()))); QUnit.notifications = function( options ) { "use strict"; options = options || {}; options.icons = options.icons || {}; options.timeout = options.timeout || 4000; options.titles = options.titles || { passed: "Passed!", failed: "Failed!" }; options.bodies = options.bodies || { passed: "{{passed}} of {{total}} passed", failed: "{{passed}} passed. {{failed}} failed." }; var renderBody = function( body, details ) { [ "passed", "failed", "total", "runtime" ].forEach( function( type ) { body = body.replace( "{{" + type + "}}", details[ type ] ); } ); return body; }; function generateQueryString( params ) { var key, querystring = "?"; params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params ); for ( key in params ) { if ( params.hasOwnProperty( key ) ) { if ( params[ key ] === undefined ) { continue; } querystring += encodeURIComponent( key ); if ( params[ key ] !== true ) { querystring += "=" + encodeURIComponent( params[ key ] ); } querystring += "&"; } } return location.protocol + "//" + location.host + location.pathname + querystring.slice( 0, -1 ); } if ( window.Notification ) { QUnit.done( function( details ) { var title, _options = {}, notification; if ( window.Notification && QUnit.urlParams.notifications ) { if ( details.failed === 0 ) { title = options.titles.passed; _options.body = renderBody( options.bodies.passed, details ); if ( options.icons.passed ) { _options.icon = options.icons.passed; } } else { title = options.titles.failed; _options.body = renderBody( options.bodies.failed, details ); if ( options.icons.failed ) { _options.icon = options.icons.failed; } } notification = new window.Notification( title, _options ); setTimeout( function() { notification.close(); }, options.timeout ); } } ); QUnit.begin( function() { var toolbar = document.getElementById( "qunit-testrunner-toolbar" ); if ( !toolbar ) { return; } var notification = document.createElement( "input" ), label = document.createElement( "label" ), disableCheckbox = function() { notification.checked = false; notification.disabled = true; label.style.opacity = 0.5; label.title = notification.title = "Note: Notifications have been " + "disabled in this browser."; }; notification.type = "checkbox"; notification.id = "qunit-notifications"; label.innerHTML = "Notifications"; label.for = "qunit-notifications"; label.title = "Show notifications."; if ( window.Notification.permission === "denied" ) { disableCheckbox(); } else if ( QUnit.urlParams.notifications ) { notification.checked = true; } notification.addEventListener( "click", function( event ) { if ( event.target.checked ) { if ( window.Notification.permission === "granted" ) { window.location = generateQueryString( { notifications: true } ); } else if ( window.Notification.permission === "denied" ) { disableCheckbox(); } else { window.Notification.requestPermission( function( permission ) { if ( permission === "denied" ) { disableCheckbox(); } else { window.location = generateQueryString( { notifications: true } ); } } ); } } else { window.location = generateQueryString( { notifications: undefined } ); } }, false ); toolbar.appendChild( notification ); toolbar.appendChild( label ); } ); } }; /* globals QUnit */ (function() { QUnit.config.autostart = false; QUnit.config.urlConfig.push({ id: 'nocontainer', label: 'Hide container'}); QUnit.config.urlConfig.push({ id: 'nolint', label: 'Disable Linting'}); QUnit.config.urlConfig.push({ id: 'dockcontainer', label: 'Dock container'}); QUnit.config.urlConfig.push({ id: 'devmode', label: 'Development mode' }); QUnit.config.testTimeout = QUnit.urlParams.devmode ? null : 60000; //Default Test Timeout 60 Seconds if (QUnit.notifications) { QUnit.notifications({ icons: { passed: '/assets/passed.png', failed: '/assets/failed.png' } }); } })(); define('ember-cli-qunit', ['exports', 'qunit', 'ember-qunit', 'ember-cli-test-loader/test-support/index'], function (exports, _qunit, _emberQunit, _index) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.TestLoader = undefined; exports.setupTestContainer = setupTestContainer; exports.loadTests = loadTests; exports.startTests = startTests; exports.setupTestAdapter = setupTestAdapter; exports.start = start; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (0, _index.addModuleExcludeMatcher)(function (moduleName) { return _qunit.default.urlParams.nolint && moduleName.match(/\.(jshint|lint-test)$/); }); (0, _index.addModuleIncludeMatcher)(function (moduleName) { return moduleName.match(/\.jshint$/); }); var moduleLoadFailures = []; _qunit.default.done(function () { if (moduleLoadFailures.length) { throw new Error('\n' + moduleLoadFailures.join('\n')); } }); var TestLoader = exports.TestLoader = function (_AbstractTestLoader) { _inherits(TestLoader, _AbstractTestLoader); function TestLoader() { _classCallCheck(this, TestLoader); return _possibleConstructorReturn(this, (TestLoader.__proto__ || Object.getPrototypeOf(TestLoader)).apply(this, arguments)); } _createClass(TestLoader, [{ key: 'moduleLoadFailure', value: function moduleLoadFailure(moduleName, error) { moduleLoadFailures.push(error); _qunit.default.module('TestLoader Failures'); _qunit.default.test(moduleName + ': could not be loaded', function () { throw error; }); } }]); return TestLoader; }(_index.default); /** Uses current URL configuration to setup the test container. * If `?nocontainer` is set, the test container will be hidden. * If `?dockcontainer` or `?devmode` are set the test container will be absolutely positioned. * If `?devmode` is set, the test container will be made full screen. @method setupTestContainer */ function setupTestContainer() { var testContainer = document.getElementById('ember-testing-container'); if (!testContainer) { return; } var params = _qunit.default.urlParams; var containerVisibility = params.nocontainer ? 'hidden' : 'visible'; var containerPosition = params.dockcontainer || params.devmode ? 'absolute' : 'relative'; if (params.devmode) { testContainer.className = ' full-screen'; } testContainer.style.visibility = containerVisibility; testContainer.style.position = containerPosition; } /** Load tests following the default patterns: * The module name ends with `-test` * The module name ends with `.jshint` Excludes tests that match the following patterns when `?nolint` URL param is set: * The module name ends with `.jshint` * The module name ends with `-lint-test` @method loadTests */ function loadTests() { new TestLoader().loadModules(); } /** Instruct QUnit to start the tests. @method startTests */ function startTests() { _qunit.default.start(); } /** Sets up the `Ember.Test` adapter for usage with QUnit 2.x. @method setupTestAdapter */ function setupTestAdapter() { Ember.Test.adapter = _emberQunit.QUnitAdapter.create(); } /** @method start @param {Object} [options] Options to be used for enabling/disabling behaviors @param {Boolean} [options.loadTests] If `false` tests will not be loaded automatically. @param {Boolean} [options.setupTestContainer] If `false` the test container will not be setup based on `devmode`, `dockcontainer`, or `nocontainer` URL params. @param {Boolean} [options.startTests] If `false` tests will not be automatically started (you must run `QUnit.start()` to kick them off). @param {Boolean} [options.setupTestAdapter] If `false` the default Ember.Test adapter will not be updated. */ function start() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (options.loadTests !== false) { loadTests(); } if (options.setupTestContainer !== false) { setupTestContainer(); } if (options.setupTestAdapter !== false) { setupTestAdapter(); } if (options.startTests !== false) { startTests(); } } }); define('ember-cli-test-loader/test-support/index', ['exports'], function (exports) { /* globals requirejs, require */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addModuleIncludeMatcher = addModuleIncludeMatcher; exports.addModuleExcludeMatcher = addModuleExcludeMatcher; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var moduleIncludeMatchers = []; var moduleExcludeMatchers = []; function addModuleIncludeMatcher(fn) { moduleIncludeMatchers.push(fn); } function addModuleExcludeMatcher(fn) { moduleExcludeMatchers.push(fn); } function checkMatchers(matchers, moduleName) { return matchers.some(function (matcher) { return matcher(moduleName); }); } var TestLoader = function () { _createClass(TestLoader, null, [{ key: 'load', value: function load() { new TestLoader().loadModules(); } }]); function TestLoader() { _classCallCheck(this, TestLoader); this._didLogMissingUnsee = false; } _createClass(TestLoader, [{ key: 'shouldLoadModule', value: function shouldLoadModule(moduleName) { return moduleName.match(/[-_]test$/); } }, { key: 'listModules', value: function listModules() { return Object.keys(requirejs.entries); } }, { key: 'listTestModules', value: function listTestModules() { var moduleNames = this.listModules(); var testModules = []; var moduleName = void 0; for (var i = 0; i < moduleNames.length; i++) { moduleName = moduleNames[i]; if (checkMatchers(moduleExcludeMatchers, moduleName)) { continue; } if (checkMatchers(moduleIncludeMatchers, moduleName) || this.shouldLoadModule(moduleName)) { testModules.push(moduleName); } } return testModules; } }, { key: 'loadModules', value: function loadModules() { var testModules = this.listTestModules(); var testModule = void 0; for (var i = 0; i < testModules.length; i++) { testModule = testModules[i]; this.require(testModule); this.unsee(testModule); } } }, { key: 'require', value: function (_require) { function require(_x) { return _require.apply(this, arguments); } require.toString = function () { return _require.toString(); }; return require; }(function (moduleName) { try { require(moduleName); } catch (e) { this.moduleLoadFailure(moduleName, e); } }) }, { key: 'unsee', value: function unsee(moduleName) { if (typeof require.unsee === 'function') { require.unsee(moduleName); } else if (!this._didLogMissingUnsee) { this._didLogMissingUnsee = true; if (typeof console !== 'undefined') { console.warn('unable to require.unsee, please upgrade loader.js to >= v3.3.0'); } } } }, { key: 'moduleLoadFailure', value: function moduleLoadFailure(moduleName, error) { console.error('Error loading: ' + moduleName, error.stack); } }]); return TestLoader; }(); exports.default = TestLoader; ; }); define('ember-qunit', ['exports', 'qunit', 'ember-qunit/module-for', 'ember-qunit/module-for-component', 'ember-qunit/module-for-model', 'ember-qunit/adapter', 'ember-test-helpers'], function (exports, _qunit, _moduleFor, _moduleForComponent, _moduleForModel, _adapter, _emberTestHelpers) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.QUnitAdapter = exports.setResolver = exports.moduleForModel = exports.moduleForComponent = exports.moduleFor = exports.todo = exports.only = exports.skip = exports.test = exports.module = undefined; Object.defineProperty(exports, 'module', { enumerable: true, get: function () { return _qunit.module; } }); Object.defineProperty(exports, 'test', { enumerable: true, get: function () { return _qunit.test; } }); Object.defineProperty(exports, 'skip', { enumerable: true, get: function () { return _qunit.skip; } }); Object.defineProperty(exports, 'only', { enumerable: true, get: function () { return _qunit.only; } }); Object.defineProperty(exports, 'todo', { enumerable: true, get: function () { return _qunit.todo; } }); exports.moduleFor = _moduleFor.default; exports.moduleForComponent = _moduleForComponent.default; exports.moduleForModel = _moduleForModel.default; exports.setResolver = _emberTestHelpers.setResolver; exports.QUnitAdapter = _adapter.default; }); define('ember-qunit/adapter', ['exports', 'qunit'], function (exports, _qunit) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function unhandledRejectionAssertion(current, error) { var message = void 0, source = void 0; if ((typeof error === 'undefined' ? 'undefined' : _typeof(error)) === 'object' && error !== null) { message = error.message; source = error.stack; } else if (typeof error === "string") { message = error; source = "unknown source"; } else { message = "unhandledRejection occured, but it had no message"; source = "unknown source"; } current.pushResult({ result: false, actual: false, expected: true, message: message, source: source }); } exports.default = Ember.Test.Adapter.extend({ init: function init() { this.doneCallbacks = []; }, asyncStart: function asyncStart() { this.doneCallbacks.push(_qunit.default.config.current ? _qunit.default.config.current.assert.async() : null); }, asyncEnd: function asyncEnd() { var done = this.doneCallbacks.pop(); // This can be null if asyncStart() was called outside of a test if (done) { done(); } }, exception: function exception(error) { unhandledRejectionAssertion(_qunit.default.config.current, error); } }); }); define('ember-qunit/module-for-component', ['exports', 'ember-qunit/qunit-module', 'ember-test-helpers'], function (exports, _qunitModule, _emberTestHelpers) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = moduleForComponent; function moduleForComponent(name, description, callbacks) { (0, _qunitModule.createModule)(_emberTestHelpers.TestModuleForComponent, name, description, callbacks); } }); define('ember-qunit/module-for-model', ['exports', 'ember-qunit/qunit-module', 'ember-test-helpers'], function (exports, _qunitModule, _emberTestHelpers) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = moduleForModel; function moduleForModel(name, description, callbacks) { (0, _qunitModule.createModule)(_emberTestHelpers.TestModuleForModel, name, description, callbacks); } }); define('ember-qunit/module-for', ['exports', 'ember-qunit/qunit-module', 'ember-test-helpers'], function (exports, _qunitModule, _emberTestHelpers) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = moduleFor; function moduleFor(name, description, callbacks) { (0, _qunitModule.createModule)(_emberTestHelpers.TestModule, name, description, callbacks); } }); define('ember-qunit/qunit-module', ['exports', 'qunit'], function (exports, _qunit) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.createModule = createModule; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function noop() {} function callbackFor(name, callbacks) { if ((typeof callbacks === 'undefined' ? 'undefined' : _typeof(callbacks)) !== 'object') { return noop; } if (!callbacks) { return noop; } var callback = noop; if (callbacks[name]) { callback = callbacks[name]; delete callbacks[name]; } return callback; } function createModule(Constructor, name, description, callbacks) { if (!callbacks && (typeof description === 'undefined' ? 'undefined' : _typeof(description)) === 'object') { callbacks = description; description = name; } var _before = callbackFor('before', callbacks); var _beforeEach = callbackFor('beforeEach', callbacks); var _afterEach = callbackFor('afterEach', callbacks); var _after = callbackFor('after', callbacks); var module; var moduleName = typeof description === 'string' ? description : name; (0, _qunit.module)(moduleName, { before: function before() { // storing this in closure scope to avoid exposing these // private internals to the test context module = new Constructor(name, description, callbacks); return _before.apply(this, arguments); }, beforeEach: function beforeEach() { var _module, _this = this, _arguments = arguments; // provide the test context to the underlying module module.setContext(this); return (_module = module).setup.apply(_module, arguments).then(function () { return _beforeEach.apply(_this, _arguments); }); }, afterEach: function afterEach() { var _arguments2 = arguments; var result = _afterEach.apply(this, arguments); return Ember.RSVP.resolve(result).then(function () { var _module2; return (_module2 = module).teardown.apply(_module2, _arguments2); }); }, after: function after() { try { return _after.apply(this, arguments); } finally { _after = _afterEach = _before = _beforeEach = callbacks = module = null; } } }); } }); define('ember-test-helpers', ['exports', 'ember-test-helpers/test-module', 'ember-test-helpers/test-module-for-acceptance', 'ember-test-helpers/test-module-for-integration', 'ember-test-helpers/test-module-for-component', 'ember-test-helpers/test-module-for-model', 'ember-test-helpers/test-context', 'ember-test-helpers/test-resolver'], function (exports, _testModule, _testModuleForAcceptance, _testModuleForIntegration, _testModuleForComponent, _testModuleForModel, _testContext, _testResolver) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.setResolver = exports.unsetContext = exports.setContext = exports.getContext = exports.TestModuleForModel = exports.TestModuleForComponent = exports.TestModuleForIntegration = exports.TestModuleForAcceptance = exports.TestModule = undefined; Ember.testing = true; exports.TestModule = _testModule.default; exports.TestModuleForAcceptance = _testModuleForAcceptance.default; exports.TestModuleForIntegration = _testModuleForIntegration.default; exports.TestModuleForComponent = _testModuleForComponent.default; exports.TestModuleForModel = _testModuleForModel.default; exports.getContext = _testContext.getContext; exports.setContext = _testContext.setContext; exports.unsetContext = _testContext.unsetContext; exports.setResolver = _testResolver.setResolver; }); define('ember-test-helpers/-legacy-overrides', ['exports', 'ember-test-helpers/has-ember-version'], function (exports, _hasEmberVersion) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.preGlimmerSetupIntegrationForComponent = preGlimmerSetupIntegrationForComponent; function preGlimmerSetupIntegrationForComponent() { var module = this; var context = this.context; this.actionHooks = {}; context.dispatcher = this.container.lookup('event_dispatcher:main') || Ember.EventDispatcher.create(); context.dispatcher.setup({}, '#ember-testing'); context.actions = module.actionHooks; (this.registry || this.container).register('component:-test-holder', Ember.Component.extend()); context.render = function (template) { // in case `this.render` is called twice, make sure to teardown the first invocation module.teardownComponent(); if (!template) { throw new Error("in a component integration test you must pass a template to `render()`"); } if (Ember.isArray(template)) { template = template.join(''); } if (typeof template === 'string') { template = Ember.Handlebars.compile(template); } module.component = module.container.lookupFactory('component:-test-holder').create({ layout: template }); module.component.set('context', context); module.component.set('controller', context); Ember.run(function () { module.component.appendTo('#ember-testing'); }); context._element = module.component.element; }; context.$ = function () { return module.component.$.apply(module.component, arguments); }; context.set = function (key, value) { var ret = Ember.run(function () { return Ember.set(context, key, value); }); if ((0, _hasEmberVersion.default)(2, 0)) { return ret; } }; context.setProperties = function (hash) { var ret = Ember.run(function () { return Ember.setProperties(context, hash); }); if ((0, _hasEmberVersion.default)(2, 0)) { return ret; } }; context.get = function (key) { return Ember.get(context, key); }; context.getProperties = function () { var args = Array.prototype.slice.call(arguments); return Ember.getProperties(context, args); }; context.on = function (actionName, handler) { module.actionHooks[actionName] = handler; }; context.send = function (actionName) { var hook = module.actionHooks[actionName]; if (!hook) { throw new Error("integration testing template received unexpected action " + actionName); } hook.apply(module, Array.prototype.slice.call(arguments, 1)); }; context.clearRender = function () { module.teardownComponent(); }; } }); define('ember-test-helpers/abstract-test-module', ['exports', 'ember-test-helpers/wait', 'ember-test-helpers/test-context'], function (exports, _wait, _testContext) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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; }; }(); // calling this `merge` here because we cannot // actually assume it is like `Object.assign` // with > 2 args var merge = Ember.assign || Ember.merge; var _class = function () { function _class(name, options) { _classCallCheck(this, _class); this.context = undefined; this.name = name; this.callbacks = options || {}; this.initSetupSteps(); this.initTeardownSteps(); } _createClass(_class, [{ key: 'setup', value: function setup(assert) { var _this = this; return this.invokeSteps(this.setupSteps, this, assert).then(function () { _this.contextualizeCallbacks(); return _this.invokeSteps(_this.contextualizedSetupSteps, _this.context, assert); }); } }, { key: 'teardown', value: function teardown(assert) { var _this2 = this; return this.invokeSteps(this.contextualizedTeardownSteps, this.context, assert).then(function () { return _this2.invokeSteps(_this2.teardownSteps, _this2, assert); }).then(function () { _this2.cache = null; _this2.cachedCalls = null; }); } }, { key: 'initSetupSteps', value: function initSetupSteps() { this.setupSteps = []; this.contextualizedSetupSteps = []; if (this.callbacks.beforeSetup) { this.setupSteps.push(this.callbacks.beforeSetup); delete this.callbacks.beforeSetup; } this.setupSteps.push(this.setupContext); this.setupSteps.push(this.setupTestElements); this.setupSteps.push(this.setupAJAXListeners); if (this.callbacks.setup) { this.contextualizedSetupSteps.push(this.callbacks.setup); delete this.callbacks.setup; } } }, { key: 'invokeSteps', value: function invokeSteps(steps, context, assert) { steps = steps.slice(); function nextStep() { var step = steps.shift(); if (step) { // guard against exceptions, for example missing components referenced from needs. return new Ember.RSVP.Promise(function (resolve) { resolve(step.call(context, assert)); }).then(nextStep); } else { return Ember.RSVP.resolve(); } } return nextStep(); } }, { key: 'contextualizeCallbacks', value: function contextualizeCallbacks() {} }, { key: 'initTeardownSteps', value: function initTeardownSteps() { this.teardownSteps = []; this.contextualizedTeardownSteps = []; if (this.callbacks.teardown) { this.contextualizedTeardownSteps.push(this.callbacks.teardown); delete this.callbacks.teardown; } this.teardownSteps.push(this.teardownContext); this.teardownSteps.push(this.teardownTestElements); this.teardownSteps.push(this.teardownAJAXListeners); if (this.callbacks.afterTeardown) { this.teardownSteps.push(this.callbacks.afterTeardown); delete this.callbacks.afterTeardown; } } }, { key: 'setupTestElements', value: function setupTestElements() { var testEl = document.querySelector('#ember-testing'); if (!testEl) { var element = document.createElement('div'); element.setAttribute('id', 'ember-testing'); document.body.appendChild(element); this.fixtureResetValue = ''; } else { this.fixtureResetValue = testEl.innerHTML; } } }, { key: 'setupContext', value: function setupContext(options) { var context = this.getContext(); merge(context, { dispatcher: null, inject: {} }); merge(context, options); this.setToString(); (0, _testContext.setContext)(context); this.context = context; } }, { key: 'setContext', value: function setContext(context) { this.context = context; } }, { key: 'getContext', value: function getContext() { if (this.context) { return this.context; } return this.context = (0, _testContext.getContext)() || {}; } }, { key: 'setToString', value: function setToString() { var _this3 = this; this.context.toString = function () { if (_this3.subjectName) { return 'test context for: ' + _this3.subjectName; } if (_this3.name) { return 'test context for: ' + _this3.name; } }; } }, { key: 'setupAJAXListeners', value: function setupAJAXListeners() { (0, _wait._setupAJAXHooks)(); } }, { key: 'teardownAJAXListeners', value: function teardownAJAXListeners() { (0, _wait._teardownAJAXHooks)(); } }, { key: 'teardownTestElements', value: function teardownTestElements() { document.getElementById('ember-testing').innerHTML = this.fixtureResetValue; // Ember 2.0.0 removed Ember.View as public API, so only do this when // Ember.View is present if (Ember.View && Ember.View.views) { Ember.View.views = {}; } } }, { key: 'teardownContext', value: function teardownContext() { var context = this.context; this.context = undefined; (0, _testContext.unsetContext)(); if (context && context.dispatcher && !context.dispatcher.isDestroyed) { Ember.run(function () { context.dispatcher.destroy(); }); } } }]); return _class; }(); exports.default = _class; }); define('ember-test-helpers/build-registry', ['exports', 'require'], function (exports, _require2) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (resolver) { var fallbackRegistry, registry, container; var namespace = Ember.Object.create({ Resolver: { create: function create() { return resolver; } } }); function register(name, factory) { var thingToRegisterWith = registry || container; if (!(container.factoryFor ? container.factoryFor(name) : container.lookupFactory(name))) { thingToRegisterWith.register(name, factory); } } if (Ember.Application.buildRegistry) { fallbackRegistry = Ember.Application.buildRegistry(namespace); fallbackRegistry.register('component-lookup:main', Ember.ComponentLookup); registry = new Ember.Registry({ fallback: fallbackRegistry }); if (Ember.ApplicationInstance && Ember.ApplicationInstance.setupRegistry) { Ember.ApplicationInstance.setupRegistry(registry); } // these properties are set on the fallback registry by `buildRegistry` // and on the primary registry within the ApplicationInstance constructor // but we need to manually recreate them since ApplicationInstance's are not // exposed externally registry.normalizeFullName = fallbackRegistry.normalizeFullName; registry.makeToString = fallbackRegistry.makeToString; registry.describe = fallbackRegistry.describe; var owner = Owner.create({ __registry__: registry, __container__: null }); container = registry.container({ owner: owner }); owner.__container__ = container; exposeRegistryMethodsWithoutDeprecations(container); } else { container = Ember.Application.buildContainer(namespace); container.register('component-lookup:main', Ember.ComponentLookup); } // Ember 1.10.0 did not properly add `view:toplevel` or `view:default` // to the registry in Ember.Application.buildRegistry :( // // Ember 2.0.0 removed Ember.View as public API, so only do this when // Ember.View is present if (Ember.View) { register('view:toplevel', Ember.View.extend()); } // Ember 2.0.0 removed Ember._MetamorphView from the Ember global, so only // do this when present if (Ember._MetamorphView) { register('view:default', Ember._MetamorphView); } var globalContext = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) === 'object' && global || self; if (requirejs.entries['ember-data/setup-container']) { // ember-data is a proper ember-cli addon since 2.3; if no 'import // 'ember-data'' is present somewhere in the tests, there is also no `DS` // available on the globalContext and hence ember-data wouldn't be setup // correctly for the tests; that's why we import and call setupContainer // here; also see https://github.com/emberjs/data/issues/4071 for context var setupContainer = (0, _require2.default)('ember-data/setup-container')['default']; setupContainer(registry || container); } else if (globalContext.DS) { var DS = globalContext.DS; if (DS._setupContainer) { DS._setupContainer(registry || container); } else { register('transform:boolean', DS.BooleanTransform); register('transform:date', DS.DateTransform); register('transform:number', DS.NumberTransform); register('transform:string', DS.StringTransform); register('serializer:-default', DS.JSONSerializer); register('serializer:-rest', DS.RESTSerializer); register('adapter:-rest', DS.RESTAdapter); } } return { registry: registry, container: container }; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function exposeRegistryMethodsWithoutDeprecations(container) { var methods = ['register', 'unregister', 'resolve', 'normalize', 'typeInjection', 'injection', 'factoryInjection', 'factoryTypeInjection', 'has', 'options', 'optionsForType']; function exposeRegistryMethod(container, method) { if (method in container) { container[method] = function () { return container._registry[method].apply(container._registry, arguments); }; } } for (var i = 0, l = methods.length; i < l; i++) { exposeRegistryMethod(container, methods[i]); } } var Owner = function () { if (Ember._RegistryProxyMixin && Ember._ContainerProxyMixin) { return Ember.Object.extend(Ember._RegistryProxyMixin, Ember._ContainerProxyMixin); } return Ember.Object.extend(); }(); }); define('ember-test-helpers/has-ember-version', ['exports'], function (exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = hasEmberVersion; function hasEmberVersion(major, minor) { var numbers = Ember.VERSION.split('-')[0].split('.'); var actualMajor = parseInt(numbers[0], 10); var actualMinor = parseInt(numbers[1], 10); return actualMajor > major || actualMajor === major && actualMinor >= minor; } }); define("ember-test-helpers/test-context", ["exports"], function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setContext = setContext; exports.getContext = getContext; exports.unsetContext = unsetContext; var __test_context__; function setContext(context) { __test_context__ = context; } function getContext() { return __test_context__; } function unsetContext() { __test_context__ = undefined; } }); define('ember-test-helpers/test-module-for-acceptance', ['exports', 'ember-test-helpers/abstract-test-module', 'ember-test-helpers/test-context'], function (exports, _abstractTestModule, _testContext) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _class = function (_AbstractTestModule) { _inherits(_class, _AbstractTestModule); function _class() { _classCallCheck(this, _class); return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments)); } _createClass(_class, [{ key: 'setupContext', value: function setupContext() { _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'setupContext', this).call(this, { application: this.createApplication() }); } }, { key: 'teardownContext', value: function teardownContext() { Ember.run(function () { (0, _testContext.getContext)().application.destroy(); }); _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'teardownContext', this).call(this); } }, { key: 'createApplication', value: function createApplication() { var _callbacks = this.callbacks, Application = _callbacks.Application, config = _callbacks.config; var application = void 0; Ember.run(function () { application = Application.create(config); application.setupForTesting(); application.injectTestHelpers(); }); return application; } }]); return _class; }(_abstractTestModule.default); exports.default = _class; }); define('ember-test-helpers/test-module-for-component', ['exports', 'ember-test-helpers/test-module', 'ember-test-helpers/has-ember-version', 'ember-test-helpers/-legacy-overrides'], function (exports, _testModule, _hasEmberVersion, _legacyOverrides) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.setupComponentIntegrationTest = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ACTION_KEY = void 0; if ((0, _hasEmberVersion.default)(2, 0)) { ACTION_KEY = 'actions'; } else { ACTION_KEY = '_actions'; } var isPreGlimmer = !(0, _hasEmberVersion.default)(1, 13); var getOwner = Ember.getOwner; var _class = function (_TestModule) { _inherits(_class, _TestModule); function _class(componentName, description, callbacks) { _classCallCheck(this, _class); // Allow `description` to be omitted if (!callbacks && (typeof description === 'undefined' ? 'undefined' : _typeof(description)) === 'object') { callbacks = description; description = null; } else if (!callbacks) { callbacks = {}; } var integrationOption = callbacks.integration; var hasNeeds = Array.isArray(callbacks.needs); var _this2 = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this, 'component:' + componentName, description, callbacks)); _this2.componentName = componentName; if (hasNeeds || callbacks.unit || integrationOption === false) { _this2.isUnitTest = true; } else if (integrationOption) { _this2.isUnitTest = false; } else { Ember.deprecate("the component:" + componentName + " test module is implicitly running in unit test mode, " + "which will change to integration test mode by default in an upcoming version of " + "ember-test-helpers. Add `unit: true` or a `needs:[]` list to explicitly opt in to unit " + "test mode.", false, { id: 'ember-test-helpers.test-module-for-component.test-type', until: '0.6.0' }); _this2.isUnitTest = true; } if (!_this2.isUnitTest && !_this2.isLegacy) { callbacks.integration = true; } if (_this2.isUnitTest || _this2.isLegacy) { _this2.setupSteps.push(_this2.setupComponentUnitTest); } else { _this2.callbacks.subject = function () { throw new Error("component integration tests do not support `subject()`. Instead, render the component as if it were HTML: `this.render('<my-component foo=true>');`. For more information, read: http://guides.emberjs.com/v2.2.0/testing/testing-components/"); }; _this2.setupSteps.push(_this2.setupComponentIntegrationTest); _this2.teardownSteps.unshift(_this2.teardownComponent); } if (Ember.View && Ember.View.views) { _this2.setupSteps.push(_this2._aliasViewRegistry); _this2.teardownSteps.unshift(_this2._resetViewRegistry); } return _this2; } _createClass(_class, [{ key: 'initIntegration', value: function initIntegration(options) { this.isLegacy = options.integration === 'legacy'; this.isIntegration = options.integration !== 'legacy'; } }, { key: '_aliasViewRegistry', value: function _aliasViewRegistry() { this._originalGlobalViewRegistry = Ember.View.views; var viewRegistry = this.container.lookup('-view-registry:main'); if (viewRegistry) { Ember.View.views = viewRegistry; } } }, { key: '_resetViewRegistry', value: function _resetViewRegistry() { Ember.View.views = this._originalGlobalViewRegistry; } }, { key: 'setupComponentUnitTest', value: function setupComponentUnitTest() { var _this = this; var resolver = this.resolver; var context = this.context; var layoutName = 'template:components/' + this.componentName; var layout = resolver.resolve(layoutName); var thingToRegisterWith = this.registry || this.container; if (layout) { thingToRegisterWith.register(layoutName, layout); thingToRegisterWith.injection(this.subjectName, 'layout', layoutName); } context.dispatcher = this.container.lookup('event_dispatcher:main') || Ember.EventDispatcher.create(); context.dispatcher.setup({}, '#ember-testing'); context._element = null; this.callbacks.render = function () { var subject; Ember.run(function () { subject = context.subject(); subject.appendTo('#ember-testing'); }); context._element = subject.element; _this.teardownSteps.unshift(function () { Ember.run(function () { Ember.tryInvoke(subject, 'destroy'); }); }); }; this.callbacks.append = function () { Ember.deprecate('this.append() is deprecated. Please use this.render() or this.$() instead.', false, { id: 'ember-test-helpers.test-module-for-component.append', until: '0.6.0' }); return context.$(); }; context.$ = function () { this.render(); var subject = this.subject(); return subject.$.apply(subject, arguments); }; } }, { key: 'setupComponentIntegrationTest', value: function setupComponentIntegrationTest() { if (isPreGlimmer) { return _legacyOverrides.preGlimmerSetupIntegrationForComponent.apply(this, arguments); } else { return _setupComponentIntegrationTest.apply(this, arguments); } } }, { key: 'setupContext', value: function setupContext() { _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'setupContext', this).call(this); // only setup the injection if we are running against a version // of Ember that has `-view-registry:main` (Ember >= 1.12) if (this.container.factoryFor ? this.container.factoryFor('-view-registry:main') : this.container.lookupFactory('-view-registry:main')) { (this.registry || this.container).injection('component', '_viewRegistry', '-view-registry:main'); } if (!this.isUnitTest && !this.isLegacy) { this.context.factory = function () {}; } } }, { key: 'teardownComponent', value: function teardownComponent() { var component = this.component; if (component) { Ember.run(component, 'destroy'); this.component = null; } } }]); return _class; }(_testModule.default); exports.default = _class; function _setupComponentIntegrationTest() { var module = this; var context = this.context; this.actionHooks = context[ACTION_KEY] = {}; context.dispatcher = this.container.lookup('event_dispatcher:main') || Ember.EventDispatcher.create(); context.dispatcher.setup({}, '#ember-testing'); var hasRendered = false; var OutletView = module.container.factoryFor ? module.container.factoryFor('view:-outlet') : module.container.lookupFactory('view:-outlet'); var OutletTemplate = module.container.lookup('template:-outlet'); var toplevelView = module.component = OutletView.create(); var hasOutletTemplate = !!OutletTemplate; var outletState = { render: { owner: getOwner ? getOwner(module.container) : undefined, into: undefined, outlet: 'main', name: 'application', controller: module.context, ViewClass: undefined, template: OutletTemplate }, outlets: {} }; var element = document.getElementById('ember-testing'); var templateId = 0; if (hasOutletTemplate) { Ember.run(function () { toplevelView.setOutletState(outletState); }); } context.render = function (template) { if (!template) { throw new Error("in a component integration test you must pass a template to `render()`"); } if (Ember.isArray(template)) { template = template.join(''); } if (typeof template === 'string') { template = Ember.Handlebars.compile(template); } var templateFullName = 'template:-undertest-' + ++templateId; this.registry.register(templateFullName, template); var stateToRender = { owner: getOwner ? getOwner(module.container) : undefined, into: undefined, outlet: 'main', name: 'index', controller: module.context, ViewClass: undefined, template: module.container.lookup(templateFullName), outlets: {} }; if (hasOutletTemplate) { stateToRender.name = 'index'; outletState.outlets.main = { render: stateToRender, outlets: {} }; } else { stateToRender.name = 'application'; outletState = { render: stateToRender, outlets: {} }; } Ember.run(function () { toplevelView.setOutletState(outletState); }); if (!hasRendered) { Ember.run(module.component, 'appendTo', '#ember-testing'); hasRendered = true; } // ensure the element is based on the wrapping toplevel view // Ember still wraps the main application template with a // normal tagged view context._element = element = document.querySelector('#ember-testing > .ember-view'); }; context.$ = function (selector) { // emulates Ember internal behavor of `this.$` in a component // https://github.com/emberjs/ember.js/blob/v2.5.1/packages/ember-views/lib/views/states/has_element.js#L18 return selector ? Ember.$(selector, element) : Ember.$(element); }; context.set = function (key, value) { var ret = Ember.run(function () { return Ember.set(context, key, value); }); if ((0, _hasEmberVersion.default)(2, 0)) { return ret; } }; context.setProperties = function (hash) { var ret = Ember.run(function () { return Ember.setProperties(context, hash); }); if ((0, _hasEmberVersion.default)(2, 0)) { return ret; } }; context.get = function (key) { return Ember.get(context, key); }; context.getProperties = function () { var args = Array.prototype.slice.call(arguments); return Ember.getProperties(context, args); }; context.on = function (actionName, handler) { module.actionHooks[actionName] = handler; }; context.send = function (actionName) { var hook = module.actionHooks[actionName]; if (!hook) { throw new Error("integration testing template received unexpected action " + actionName); } hook.apply(module.context, Array.prototype.slice.call(arguments, 1)); }; context.clearRender = function () { Ember.run(function () { toplevelView.setOutletState({ render: { owner: module.container, into: undefined, outlet: 'main', name: 'application', controller: module.context, ViewClass: undefined, template: undefined }, outlets: {} }); }); }; } exports.setupComponentIntegrationTest = _setupComponentIntegrationTest; }); define('ember-test-helpers/test-module-for-integration', ['exports', 'ember-test-helpers/abstract-test-module', 'ember-test-helpers/test-resolver', 'ember-test-helpers/build-registry', 'ember-test-helpers/has-ember-version', 'ember-test-helpers/-legacy-overrides', 'ember-test-helpers/test-module-for-component'], function (exports, _abstractTestModule, _testResolver, _buildRegistry, _hasEmberVersion, _legacyOverrides, _testModuleForComponent) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var isPreGlimmer = !(0, _hasEmberVersion.default)(1, 13); var _class = function (_AbstractTestModule) { _inherits(_class, _AbstractTestModule); function _class() { _classCallCheck(this, _class); var _this2 = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments)); _this2.resolver = _this2.callbacks.resolver || (0, _testResolver.getResolver)(); return _this2; } _createClass(_class, [{ key: 'initSetupSteps', value: function initSetupSteps() { this.setupSteps = []; this.contextualizedSetupSteps = []; if (this.callbacks.beforeSetup) { this.setupSteps.push(this.callbacks.beforeSetup); delete this.callbacks.beforeSetup; } this.setupSteps.push(this.setupContainer); this.setupSteps.push(this.setupContext); this.setupSteps.push(this.setupTestElements); this.setupSteps.push(this.setupAJAXListeners); this.setupSteps.push(this.setupComponentIntegrationTest); if (Ember.View && Ember.View.views) { this.setupSteps.push(this._aliasViewRegistry); } if (this.callbacks.setup) { this.contextualizedSetupSteps.push(this.callbacks.setup); delete this.callbacks.setup; } } }, { key: 'initTeardownSteps', value: function initTeardownSteps() { this.teardownSteps = []; this.contextualizedTeardownSteps = []; if (this.callbacks.teardown) { this.contextualizedTeardownSteps.push(this.callbacks.teardown); delete this.callbacks.teardown; } this.teardownSteps.push(this.teardownContainer); this.teardownSteps.push(this.teardownContext); this.teardownSteps.push(this.teardownAJAXListeners); this.teardownSteps.push(this.teardownComponent); if (Ember.View && Ember.View.views) { this.teardownSteps.push(this._resetViewRegistry); } this.teardownSteps.push(this.teardownTestElements); if (this.callbacks.afterTeardown) { this.teardownSteps.push(this.callbacks.afterTeardown); delete this.callbacks.afterTeardown; } } }, { key: 'setupContainer', value: function setupContainer() { var resolver = this.resolver; var items = (0, _buildRegistry.default)(resolver); this.container = items.container; this.registry = items.registry; if ((0, _hasEmberVersion.default)(1, 13)) { var thingToRegisterWith = this.registry || this.container; var router = resolver.resolve('router:main'); router = router || Ember.Router.extend(); thingToRegisterWith.register('router:main', router); } } }, { key: 'setupContext', value: function setupContext() { var subjectName = this.subjectName; var container = this.container; var factory = function factory() { return container.factoryFor ? container.factoryFor(subjectName) : container.lookupFactory(subjectName); }; _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'setupContext', this).call(this, { container: this.container, registry: this.registry, factory: factory, register: function register() { var target = this.registry || this.container; return target.register.apply(target, arguments); } }); var context = this.context; if (Ember.setOwner) { Ember.setOwner(context, this.container.owner); } if (Ember.inject) { var keys = (Object.keys || Ember.keys)(Ember.inject); keys.forEach(function (typeName) { context.inject[typeName] = function (name, opts) { var alias = opts && opts.as || name; Ember.run(function () { Ember.set(context, alias, context.container.lookup(typeName + ':' + name)); }); }; }); } // only setup the injection if we are running against a version // of Ember that has `-view-registry:main` (Ember >= 1.12) if (this.container.factoryFor ? this.container.factoryFor('-view-registry:main') : this.container.lookupFactory('-view-registry:main')) { (this.registry || this.container).injection('component', '_viewRegistry', '-view-registry:main'); } } }, { key: 'setupComponentIntegrationTest', value: function setupComponentIntegrationTest() { if (isPreGlimmer) { return _legacyOverrides.preGlimmerSetupIntegrationForComponent.apply(this, arguments); } else { return _testModuleForComponent.setupComponentIntegrationTest.apply(this, arguments); } } }, { key: 'teardownComponent', value: function teardownComponent() { var component = this.component; if (component) { Ember.run(function () { component.destroy(); }); } } }, { key: 'teardownContainer', value: function teardownContainer() { var container = this.container; Ember.run(function () { container.destroy(); }); } }, { key: 'contextualizeCallbacks', value: function contextualizeCallbacks() { var callbacks = this.callbacks; var context = this.context; this.cache = this.cache || {}; this.cachedCalls = this.cachedCalls || {}; var keys = (Object.keys || Ember.keys)(callbacks); var keysLength = keys.length; if (keysLength) { for (var i = 0; i < keysLength; i++) { this._contextualizeCallback(context, keys[i], context); } } } }, { key: '_contextualizeCallback', value: function _contextualizeCallback(context, key, callbackContext) { var _this = this; var callbacks = this.callbacks; var factory = context.factory; context[key] = function (options) { if (_this.cachedCalls[key]) { return _this.cache[key]; } var result = callbacks[key].call(callbackContext, options, factory()); _this.cache[key] = result; _this.cachedCalls[key] = true; return result; }; } }, { key: '_aliasViewRegistry', value: function _aliasViewRegistry() { this._originalGlobalViewRegistry = Ember.View.views; var viewRegistry = this.container.lookup('-view-registry:main'); if (viewRegistry) { Ember.View.views = viewRegistry; } } }, { key: '_resetViewRegistry', value: function _resetViewRegistry() { Ember.View.views = this._originalGlobalViewRegistry; } }]); return _class; }(_abstractTestModule.default); exports.default = _class; }); define('ember-test-helpers/test-module-for-model', ['exports', 'require', 'ember-test-helpers/test-module'], function (exports, _require2, _testModule) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _class = function (_TestModule) { _inherits(_class, _TestModule); function _class(modelName, description, callbacks) { _classCallCheck(this, _class); var _this = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this, 'model:' + modelName, description, callbacks)); _this.modelName = modelName; _this.setupSteps.push(_this.setupModel); return _this; } _createClass(_class, [{ key: 'setupModel', value: function setupModel() { var container = this.container; var defaultSubject = this.defaultSubject; var callbacks = this.callbacks; var modelName = this.modelName; var adapterFactory = container.factoryFor ? container.factoryFor('adapter:application') : container.lookupFactory('adapter:application'); if (!adapterFactory) { if (requirejs.entries['ember-data/adapters/json-api']) { adapterFactory = (0, _require2.default)('ember-data/adapters/json-api')['default']; } // when ember-data/adapters/json-api is provided via ember-cli shims // using Ember Data 1.x the actual JSONAPIAdapter isn't found, but the // above require statement returns a bizzaro object with only a `default` // property (circular reference actually) if (!adapterFactory || !adapterFactory.create) { adapterFactory = DS.JSONAPIAdapter || DS.FixtureAdapter; } var thingToRegisterWith = this.registry || this.container; thingToRegisterWith.register('adapter:application', adapterFactory); } callbacks.store = function () { var container = this.container; return container.lookup('service:store') || container.lookup('store:main'); }; if (callbacks.subject === defaultSubject) { callbacks.subject = function (options) { var container = this.container; return Ember.run(function () { var store = container.lookup('service:store') || container.lookup('store:main'); return store.createRecord(modelName, options); }); }; } } }]); return _class; }(_testModule.default); exports.default = _class; }); define('ember-test-helpers/test-module', ['exports', 'ember-test-helpers/abstract-test-module', 'ember-test-helpers/test-resolver', 'ember-test-helpers/build-registry', 'ember-test-helpers/has-ember-version'], function (exports, _abstractTestModule, _testResolver, _buildRegistry, _hasEmberVersion) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _class = function (_AbstractTestModule) { _inherits(_class, _AbstractTestModule); function _class(subjectName, description, callbacks) { _classCallCheck(this, _class); // Allow `description` to be omitted, in which case it should // default to `subjectName` if (!callbacks && (typeof description === 'undefined' ? 'undefined' : _typeof(description)) === 'object') { callbacks = description; description = subjectName; } var _this2 = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this, description || subjectName, callbacks)); _this2.subjectName = subjectName; _this2.description = description || subjectName; _this2.resolver = _this2.callbacks.resolver || (0, _testResolver.getResolver)(); if (_this2.callbacks.integration && _this2.callbacks.needs) { throw new Error("cannot declare 'integration: true' and 'needs' in the same module"); } if (_this2.callbacks.integration) { _this2.initIntegration(callbacks); delete callbacks.integration; } _this2.initSubject(); _this2.initNeeds(); return _this2; } _createClass(_class, [{ key: 'initIntegration', value: function initIntegration(options) { if (options.integration === 'legacy') { throw new Error('`integration: \'legacy\'` is only valid for component tests.'); } this.isIntegration = true; } }, { key: 'initSubject', value: function initSubject() { this.callbacks.subject = this.callbacks.subject || this.defaultSubject; } }, { key: 'initNeeds', value: function initNeeds() { this.needs = [this.subjectName]; if (this.callbacks.needs) { this.needs = this.needs.concat(this.callbacks.needs); delete this.callbacks.needs; } } }, { key: 'initSetupSteps', value: function initSetupSteps() { this.setupSteps = []; this.contextualizedSetupSteps = []; if (this.callbacks.beforeSetup) { this.setupSteps.push(this.callbacks.beforeSetup); delete this.callbacks.beforeSetup; } this.setupSteps.push(this.setupContainer); this.setupSteps.push(this.setupContext); this.setupSteps.push(this.setupTestElements); this.setupSteps.push(this.setupAJAXListeners); if (this.callbacks.setup) { this.contextualizedSetupSteps.push(this.callbacks.setup); delete this.callbacks.setup; } } }, { key: 'initTeardownSteps', value: function initTeardownSteps() { this.teardownSteps = []; this.contextualizedTeardownSteps = []; if (this.callbacks.teardown) { this.contextualizedTeardownSteps.push(this.callbacks.teardown); delete this.callbacks.teardown; } this.teardownSteps.push(this.teardownSubject); this.teardownSteps.push(this.teardownContainer); this.teardownSteps.push(this.teardownContext); this.teardownSteps.push(this.teardownTestElements); this.teardownSteps.push(this.teardownAJAXListeners); if (this.callbacks.afterTeardown) { this.teardownSteps.push(this.callbacks.afterTeardown); delete this.callbacks.afterTeardown; } } }, { key: 'setupContainer', value: function setupContainer() { if (this.isIntegration || this.isLegacy) { this._setupIntegratedContainer(); } else { this._setupIsolatedContainer(); } } }, { key: 'setupContext', value: function setupContext() { var subjectName = this.subjectName; var container = this.container; var factory = function factory() { return container.factoryFor ? container.factoryFor(subjectName) : container.lookupFactory(subjectName); }; _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'setupContext', this).call(this, { container: this.container, registry: this.registry, factory: factory, register: function register() { var target = this.registry || this.container; return target.register.apply(target, arguments); } }); if (Ember.setOwner) { Ember.setOwner(this.context, this.container.owner); } this.setupInject(); } }, { key: 'setupInject', value: function setupInject() { var module = this; var context = this.context; if (Ember.inject) { var keys = (Object.keys || Ember.keys)(Ember.inject); keys.forEach(function (typeName) { context.inject[typeName] = function (name, opts) { var alias = opts && opts.as || name; Ember.run(function () { Ember.set(context, alias, module.container.lookup(typeName + ':' + name)); }); }; }); } } }, { key: 'teardownSubject', value: function teardownSubject() { var subject = this.cache.subject; if (subject) { Ember.run(function () { Ember.tryInvoke(subject, 'destroy'); }); } } }, { key: 'teardownContainer', value: function teardownContainer() { var container = this.container; Ember.run(function () { container.destroy(); }); } }, { key: 'defaultSubject', value: function defaultSubject(options, factory) { return factory.create(options); } }, { key: 'contextualizeCallbacks', value: function contextualizeCallbacks() { var callbacks = this.callbacks; var context = this.context; this.cache = this.cache || {}; this.cachedCalls = this.cachedCalls || {}; var keys = (Object.keys || Ember.keys)(callbacks); var keysLength = keys.length; if (keysLength) { var deprecatedContext = this._buildDeprecatedContext(this, context); for (var i = 0; i < keysLength; i++) { this._contextualizeCallback(context, keys[i], deprecatedContext); } } } }, { key: '_contextualizeCallback', value: function _contextualizeCallback(context, key, callbackContext) { var _this = this; var callbacks = this.callbacks; var factory = context.factory; context[key] = function (options) { if (_this.cachedCalls[key]) { return _this.cache[key]; } var result = callbacks[key].call(callbackContext, options, factory()); _this.cache[key] = result; _this.cachedCalls[key] = true; return result; }; } }, { key: '_buildDeprecatedContext', value: function _buildDeprecatedContext(module, context) { var deprecatedContext = Object.create(context); var keysForDeprecation = Object.keys(module); for (var i = 0, l = keysForDeprecation.length; i < l; i++) { this._proxyDeprecation(module, deprecatedContext, keysForDeprecation[i]); } return deprecatedContext; } }, { key: '_proxyDeprecation', value: function _proxyDeprecation(obj, proxy, key) { if (typeof proxy[key] === 'undefined') { Object.defineProperty(proxy, key, { get: function get() { Ember.deprecate('Accessing the test module property "' + key + '" from a callback is deprecated.', false, { id: 'ember-test-helpers.test-module.callback-context', until: '0.6.0' }); return obj[key]; } }); } } }, { key: '_setupContainer', value: function _setupContainer(isolated) { var resolver = this.resolver; var items = (0, _buildRegistry.default)(!isolated ? resolver : Object.create(resolver, { resolve: { value: function value() {} } })); this.container = items.container; this.registry = items.registry; if ((0, _hasEmberVersion.default)(1, 13)) { var thingToRegisterWith = this.registry || this.container; var router = resolver.resolve('router:main'); router = router || Ember.Router.extend(); thingToRegisterWith.register('router:main', router); } } }, { key: '_setupIsolatedContainer', value: function _setupIsolatedContainer() { var resolver = this.resolver; this._setupContainer(true); var thingToRegisterWith = this.registry || this.container; for (var i = this.needs.length; i > 0; i--) { var fullName = this.needs[i - 1]; var normalizedFullName = resolver.normalize(fullName); thingToRegisterWith.register(fullName, resolver.resolve(normalizedFullName)); } if (!this.registry) { this.container.resolver = function () {}; } } }, { key: '_setupIntegratedContainer', value: function _setupIntegratedContainer() { this._setupContainer(); } }]); return _class; }(_abstractTestModule.default); exports.default = _class; }); define('ember-test-helpers/test-resolver', ['exports'], function (exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.setResolver = setResolver; exports.getResolver = getResolver; var __resolver__; function setResolver(resolver) { __resolver__ = resolver; } function getResolver() { if (__resolver__ == null) { throw new Error('you must set a resolver with `testResolver.set(resolver)`'); } return __resolver__; } }); define('ember-test-helpers/wait', ['exports'], function (exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports._teardownAJAXHooks = _teardownAJAXHooks; exports._setupAJAXHooks = _setupAJAXHooks; exports.default = wait; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var jQuery = Ember.$; var requests; function incrementAjaxPendingRequests(_, xhr) { requests.push(xhr); } function decrementAjaxPendingRequests(_, xhr) { for (var i = 0; i < requests.length; i++) { if (xhr === requests[i]) { requests.splice(i, 1); } } } function _teardownAJAXHooks() { if (!jQuery) { return; } jQuery(document).off('ajaxSend', incrementAjaxPendingRequests); jQuery(document).off('ajaxComplete', decrementAjaxPendingRequests); } function _setupAJAXHooks() { requests = []; if (!jQuery) { return; } jQuery(document).on('ajaxSend', incrementAjaxPendingRequests); jQuery(document).on('ajaxComplete', decrementAjaxPendingRequests); } var _internalCheckWaiters; if (Ember.__loader.registry['ember-testing/test/waiters']) { _internalCheckWaiters = Ember.__loader.require('ember-testing/test/waiters').checkWaiters; } function checkWaiters() { if (_internalCheckWaiters) { return _internalCheckWaiters(); } else if (Ember.Test.waiters) { if (Ember.Test.waiters.any(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), context = _ref2[0], callback = _ref2[1]; return !callback.call(context); })) { return true; } } return false; } function wait(_options) { var options = _options || {}; var waitForTimers = options.hasOwnProperty('waitForTimers') ? options.waitForTimers : true; var waitForAJAX = options.hasOwnProperty('waitForAJAX') ? options.waitForAJAX : true; var waitForWaiters = options.hasOwnProperty('waitForWaiters') ? options.waitForWaiters : true; return new Ember.RSVP.Promise(function (resolve) { var watcher = self.setInterval(function () { if (waitForTimers && (Ember.run.hasScheduledTimers() || Ember.run.currentRunLoop)) { return; } if (waitForAJAX && requests && requests.length > 0) { return; } if (waitForWaiters && checkWaiters()) { return; } // Stop polling self.clearInterval(watcher); // Synchronously resolve the promise Ember.run(null, resolve); }, 10); }); } }); define("qunit", ["exports"], function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* globals QUnit */ var _module = QUnit.module; exports.module = _module; var test = exports.test = QUnit.test; var skip = exports.skip = QUnit.skip; var only = exports.only = QUnit.only; var todo = exports.todo = QUnit.todo; exports.default = QUnit; }); runningTests = true; if (window.Testem) { window.Testem.hookIntoTestFramework(); } //# sourceMappingURL=test-support.map
/** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const gulp = require('gulp'); const serve = require('serve'); const file = require('gulp-file'); const rename = require('gulp-rename'); const del = require('del'); const cache = require('gulp-cached'); const jasmine = require('gulp-jasmine'); const eslint = require('gulp-eslint'); const gutil = require('gulp-util'); const gulpIf = require('gulp-if'); const gulpIgnore = require('gulp-ignore'); const favicons = require('gulp-favicons'); const argv = require('yargs').argv; const path = require('path'); const fs = require('fs'); const change = require('gulp-change'); const grun = require('gulp-run'); const htmlmin = require('gulp-htmlmin'); const htmlhint = require('gulp-htmlhint'); const compileExample = require('./tasks/compile-example'); const sitemap = require('./tasks/compile-sitemap'); const createExample = require('./tasks/create-example'); const FileName = require('./lib/FileName'); const Metadata = require('./lib/Metadata'); const ExampleFile = require('./lib/ExampleFile'); const gulpAmpValidator = require('gulp-amphtml-validator'); const Templates = require('./lib/Templates'); const PROD = 'prod'; const paths = { dist: { dir: 'dist', css: 'dist/css', html: 'dist/**/*.html', samples: ['dist/**/*.html'], img: 'dist/img', video: 'dist/video', json: 'dist/json', favicons: 'dist/favicons', fonts: 'dist/fonts', wellknown: 'dist/.well-known', }, nodeModules: ['sw-toolbox'], images: 'src/img/*.{png,jpg,gif,svg}', favicon: 'src/img/favicon.png', samples: 'src/**/*.html', metadata: 'src/**/*.json', playground: 'playground', boilerplate: 'boilerplate-generator', src: 'src', scripts: [ 'tasks/**/*.js', 'gulpfile.js', 'boilerplate-generator/*.js', 'boilerplate-generator/lib/**/*.js', ], static: 'static/**/*.*', templates: { dir: 'templates', files: ['templates/**/*.css', 'templates/**/*.html'], html: 'templates/**/*.html', }, api: { conf: 'api/conf.json', dir: 'api', src: 'api/src/**/*.*', dist: 'api/dist', }, packager: { dist: 'packager/dist', }, tmp: { dir: 'tmp', }, videos: 'src/video/*.{mp4,webm,m3u8,ts,vtt}', json: 'src/json/*.json', css: 'templates/css/*.css', fonts: 'src/fonts/*.ttf', wellknown: '.well-known/assetlinks.json', }; const config = { templates: { root: paths.templates.dir, index: 'index.html', example: 'example.html', newExample: 'new-example.html', preview: 'preview.html', }, api: { host: 'https://amp-by-example-api.appspot.com', dist: 'api/dist', }, a4a: { template: 'preview-a4a.html', defaultLayout: 'fixed', defaultWidth: 300, defaultHeight: 250, }, amp4email: { template: 'preview-amp4email.html', defaultLayout: 'fixed', defaultWidth: 832, }, host: 'https://ampbyexample.com', }; const sampleTemplates = Templates.get(config.templates.root, /* minify */ false, '<% %>'); gulp.task('serve', () => { serve(paths.dist.dir, { port: argv.port || 8000, ignore: ['node_modules'], }); }); gulp.task('serve:api', () => { serve(paths.api.dist, { port: 8800, ignore: ['node_modules'], }); }); gulp.task('deploy:prod', callback => { config.env = PROD; return gulp.series('clean', 'robots:allow', 'build', 'deploy:site:prod', 'deploy:api:prod', 'build:sxg', 'deploy:sxg:prod')(callback); }); gulp.task('deploy:staging', callback => { config.env = PROD; config.appId = 'amp-by-example-staging'; config.host = 'https://' + config.appId + '.appspot.com'; return gulp.series('clean', 'robots:disallow', 'build', 'deploy:site:staging')(callback); }); gulp.task('conf:encode', () => { return run('openssl aes-256-cbc -e -in ' + paths.api.conf + ' -out ' + paths.api.conf + '.enc -pass env:AMP_BY_EXAMPLE_DEPLOY_KEY').exec(); }); gulp.task('conf:decode', () => { return run('openssl aes-256-cbc -d -in ' + paths.api.conf + '.enc -out ' + paths.api.conf + ' -pass env:AMP_BY_EXAMPLE_DEPLOY_KEY').exec(); }); gulp.task('deploy:site:prod', () => { return run('goapp deploy -application amp-by-example -version 1').exec(); }); gulp.task('deploy:api:prod', () => { return run( 'cd api && goapp deploy -application amp-by-example-api -version 1') .exec(); }); gulp.task('deploy:sxg:prod', () => { const privkey = 'packager/certs/privkey.pem.enc'; const cert = 'packager/certs/cert.pem.enc'; if (!fs.existsSync(privkey) || !fs.existsSync(cert)) { throw Error([ `Encrypted private keys (${privkey}, ${cert})`, 'required for SXG are missing', ].join(' ')); } return run( 'cd packager && gcloud app deploy -q --project amp-by-example-sxg') .exec(); }); gulp.task('deploy:site:staging', () => { return run('goapp deploy -application ' + config.appId + ' -version 1') .exec(); }); gulp.task('copy:images', () => { return gulp.src(paths.images) .pipe(cache('img')) .pipe(gulp.dest(paths.dist.img)); }); gulp.task('copy:videos', () => { return gulp.src(paths.videos) .pipe(cache('video')) .pipe(gulp.dest(paths.dist.video)); }); gulp.task('copy:json', () => { return gulp.src(paths.json) .pipe(cache('json')) .pipe(gulp.dest(paths.dist.json)); }); gulp.task('copy:css', () => { return gulp.src(paths.css) .pipe(cache('css')) .pipe(gulp.dest(paths.dist.css)); }); gulp.task('copy:node-modules', () => { const modules = paths.nodeModules.map( module => 'node_modules/' + module + '/**/*' ); return gulp.src(modules, { base: 'node_modules', }).pipe(gulp.dest(paths.dist.dir)); }); gulp.task('copy:fonts', () => { return gulp.src(paths.fonts) .pipe(cache('fonts')) .pipe(gulp.dest(paths.dist.fonts)); }); gulp.task('copy:well-known', () => { return gulp.src(paths.wellknown) .pipe(cache('wellknown')) .pipe(gulp.dest(paths.dist.wellknown)); }); gulp.task('copy:license', () => { return gulp.src('LICENSE') .pipe(cache('license')) .pipe(rename(path => { path.extname = '.txt'; })) .pipe(gulp.dest(paths.dist.dir)); }); gulp.task('copy:static', () => { return gulp.src(paths.static) .pipe(gulpIf(isHtml, change(prerenderTemplates))) .pipe(cache('static')) .pipe(gulp.dest(paths.dist.dir)); }); gulp.task('copy:api', () => { return gulp.src(paths.api.src) .pipe(cache('api')) .pipe(gulp.dest(paths.api.dist)); }); function isHtml(file) { return file.path.endsWith('.html'); } function prerenderTemplates(string) { return sampleTemplates.renderString(string, config); } gulp.task('compile:favicons', () => { return gulp.src(paths.favicon) .pipe(cache('favicons')) .pipe(favicons({ 'appName': 'AMP by Example', 'appDescription': 'Accelerated Mobile Pages in Action', 'developerName': 'Sebastian Benz', 'developerURL': 'http://sebastianbenz.de/', 'background': '#ffffff', 'path': '/favicons', 'url': Metadata.HOST, 'display': 'standalone', 'orientation': 'none', 'version': 1.0, 'logging': false, 'online': false, 'html': 'favicons.html', 'pipeHTML': true, 'replace': true, 'icons': { 'opengraph': false, 'twitter': false, }, })) .on('error', gutil.log) .pipe(gulp.dest(paths.dist.favicons)); }); const shouldIgnoreSample = function(file) { if (!file.path.endsWith('.html')) { return true; } if (file.path.endsWith('/source/index.html')) { return true; } const metadata = file.metadata; if (!metadata) { return false; } if (!metadata.experiments && !metadata.skipValidation) { return false; } gutil.log(gutil.colors.yellow('IGNORED') + ' ' + file.relative); return true; }; gulp.task('validate:example', () => { return gulp.src(paths.samples) .pipe(compileExample(config)) .pipe(gulpIgnore.exclude(shouldIgnoreSample)) // Valide the input and attach the validation result to the "amp" property // of the file object. .pipe(gulpAmpValidator.validate()) // Print the validation results to the console. .pipe(gulpAmpValidator.format()) // Exit the process with error code (1) if an AMP validation error // occurred. .pipe(gulpAmpValidator.failAfterError()); }); function shouldMinifyHtml(file) { if (!file.path.endsWith('.html')) { return false; } if (file.path.endsWith('/source/index.html')) { return false; } return true; } gulp.task('compile:example', () => { return gulp.src(paths.samples) .pipe(compileExample(config)) .pipe(gulpIf(shouldMinifyHtml, htmlmin({ collapseWhitespace: true, minifyCSS: true, caseSensitive: true, }))) .pipe(gulp.dest(paths.dist.dir)); }); gulp.task('compile:sitemap', () => { return gulp.src(paths.samples) .pipe(sitemap(config)) .pipe(gulp.dest(paths.dist.dir)); }); gulp.task('create', () => { const title = argv.n || argv.name; const fileName = FileName.fromString(title); if (!fileName) { throwInvalidArgumentError('example name missing'); } let examplePath; const dest = argv.d || argv.dest; const category = argv.c || argv.category; if (dest) { examplePath = path.join(path.basename(dest), fileName); } else if (category) { examplePath = FileName.fromString(category, title); } else { throwInvalidArgumentError('example category or directory missing'); } return file(examplePath, '', { src: true, }) .pipe(createExample(paths, config)) .pipe(gulp.dest(paths.src)); }); function throwInvalidArgumentError(message) { throw new gutil.PluginError({ plugin: 'create', message: gutil.colors.red('\nError: ' + message + '\n\n') + gutil.colors.blue('create a new category:\n') + 'gulp create -n "The Name" -c "The Category"\n\n' + gutil.colors.blue('add to existing category:\n') + 'gulp create -n "The Name" -d src/directory', }); } gulp.task('clean', () => { cache.caches = {}; return del([paths.dist.dir, paths.packager.dist, config.api.dist]); }); gulp.task('watch', () => { gulp.watch( [paths.samples, paths.templates.files, paths.metadata], gulp.series('compile:example') ); gulp.watch(paths.images, gulp.series('copy:images')); gulp.watch(paths.json, gulp.series('copy:json')); gulp.watch(paths.videos, gulp.series('copy:videos')); gulp.watch(paths.static, gulp.series('copy:static')); }); gulp.task('test', () => { return gulp.src('spec/**/*Spec.js') .pipe(jasmine()); }); gulp.task('test2', () => { return gulp.src('spec/**/*Spec.js') .pipe(jasmine({ includeStackTrace: true, })); }); gulp.task('lint', () => { const hasFixFlag = argv.fix; let errorsFound = false; return gulp.src(paths.scripts, { base: './', }) .pipe(eslint({ fix: hasFixFlag, })) .pipe(eslint.formatEach('stylish', msg => { errorsFound = true; gutil.log(gutil.colors.red(msg)); })) .pipe(gulpIf(isFixed, gulp.dest('.'))) .on('end', () => { if (errorsFound && !hasFixFlag) { gutil.log(gutil.colors.blue('Run `gulp lint --fix` to ' + 'fix some of these lint warnings/errors. This is a destructive ' + 'operation (operates on the file system) so please make sure ' + 'you commit before running.')); process.exit(1); } }); }); gulp.task('lint:backend', () => { /* gofmt only returns non zero status on syntax error */ return run('test -z $(gofmt -l $(find . -name \'*.go\'))').exec(); }); gulp.task('lint:html', () => { return gulp.src([paths.samples].join(paths.dist.samples)) .pipe(htmlhint({ 'doctype-first': false, 'title-require': false, 'attr-lowercase': false, })) .pipe(htmlhint.failReporter()); }); gulp.task('default', callback => { config.host = 'http://localhost:8000'; config.api.host = 'http://localhost:8800'; return gulp.parallel( 'serve', 'serve:api', 'build', 'watch')(callback); }); gulp.task('backend:watch', callback => { config.host = 'http://localhost:8080'; config.api.host = 'http://localhost:8800'; return gulp.parallel( 'serve:api', 'build', 'watch', 'backend:serve')(callback); }); gulp.task('backend:serve', () => { return run('dev_appserver.py app.yaml').exec(); }); gulp.task('api:serve', () => { return run('cd api && dev_appserver.py app.yaml --admin_port=8100').exec(); }); gulp.task('validate', gulp.series( 'test', 'validate:example', 'lint', 'lint:backend', 'lint:html', 'test' )); gulp.task('robots:disallow', () => { return generateRobotsTxt(`User-Agent: * Disallow: / `); }); gulp.task('robots:allow', () => { return generateRobotsTxt(`User-Agent: * Disallow: `); }); gulp.task('build:playground', () => { const playgroundDist = '../dist/' + paths.playground; return run( 'cd ' + paths.playground + ' && ' + 'npm i && ' + 'npm run-script build && ' + 'mkdir -p ../' + paths.dist.dir + ' && ' + 'rm -rf ' + playgroundDist + ' && ' + 'cp -R dist ' + playgroundDist ).exec(); }); gulp.task('build:boilerplate-generator', () => { const boilerplateDist = '../dist/boilerplate'; return run( 'cd ' + paths.boilerplate + ' && ' + 'npm i && ' + 'node build.js && ' + 'mkdir -p ../' + paths.dist.dir + ' && ' + 'rm -rf ' + boilerplateDist + ' && ' + 'cp -R dist ' + boilerplateDist ).exec(); } ); gulp.task('build:sxg', () => { return gulp.src(paths.dist.html) .pipe(gulpAmpValidator.validate()) .pipe(gulpIgnore.exclude(function(file) { return file.ampValidationResult.status !== 'PASS'; })) .pipe(gulp.dest(paths.packager.dist)); }); function generateRobotsTxt(contents) { return file('robots.txt', contents, { src: true, }) .pipe(gulp.dest('dist')); } /* adds a title link to all sample files */ function performChange(content) { const exampleFile = ExampleFile.fromPath(this.file.path); const match = content.match(/<!---([\s\S]*)?--->/); if (!match) { return content; } gutil.log('changing', exampleFile.title); const frontmatter = JSON.parse(match[1]); const yaml = require('js-yaml'); const yamlFrontmatter = `<!--- ${yaml.safeDump(frontmatter)} ---> ${content.substring(match[0].length)}`; /* if (!/<title>/.test(content)) { content = content.replace(/<meta charset="utf-8">/g, '<meta charset="utf-8">\n <title>' + exampleFile.title() + '</title>'); } */ return yamlFrontmatter; } gulp.task('change', () => { return gulp.src('src/**/*.html') .pipe(change(performChange)) .pipe(gulp.dest('src/')); }); gulp.task('build', gulp.parallel( 'copy:images', 'copy:videos', 'copy:json', 'copy:css', 'copy:api', 'copy:fonts', 'copy:node-modules', 'copy:license', 'copy:static', 'compile:favicons', 'compile:sitemap', 'compile:example', 'copy:well-known', 'build:playground', 'build:boilerplate-generator' )); function run(command) { return grun(command, { verbosity: 3, }); } function isFixed(file) { return file.eslint.fixed; }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkhbase.endpoint import endpoint_data class ModifyInstanceTypeRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'HBase', '2019-01-01', 'ModifyInstanceType','hbase') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ClusterId(self): return self.get_query_params().get('ClusterId') def set_ClusterId(self,ClusterId): self.add_query_param('ClusterId',ClusterId) def get_MasterInstanceType(self): return self.get_query_params().get('MasterInstanceType') def set_MasterInstanceType(self,MasterInstanceType): self.add_query_param('MasterInstanceType',MasterInstanceType) def get_CoreInstanceType(self): return self.get_query_params().get('CoreInstanceType') def set_CoreInstanceType(self,CoreInstanceType): self.add_query_param('CoreInstanceType',CoreInstanceType)
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model for an Oppia exploration.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules import datetime from constants import constants import core.storage.base_model.gae_models as base_models import core.storage.user.gae_models as user_models import feconf import python_utils from google.appengine.ext import ndb class ExplorationSnapshotMetadataModel(base_models.BaseSnapshotMetadataModel): """Storage model for the metadata for an exploration snapshot.""" pass class ExplorationSnapshotContentModel(base_models.BaseSnapshotContentModel): """Storage model for the content of an exploration snapshot.""" pass class ExplorationModel(base_models.VersionedModel): """Versioned storage model for an Oppia exploration. This class should only be imported by the exploration services file and the exploration model test file. """ SNAPSHOT_METADATA_CLASS = ExplorationSnapshotMetadataModel SNAPSHOT_CONTENT_CLASS = ExplorationSnapshotContentModel ALLOW_REVERT = True # What this exploration is called. title = ndb.StringProperty(required=True) # The category this exploration belongs to. category = ndb.StringProperty(required=True, indexed=True) # The objective of this exploration. objective = ndb.TextProperty(default='', indexed=False) # The ISO 639-1 code for the language this exploration is written in. language_code = ndb.StringProperty( default=constants.DEFAULT_LANGUAGE_CODE, indexed=True) # Tags (topics, skills, concepts, etc.) associated with this # exploration. tags = ndb.StringProperty(repeated=True, indexed=True) # A blurb for this exploration. blurb = ndb.TextProperty(default='', indexed=False) # 'Author notes' for this exploration. author_notes = ndb.TextProperty(default='', indexed=False) # The version of the states blob schema. states_schema_version = ndb.IntegerProperty( required=True, default=0, indexed=True) # The name of the initial state of this exploration. init_state_name = ndb.StringProperty(required=True, indexed=False) # A dict representing the states of this exploration. This dict should # not be empty. states = ndb.JsonProperty(default={}, indexed=False) # The dict of parameter specifications associated with this exploration. # Each specification is a dict whose keys are param names and whose values # are each dicts with a single key, 'obj_type', whose value is a string. param_specs = ndb.JsonProperty(default={}, indexed=False) # The list of parameter changes to be performed once at the start of a # reader's encounter with an exploration. param_changes = ndb.JsonProperty(repeated=True, indexed=False) # A boolean indicating whether automatic text-to-speech is enabled in # this exploration. auto_tts_enabled = ndb.BooleanProperty(default=True, indexed=True) # A boolean indicating whether correctness feedback is enabled in this # exploration. correctness_feedback_enabled = ndb.BooleanProperty( default=False, indexed=True) # DEPRECATED in v2.0.0.rc.2. Do not use. Retaining it here because deletion # caused GAE to raise an error on fetching a specific version of the # exploration model. # TODO(sll): Fix this error and remove this property. skill_tags = ndb.StringProperty(repeated=True, indexed=True) # DEPRECATED in v2.0.1. Do not use. # TODO(sll): Remove this property from the model. default_skin = ndb.StringProperty(default='conversation_v1') # DEPRECATED in v2.5.4. Do not use. skin_customizations = ndb.JsonProperty(indexed=False) @staticmethod def get_deletion_policy(): """Exploration is deleted only if it is not public.""" return base_models.DELETION_POLICY.KEEP_IF_PUBLIC @classmethod def has_reference_to_user_id(cls, user_id): """Check whether ExplorationModel or its snapshots references the given user. Args: user_id: str. The ID of the user whose data should be checked. Returns: bool. Whether any models refer to the given user ID. """ return cls.SNAPSHOT_METADATA_CLASS.exists_for_user_id(user_id) @staticmethod def get_user_id_migration_policy(): """ExplorationModel doesn't have any field with user ID.""" return base_models.USER_ID_MIGRATION_POLICY.NOT_APPLICABLE @classmethod def get_exploration_count(cls): """Returns the total number of explorations.""" return cls.get_all().count() def _trusted_commit( self, committer_id, commit_type, commit_message, commit_cmds): """Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the change. commit_type: str. The type of commit. Possible values are in core.storage.base_models.COMMIT_TYPE_CHOICES. commit_message: str. The commit description message. commit_cmds: list(dict). A list of commands, describing changes made in this model, which should give sufficient information to reconstruct the commit. Each dict always contains: cmd: str. Unique command. and then additional arguments for that command. """ super(ExplorationModel, self)._trusted_commit( committer_id, commit_type, commit_message, commit_cmds) committer_user_settings_model = ( user_models.UserSettingsModel.get_by_id(committer_id)) committer_username = ( committer_user_settings_model.username if committer_user_settings_model else '') exp_rights = ExplorationRightsModel.get_by_id(self.id) # TODO(msl): test if put_async() leads to any problems (make # sure summary dicts get updated correctly when explorations # are changed). exploration_commit_log = ExplorationCommitLogEntryModel.create( self.id, self.version, committer_id, committer_username, commit_type, commit_message, commit_cmds, exp_rights.status, exp_rights.community_owned ) exploration_commit_log.exploration_id = self.id exploration_commit_log.put() @classmethod def delete_multi(cls, entity_ids, committer_id, commit_message, force_deletion=False): """Deletes the given cls instances with the given entity_ids. Note that this extends the superclass method. Args: entity_ids: list(str). Ids of entities to delete. committer_id: str. The user_id of the user who committed the change. commit_message: str. The commit description message. force_deletion: bool. If True these models are deleted completely from storage, otherwise there are only marked as deleted. Default is False. """ super(ExplorationModel, cls).delete_multi( entity_ids, committer_id, commit_message, force_deletion=force_deletion) if not force_deletion: committer_user_settings_model = ( user_models.UserSettingsModel.get_by_id(committer_id)) committer_username = ( committer_user_settings_model.username if committer_user_settings_model else '') commit_log_models = [] exp_rights_models = ExplorationRightsModel.get_multi( entity_ids, include_deleted=True) versioned_models = cls.get_multi(entity_ids, include_deleted=True) for model, rights_model in python_utils.ZIP(versioned_models, exp_rights_models): exploration_commit_log = ExplorationCommitLogEntryModel.create( model.id, model.version, committer_id, committer_username, cls._COMMIT_TYPE_DELETE, commit_message, [{'cmd': cls.CMD_DELETE_COMMIT}], rights_model.status, rights_model.community_owned ) exploration_commit_log.exploration_id = model.id commit_log_models.append(exploration_commit_log) ndb.put_multi_async(commit_log_models) class ExplorationRightsSnapshotMetadataModel( base_models.BaseSnapshotMetadataModel): """Storage model for the metadata for an exploration rights snapshot.""" pass class ExplorationRightsSnapshotContentModel( base_models.BaseSnapshotContentModel): """Storage model for the content of an exploration rights snapshot.""" pass class ExplorationRightsModel(base_models.VersionedModel): """Storage model for rights related to an exploration. The id of each instance is the id of the corresponding exploration. """ SNAPSHOT_METADATA_CLASS = ExplorationRightsSnapshotMetadataModel SNAPSHOT_CONTENT_CLASS = ExplorationRightsSnapshotContentModel ALLOW_REVERT = False # The user_ids of owners of this exploration. owner_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to edit this exploration. editor_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to voiceover this exploration. voice_artist_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to view this exploration. viewer_ids = ndb.StringProperty(indexed=True, repeated=True) # Whether this exploration is owned by the community. community_owned = ndb.BooleanProperty(indexed=True, default=False) # The exploration id which this exploration was cloned from. If None, this # exploration was created from scratch. cloned_from = ndb.StringProperty() # For private explorations, whether this exploration can be viewed # by anyone who has the URL. If the exploration is not private, this # setting is ignored. viewable_if_private = ndb.BooleanProperty(indexed=True, default=False) # Time, in milliseconds, when the exploration was first published. first_published_msec = ndb.FloatProperty(indexed=True, default=None) # The publication status of this exploration. status = ndb.StringProperty( default=constants.ACTIVITY_STATUS_PRIVATE, indexed=True, choices=[ constants.ACTIVITY_STATUS_PRIVATE, constants.ACTIVITY_STATUS_PUBLIC ] ) # DEPRECATED in v2.8.3. Do not use. translator_ids = ndb.StringProperty(indexed=True, repeated=True) @staticmethod def get_deletion_policy(): """Exploration rights are deleted only if the corresponding exploration is not public. """ return base_models.DELETION_POLICY.KEEP_IF_PUBLIC @staticmethod def transform_dict_to_valid(model_dict): """Replace invalid fields and values in the ExplorationRightsModel dict. Some old ExplorationRightsSnapshotContentModels can contain fields and field values that are no longer supported and would cause an exception when we try to reconstitute a ExplorationRightsModel from them. We need to remove or replace these fields and values. Args: model_dict: dict. The content of the model. Some fields and field values might no longer exist in the ExplorationRightsModel schema. Returns: dict. The content of the model. Only valid fields and values are present. """ # The all_viewer_ids field was previously used in some versions of the # model, we need to remove it. if 'all_viewer_ids' in model_dict: del model_dict['all_viewer_ids'] # The status field could historically take the value 'publicized', this # value is now equivalent to 'public'. if model_dict['status'] == 'publicized': model_dict['status'] = constants.ACTIVITY_STATUS_PUBLIC # The voice_artist_ids field was previously named translator_ids. We # need to move the values from translator_ids field to voice_artist_ids # and delete translator_ids. if 'translator_ids' in model_dict and model_dict['translator_ids']: model_dict['voice_artist_ids'] = model_dict['translator_ids'] model_dict['translator_ids'] = [] return model_dict @classmethod def has_reference_to_user_id(cls, user_id): """Check whether ExplorationRightsModel or its snapshots reference user. Args: user_id: str. The ID of the user whose data should be checked. Returns: bool. Whether any models refer to the given user ID. """ more_results = True cursor = None while more_results: snapshot_content_models, cursor, more_results = ( cls.SNAPSHOT_CONTENT_CLASS.query().fetch_page( base_models.FETCH_BATCH_SIZE, start_cursor=cursor)) for snapshot_content_model in snapshot_content_models: reconstituted_model = cls( **ExplorationRightsModel.transform_dict_to_valid( snapshot_content_model.content)) if any((user_id in reconstituted_model.owner_ids, user_id in reconstituted_model.editor_ids, user_id in reconstituted_model.voice_artist_ids, user_id in reconstituted_model.viewer_ids)): return True return ( cls.query(ndb.OR( cls.owner_ids == user_id, cls.editor_ids == user_id, cls.voice_artist_ids == user_id, cls.viewer_ids == user_id )).get(keys_only=True) is not None or cls.SNAPSHOT_METADATA_CLASS.exists_for_user_id(user_id)) @staticmethod def get_user_id_migration_policy(): """ExplorationRightsModel has multiple fields with user ID.""" return base_models.USER_ID_MIGRATION_POLICY.CUSTOM @classmethod def migrate_model(cls, old_user_id, new_user_id): """Migrate model to use the new user ID in the owner_ids, editor_ids, voice_artist_ids and viewer_ids. Args: old_user_id: str. The old user ID. new_user_id: str. The new user ID. """ migrated_models = [] for model in cls.query(ndb.OR( cls.owner_ids == old_user_id, cls.editor_ids == old_user_id, cls.voice_artist_ids == old_user_id, cls.viewer_ids == old_user_id)).fetch(): model.owner_ids = [ new_user_id if owner_id == old_user_id else owner_id for owner_id in model.owner_ids] model.editor_ids = [ new_user_id if editor_id == old_user_id else editor_id for editor_id in model.editor_ids] model.voice_artist_ids = [ new_user_id if voice_art_id == old_user_id else voice_art_id for voice_art_id in model.voice_artist_ids] model.viewer_ids = [ new_user_id if viewer_id == old_user_id else viewer_id for viewer_id in model.viewer_ids] migrated_models.append(model) cls.put_multi(migrated_models, update_last_updated_time=False) def verify_model_user_ids_exist(self): """Check if UserSettingsModel exists for all the ids in owner_ids, editor_ids, voice_artist_ids and viewer_ids. """ user_ids = (self.owner_ids + self.editor_ids + self.voice_artist_ids + self.viewer_ids) user_ids = [user_id for user_id in user_ids if user_id != feconf.SYSTEM_COMMITTER_ID] user_settings_models = user_models.UserSettingsModel.get_multi( user_ids, include_deleted=True) return all(model is not None for model in user_settings_models) def save(self, committer_id, commit_message, commit_cmds): """Saves a new version of the exploration, updating the Exploration datastore model. Args: committer_id: str. The user_id of the user who committed the change. commit_message: str. The commit description message. commit_cmds: list(dict). A list of commands, describing changes made in this model, which should give sufficient information to reconstruct the commit. Each dict always contains: cmd: str. The type of the command. A full list of command types can be found in core/domain/exp_domain.py. and then additional arguments for that command. For example: {'cmd': 'AUTO_revert_version_number', 'version_number': 4} """ super(ExplorationRightsModel, self).commit( committer_id, commit_message, commit_cmds) def _trusted_commit( self, committer_id, commit_type, commit_message, commit_cmds): """Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the change. commit_type: str. The type of commit. Possible values are in core.storage.base_models.COMMIT_TYPE_CHOICES. commit_message: str. The commit description message. commit_cmds: list(dict). A list of commands, describing changes made in this model, should give sufficient information to reconstruct the commit. Each dict always contains: cmd: str. Unique command. and then additional arguments for that command. """ super(ExplorationRightsModel, self)._trusted_commit( committer_id, commit_type, commit_message, commit_cmds) # Create and delete events will already be recorded in the # ExplorationModel. if commit_type not in ['create', 'delete']: committer_user_settings_model = ( user_models.UserSettingsModel.get_by_id(committer_id)) committer_username = ( committer_user_settings_model.username if committer_user_settings_model else '') # TODO(msl): test if put_async() leads to any problems (make # sure summary dicts get updated correctly when explorations # are changed). ExplorationCommitLogEntryModel( id=('rights-%s-%s' % (self.id, self.version)), user_id=committer_id, username=committer_username, exploration_id=self.id, commit_type=commit_type, commit_message=commit_message, commit_cmds=commit_cmds, version=None, post_commit_status=self.status, post_commit_community_owned=self.community_owned, post_commit_is_private=( self.status == constants.ACTIVITY_STATUS_PRIVATE) ).put_async() @classmethod def export_data(cls, user_id): """(Takeout) Export user-relevant properties of ExplorationRightsModel. Args: user_id: str. The user_id denotes which user's data to extract. Returns: dict or None. The user-relevant properties of ExplorationRightsModel in a python dict format. In this case, we are returning all the ids of explorations that the user is connected to, so they either own, edit, voice, or have permission to view. """ owned_explorations = cls.get_all().filter(cls.owner_ids == user_id) editable_explorations = cls.get_all().filter(cls.editor_ids == user_id) voiced_explorations = ( cls.get_all().filter(cls.voice_artist_ids == user_id)) viewable_explorations = cls.get_all().filter(cls.viewer_ids == user_id) owned_exploration_ids = [exp.key.id() for exp in owned_explorations] editable_exploration_ids = ( [exp.key.id() for exp in editable_explorations]) voiced_exploration_ids = [exp.key.id() for exp in voiced_explorations] viewable_exploration_ids = ( [exp.key.id() for exp in viewable_explorations]) return { 'owned_exploration_ids': owned_exploration_ids, 'editable_exploration_ids': editable_exploration_ids, 'voiced_exploration_ids': voiced_exploration_ids, 'viewable_exploration_ids': viewable_exploration_ids } class ExplorationCommitLogEntryModel(base_models.BaseCommitLogEntryModel): """Log of commits to explorations. A new instance of this model is created and saved every time a commit to ExplorationModel or ExplorationRightsModel occurs. The id for this model is of the form 'exploration-{{EXP_ID}}-{{EXP_VERSION}}'. """ # The id of the exploration being edited. exploration_id = ndb.StringProperty(indexed=True, required=True) @staticmethod def get_deletion_policy(): """Exploration commit log is deleted only if the corresponding exploration is not public. """ return base_models.DELETION_POLICY.KEEP_IF_PUBLIC @classmethod def get_multi(cls, exp_id, exp_versions): """Gets the ExplorationCommitLogEntryModels for the given exploration id and exploration versions. Args: exp_id: str. The id of the exploration. exp_versions: list(int). The versions of the exploration. Returns: list(ExplorationCommitLogEntryModel). The list of ExplorationCommitLogEntryModel instances which matches the given exp_id and exp_versions. """ instance_ids = [cls._get_instance_id(exp_id, exp_version) for exp_version in exp_versions] return super(ExplorationCommitLogEntryModel, cls).get_multi( instance_ids) @classmethod def _get_instance_id(cls, exp_id, exp_version): """Returns ID of the exploration commit log entry model. Args: exp_id: str. The exploration id whose states are mapped. exp_version: int. The version of the exploration. Returns: str. A string containing exploration ID and exploration version. """ return 'exploration-%s-%s' % (exp_id, exp_version) @classmethod def get_all_non_private_commits( cls, page_size, urlsafe_start_cursor, max_age=None): """Fetches a list of all the non-private commits sorted by their last updated attribute. Args: page_size: int. The maximum number of entities to be returned. urlsafe_start_cursor: str or None. If provided, the list of returned entities starts from this datastore cursor. Otherwise, the returned entities start from the beginning of the full list of entities. max_age: datetime.timedelta. The maximum time duration within which commits are needed. Returns: 3-tuple of (results, cursor, more) which were created which were created no earlier than max_age before the current time where: results: List of query results. cursor: str or None. A query cursor pointing to the next batch of results. If there are no more results, this will be None. more: bool. If True, there are (probably) more results after this batch. If False, there are no further results after this batch. """ if not isinstance(max_age, datetime.timedelta) and max_age is not None: raise ValueError( 'max_age must be a datetime.timedelta instance or None.') query = cls.query(cls.post_commit_is_private == False) # pylint: disable=singleton-comparison if max_age: query = query.filter( cls.last_updated >= datetime.datetime.utcnow() - max_age) return cls._fetch_page_sorted_by_last_updated( query, page_size, urlsafe_start_cursor) class ExpSummaryModel(base_models.BaseModel): """Summary model for an Oppia exploration. This should be used whenever the content blob of the exploration is not needed (e.g. in search results, etc). A ExpSummaryModel instance stores the following information: id, title, category, objective, language_code, tags, last_updated, created_on, status (private, public), community_owned, owner_ids, editor_ids, viewer_ids, version. The key of each instance is the exploration id. """ # What this exploration is called. title = ndb.StringProperty(required=True) # The category this exploration belongs to. category = ndb.StringProperty(required=True, indexed=True) # The objective of this exploration. objective = ndb.TextProperty(required=True, indexed=False) # The ISO 639-1 code for the language this exploration is written in. language_code = ndb.StringProperty(required=True, indexed=True) # Tags associated with this exploration. tags = ndb.StringProperty(repeated=True, indexed=True) # Aggregate user-assigned ratings of the exploration. ratings = ndb.JsonProperty(default=None, indexed=False) # Scaled average rating for the exploration. scaled_average_rating = ndb.FloatProperty(indexed=True) # Time when the exploration model was last updated (not to be # confused with last_updated, which is the time when the # exploration *summary* model was last updated). exploration_model_last_updated = ndb.DateTimeProperty(indexed=True) # Time when the exploration model was created (not to be confused # with created_on, which is the time when the exploration *summary* # model was created). exploration_model_created_on = ndb.DateTimeProperty(indexed=True) # Time when the exploration was first published. first_published_msec = ndb.FloatProperty(indexed=True) # The publication status of this exploration. status = ndb.StringProperty( default=constants.ACTIVITY_STATUS_PRIVATE, indexed=True, choices=[ constants.ACTIVITY_STATUS_PRIVATE, constants.ACTIVITY_STATUS_PUBLIC ] ) # Whether this exploration is owned by the community. community_owned = ndb.BooleanProperty(required=True, indexed=True) # The user_ids of owners of this exploration. owner_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to edit this exploration. editor_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to voiceover this exploration. voice_artist_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to view this exploration. viewer_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who have contributed (humans who have made a # positive (not just a revert) change to the exploration's content). contributor_ids = ndb.StringProperty(indexed=True, repeated=True) # A dict representing the contributors of non-trivial commits to this # exploration. Each key of this dict is a user_id, and the corresponding # value is the number of non-trivial commits that the user has made. contributors_summary = ndb.JsonProperty(default={}, indexed=False) # The version number of the exploration after this commit. Only populated # for commits to an exploration (as opposed to its rights, etc.). version = ndb.IntegerProperty() # DEPRECATED in v2.8.3. Do not use. translator_ids = ndb.StringProperty(indexed=True, repeated=True) @staticmethod def get_deletion_policy(): """Exploration summary is deleted only if the corresponding exploration is not public. """ return base_models.DELETION_POLICY.KEEP_IF_PUBLIC @classmethod def has_reference_to_user_id(cls, user_id): """Check whether ExpSummaryModel references user. Args: user_id: str. The ID of the user whose data should be checked. Returns: bool. Whether any models refer to the given user ID. """ return cls.query(ndb.OR( cls.owner_ids == user_id, cls.editor_ids == user_id, cls.voice_artist_ids == user_id, cls.viewer_ids == user_id, cls.contributor_ids == user_id )).get(keys_only=True) is not None @staticmethod def get_user_id_migration_policy(): """ExpSummaryModel has multiple fields with user ID.""" return base_models.USER_ID_MIGRATION_POLICY.CUSTOM @classmethod def migrate_model(cls, old_user_id, new_user_id): """Migrate model to use the new user ID in the owner_ids, editor_ids, voice_artist_ids, viewer_ids and contributor_ids. Args: old_user_id: str. The old user ID. new_user_id: str. The new user ID. """ migrated_models = [] for model in cls.query(ndb.OR( cls.owner_ids == old_user_id, cls.editor_ids == old_user_id, cls.voice_artist_ids == old_user_id, cls.viewer_ids == old_user_id, cls.contributor_ids == old_user_id)).fetch(): model.owner_ids = [ new_user_id if owner_id == old_user_id else owner_id for owner_id in model.owner_ids] model.editor_ids = [ new_user_id if editor_id == old_user_id else editor_id for editor_id in model.editor_ids] model.voice_artist_ids = [ new_user_id if voice_art_id == old_user_id else voice_art_id for voice_art_id in model.voice_artist_ids] model.viewer_ids = [ new_user_id if viewer_id == old_user_id else viewer_id for viewer_id in model.viewer_ids] model.contributor_ids = [ new_user_id if contributor_id == old_user_id else contributor_id for contributor_id in model.contributor_ids] migrated_models.append(model) cls.put_multi(migrated_models, update_last_updated_time=False) @classmethod def get_non_private(cls): """Returns an iterable with non-private ExpSummary models. Returns: iterable. An iterable with non-private ExpSummary models. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status != constants.ACTIVITY_STATUS_PRIVATE ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT) @classmethod def get_top_rated(cls, limit): """Fetches the top-rated exp summaries that are public in descending order of scaled_average_rating. Args: limit: int. The maximum number of results to return. Returns: iterable. An iterable with the top rated exp summaries that are public in descending order of scaled_average_rating. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status == constants.ACTIVITY_STATUS_PUBLIC ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).order( -ExpSummaryModel.scaled_average_rating ).fetch(limit) @classmethod def get_private_at_least_viewable(cls, user_id): """Fetches private exp summaries that are at least viewable by the given user. Args: user_id: The id of the given user. Returns: iterable. An iterable with private exp summaries that are at least viewable by the given user. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status == constants.ACTIVITY_STATUS_PRIVATE ).filter( ndb.OR(ExpSummaryModel.owner_ids == user_id, ExpSummaryModel.editor_ids == user_id, ExpSummaryModel.voice_artist_ids == user_id, ExpSummaryModel.viewer_ids == user_id) ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT) @classmethod def get_at_least_editable(cls, user_id): """Fetches exp summaries that are at least editable by the given user. Args: user_id: The id of the given user. Returns: iterable. An iterable with exp summaries that are at least editable by the given user. """ return ExpSummaryModel.query().filter( ndb.OR(ExpSummaryModel.owner_ids == user_id, ExpSummaryModel.editor_ids == user_id) ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT) @classmethod def get_recently_published(cls, limit): """Fetches exp summaries that are recently published. Args: limit: int. The maximum number of results to return. Returns: An iterable with exp summaries that are recently published. The returned list is sorted by the time of publication with latest being first in the list. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status == constants.ACTIVITY_STATUS_PUBLIC ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).order( -ExpSummaryModel.first_published_msec ).fetch(limit) def verify_model_user_ids_exist(self): """Check if UserSettingsModel exists for all the ids in owner_ids, editor_ids, voice_artist_ids, viewer_ids and contributor_ids. """ user_ids = (self.owner_ids + self.editor_ids + self.voice_artist_ids + self.viewer_ids + self.contributor_ids) user_ids = [user_id for user_id in user_ids if user_id != feconf.SYSTEM_COMMITTER_ID] user_settings_models = user_models.UserSettingsModel.get_multi( user_ids, include_deleted=True) return all(model is not None for model in user_settings_models)
from django.contrib.auth.decorators import login_required from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from django.db.models import Sum, Q, Min, CharField, Value as V from django.db.models.functions import Concat from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, JsonResponse from django.template import loader from django.urls import reverse from django.views.decorators.http import require_http_methods from NearBeach.forms import AddBugForm, AddCustomerForm, AddGroupForm, AddObjectLinkForm, AddNoteForm, AddTagsForm, AddUserForm, User, DeleteTagForm, SearchForm, QueryBugClientForm from NearBeach.views.tools.internal_functions import set_object_from_destination, project, task, requirement, requirement_item, get_object_from_destination, opportunity, organisation from NearBeach.models import bug, object_assignment, group, object_note, tag, tag_assignment, permission_set, bug_client, customer, user_group, list_of_requirement_status, list_of_requirement_item_status import json, urllib, urllib3 @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def add_bug(request, destination, location_id): #ADD IN CHECK PERMISSIONS THAT USES THE DESTINATION AND LOCATION! # Get data from form form = AddBugForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Save the data submit_bug = bug( bug_client=form.cleaned_data['bug_client'], bug_code=form.cleaned_data['bug_id'], bug_description=form.cleaned_data['bug_description'], bug_status=form.cleaned_data['bug_status'], change_user=request.user, ) # Connect to the correct destination submit_bug = set_object_from_destination(submit_bug, destination, location_id) # Save submit_bug.save() # Get new bug to send back to use bug_results = bug.objects.filter(bug_id=submit_bug.bug_id) # Return the JSON data return HttpResponse(serializers.serialize('json', bug_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def add_customer(request, destination, location_id): #ADD IN CHECK PERMISSIONS THAT USES THE DESTINATION AND LOCATION! # Get data from form form = AddCustomerForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Obtain the data dependent on the destination submit_object_assignment = object_assignment( change_user=request.user, customer=form.cleaned_data['customer'] ) submit_object_assignment = set_object_from_destination( submit_object_assignment, destination, location_id ) # Save the data submit_object_assignment.save() customer_results = get_customer_list(destination, location_id) return HttpResponse(serializers.serialize('json', customer_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def add_group(request, destination, location_id): # ADD IN CHECK PERMISSIONS THAT USES THE DESTINATION AND LOCATION! # Get data from form form = AddGroupForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # We loop through the responses and add them to the destination's object association group_list = request.POST.getlist('group_list') for single_group in group_list: # Get group instance group_instance = group.objects.get(group_id=single_group) # Construct the object assignment submit_object_assignment = object_assignment( group_id=group_instance, change_user=request.user, ) submit_object_assignment = set_object_from_destination(submit_object_assignment, destination, location_id) # Save the data submit_object_assignment.save() # Get the new group list data group_results = get_group_list(destination, location_id) return HttpResponse(serializers.serialize('json', group_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def add_link(request, destination, location_id): """ :param request: :param destination: :param location_id: :return: """ # ADD IN CHECKER FOR USER PERMISSIONS # Get the data form = AddObjectLinkForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Start saving the data object_assignment_submit = object_assignment( change_user=request.user, ) # Add the destination/location_id to the object object_assignment_submit = link_object(object_assignment_submit, destination, location_id) # Loop through the results and add them in. for row in request.POST.getlist("project"): submit_object_assignment = object_assignment( project=project.objects.get(project_id=row), change_user=request.user, ) set_object_from_destination(submit_object_assignment, destination, location_id) submit_object_assignment.save() for row in request.POST.getlist("task"): submit_object_assignment = object_assignment( task=task.objects.get(task_id=row), change_user=request.user, ) set_object_from_destination(submit_object_assignment, destination, location_id) submit_object_assignment.save() for row in request.POST.getlist("requirement"): submit_object_assignment = object_assignment( requirement=requirement.objects.get(requirement_id=row), change_user=request.user, ) set_object_from_destination(submit_object_assignment, destination, location_id) submit_object_assignment.save() for row in request.POST.getlist("requirement_item"): submit_object_assignment = object_assignment( requirement_item=requirement_item.objects.get(requirement_item_id=row), change_user=request.user, ) set_object_from_destination(submit_object_assignment, destination, location_id) submit_object_assignment.save() return HttpResponse("Success") @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def add_notes(request, destination, location_id): # ADD IN PERMISSIONS HERE! # Fill out the form form = AddNoteForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # SAVE DATA submit_object_note = object_note( change_user = request.user, object_note = form.cleaned_data['note'] ) submit_object_note = set_object_from_destination( submit_object_note, destination, location_id ) submit_object_note.save() # Get data to send back to user note_resuts = object_note.objects.filter(object_note_id=submit_object_note.object_note_id) return HttpResponse(serializers.serialize('json', note_resuts), content_type='application.json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def add_tags(request, destination, location_id): #Check the data against the form form = AddTagsForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Loop throgh each tag tag_list = request.POST.getlist("tag_id") for single_tag in tag_list: # Grab the tag instance tag_instance = tag.objects.get(tag_id=single_tag) submit_tag_assignment = tag_assignment( tag=tag_instance, object_enum=destination, object_id=location_id, change_user=request.user, ) submit_tag_assignment.save() # Return all tags associated with the destination/locationid tag_results = tag.objects.filter( is_deleted=False, tag_id__in=tag_assignment.objects.filter( is_deleted=False, object_enum=destination, object_id=location_id, ).values('tag_id') ) return HttpResponse( serializers.serialize('json', tag_results), content_type='application/json', ) @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def add_user(request, destination, location_id): # ADD IN A CHECK TO CHECK USER'S PERMISSION! # Check the data against the form form = AddUserForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Extract the list of users from the POST data user_list = request.POST.getlist('user_list') # Loop through them and add them to the object assignment for single_user in user_list: # Get user instance user_instance = User.objects.get(id=single_user) # Create object assignment submit_object_assignment = object_assignment( change_user=request.user, assigned_user=user_instance, ) submit_object_assignment = set_object_from_destination(submit_object_assignment, destination, location_id) # Save submit_object_assignment.save() # Get the data to return to the user user_results = get_user_list(destination, location_id) return HttpResponse(user_results, content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def admin_add_user(request): """ :param request: :return: """ # Make sure user has permissions # Get data group_results = group.objects.filter( is_deleted=False, ).values() permission_set_results = permission_set.objects.filter( is_deleted=False, ).values() user_results = User.objects.filter( is_active=True, ).values() # Convert data to json format group_results = json.dumps(list(group_results), cls=DjangoJSONEncoder) permission_set_results = json.dumps(list(permission_set_results), cls=DjangoJSONEncoder) user_results = json.dumps(list(user_results), cls=DjangoJSONEncoder) return_data = { 'group_results': json.loads(group_results), 'permission_set_results': json.loads(permission_set_results), 'user_results': json.loads(user_results), } return JsonResponse(return_data) @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def associated_objects(request, destination, location_id): """ :param request: :param destination: :param location_id: :return: """ # Organisations have a special method. We will return the results directly from this method to the user. if destination == 'organisation': return associated_objects_organisations(location_id) # Get the data object_assignment_results = object_assignment.objects.filter( is_deleted=False, ) object_assignment_results = get_object_from_destination(object_assignment_results, destination, location_id) opportunity_results = opportunity.objects.filter( is_deleted=False, opportunity_id__in=object_assignment_results.filter( opportunity_id__isnull=False ).values('opportunity_id') ).values() project_results = project.objects.filter( is_deleted=False, project_id__in=object_assignment_results.filter( project_id__isnull=False ).values('project_id') ).values() requirement_results = requirement.objects.filter( is_deleted=False, requirement_id__in=object_assignment_results.filter( requirement_id__isnull=False ).values('requirement_id') ).values() task_results = task.objects.filter( is_deleted=False, task_id__in=object_assignment_results.filter( task_id__isnull=False ).values('task_id') ).values() # Return the JSON Response back - which will return strait to the user return JsonResponse({ 'opportunity': list(opportunity_results), 'project': list(project_results), 'requirement': list(requirement_results), 'task': list(task_results), }) # Internal Functions def associated_objects_organisations(location_id): """ Due to organisation's links being connected to the objects directly. We will need to query all the objects that can be related to an organisation, and combine them into one JSON output. Please note - opportunities are the exception here - hence they are utilising the object assignment table. To make it JSON friendly, we have to add .values() to each object lookup, and then simple list them in the JSON return function below. :param location_id: :return: """ # Get the data opportunity_results = opportunity.objects.filter( is_deleted=False, opportunity_id__in=object_assignment.objects.filter( is_deleted=False, opportunity_id__isnull=False, organisation_id=location_id, ).values('opportunity_id') ).values() project_results = project.objects.filter( is_deleted=False, organisation__in=location_id, ).values() requirement_results = requirement.objects.filter( is_deleted=False, organisation__in=location_id, ).values() task_results = task.objects.filter( is_deleted=False, organisation__in=location_id, ).values() # Return the JSON Response back - which will return strait to the user return JsonResponse({ 'opportunity': list(opportunity_results), 'project': list(project_results), 'requirement': list(requirement_results), 'task': list(task_results), }) @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def bug_client_list(request): bug_client_results = bug_client.objects.filter( is_deleted=False, ) return HttpResponse(serializers.serialize('json', bug_client_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def bug_list(request, destination, location_id): # Obtain the data dependent on the destination bug_list = bug.objects.filter( is_deleted=False, ) bug_list = get_object_from_destination(bug_list, destination, location_id) # Limit to certain values bug_list = bug_list.values( 'bug_client', 'bug_client__list_of_bug_client', 'bug_client__list_of_bug_client__bug_client_name', 'bug_client__bug_client_name', 'bug_client__bug_client_url', 'bug_code', 'bug_description', 'bug_status', "project_id", "requirement_id", "task_id", ) """ As explained on stack overflow here - https://stackoverflow.com/questions/7650448/django-serialize-queryset-values-into-json#31994176 We need to Django's serializers can't handle a ValuesQuerySet. However, you can serialize by using a standard json.dumps() and transforming your ValuesQuerySet to a list by using list().[sic] """ # Send back json data json_results = json.dumps(list(bug_list), cls=DjangoJSONEncoder) return HttpResponse(json_results, content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def customer_list(request, destination, location_id): customer_results = get_customer_list(destination, location_id) return HttpResponse(serializers.serialize('json', customer_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def customer_list_all(request, destination, location_id): # Get the organisation dependant on the destination source if destination == "requirement": organisation_results = organisation.objects.get( organisation_id=requirement.objects.get( is_deleted=False, requirement_id=location_id, ).organisation_id ) elif destination == "requirement_item": organisation_results = organisation.objects.get( organisation_id=requirement.objects.get( is_deleted=False, requirement_id=requirement_item.objects.get( requirement_item_id=location_id ).requirement_id, ).organisation_id ) elif destination == "project": organisation_results = organisation.objects.get( organisation_id=project.objects.get( is_deleted=False, project_id=location_id, ).organisation_id ) elif destination == "task": organisation_results = organisation.objects.get( organisation_id=task.objects.get( is_deleted=False, task_id=location_id, ).organisation_id ) else: # There is no destination that could match this. Send user to errors return HttpResponseBadRequest("Sorry - there was an error getting the Customer List") customer_results = customer.objects.filter( is_deleted=False, organisation_id=organisation_results.organisation_id ) return HttpResponse(serializers.serialize('json', customer_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def delete_tag(request): # Get form data form = DeleteTagForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Update/Delete tag associations tag_assignment.objects.filter( is_deleted=False, tag_id=form.cleaned_data['tag'], object_enum=form.cleaned_data['object_enum'], object_id=form.cleaned_data['object_id'] ).update( is_deleted=True, ) # Ok - return blank return HttpResponse("") # Internal function def get_customer_list(destination, location_id): # Get a list of all objects assignments dependant on the destination object_customers = object_assignment.objects.filter( is_deleted=False, customer_id__isnull=False, ) object_customers = get_object_from_destination(object_customers, destination, location_id) return customer.objects.filter( is_deleted=False, customer_id__in=object_customers.values('customer_id') ) # Internal function def get_group_list(destination, location_id): object_results = object_assignment.objects.filter( is_deleted=False, ) object_results = get_object_from_destination( object_results, destination, location_id ) # Now return the groups return group.objects.filter( is_deleted=False, group_id__in=object_results.values('group_id') ) # Internal Function def get_user_list(destination, location_id): # Get the data we want object_results = object_assignment.objects.filter( is_deleted=False, assigned_user_id__isnull=False, ) object_results = get_object_from_destination( object_results, destination, location_id ) # Get the user details user_results = User.objects.filter( id__in=object_results.values('assigned_user_id') ).values( 'id', 'username', 'first_name', 'last_name', 'email', ) return json.dumps(list(user_results), cls=DjangoJSONEncoder) # Internal Function def get_user_list_all(destination, location_id): # Get a list of users we want to exclude object_results = object_assignment.objects.filter( is_deleted=False, assigned_user_id__isnull=False, ) object_results = get_object_from_destination( object_results, destination, location_id ) # Get a list of all the groups associated with this destination group_results = object_assignment.objects.filter( is_deleted=False, group_id__isnull=False, ) group_results = get_object_from_destination(group_results, destination, location_id) # Get a list of users who are associated with these groups & not in the excluded list user_results = User.objects.filter( id__in=user_group.objects.filter( is_deleted=False, group_id__in=group_results.values('group_id'), ).values('username_id'), is_active=True, ).exclude( id__in=object_results.values('assigned_user_id') ) # Send the results back return user_results @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def group_list(request, destination, location_id): # Get the data dependant on the object lookup group_results = get_group_list(destination, location_id) # Return the data return HttpResponse(serializers.serialize('json', group_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def group_list_all(request, destination, location_id): # ADD CHECKS FOR USER PERMISSIONS! # Obtain data group_existing_results = object_assignment.objects.filter( is_deleted=False, group_id__isnull=False, ) group_existing_results = get_object_from_destination(group_existing_results, destination, location_id) group_results = group.objects.filter( is_deleted=False, ).exclude( group_id__in=group_existing_results.values('group_id') ) # Return data as json return HttpResponse(serializers.serialize('json', group_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def lead_user_list(request): """ :param request: :return: """ # Get the data search_form = SearchForm(request.POST) if not search_form.is_valid(): return HttpResponseBadRequest(search_form.errors) # First we create a search string and annotate it onto our results user_results = User.objects.annotate( search_string=Concat( 'username', V(' '), 'first_name', V(' '), 'last_name', V(' '), 'email', output_field=CharField() ) ).filter( is_active=True, ) for split_row in search_form.cleaned_data['search'].split(' '): """ """ user_results.filter( search_string__icontains=split_row, ) # Return the json data return HttpResponse(serializers.serialize('json', user_results[:25]), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def link_list(request, destination, location_id, object_lookup): # Get the data dependent on the object lookup if object_lookup == 'project': data_results = project.objects.filter( is_deleted=False, ).exclude( project_status='Closed', ) elif object_lookup == "task": data_results = task.objects.filter( is_deleted=False, ).exclude( task_status='Closed', ) elif object_lookup == "requirement": data_results = requirement.objects.filter( is_deleted=False, requirement_status_id__in=list_of_requirement_status.objects.filter( is_deleted=False, requirement_status_is_closed=False, ).values('requirement_status_id'), ) elif object_lookup == "requirement_item": data_results = requirement_item.objects.filter( is_deleted=False, requirement_item_status_id__in=list_of_requirement_item_status.objects.filter( is_deleted=False, status_is_closed=False, ).values('requirement_item_status_id'), requirement_id__in=requirement.objects.filter( is_deleted=False, requirement_status_id__in=list_of_requirement_status.objects.filter( is_deleted=False, requirement_status_is_closed=False, ).values('requirement_status_id') ).values('requirement_id'), ) else: # There is an error. return HttpResponseBadRequest("Sorry - but that object lookup does not exist") # Send the data to the user return HttpResponse(serializers.serialize('json', data_results), content_type='application/json') # Internal function def link_object(object_assignment_submit, destination, location_id): """ This is an internal function - depending on the destination, depends on what we are linking in the object_association_submit :param object_assignment_submit: :param destination: :param location_id: :return: """ if destination == "project": object_assignment_submit.project = project.objects.get(project_id=location_id) elif destination == "requirement": object_assignment_submit.requirement = requirement.objects.get(requirement_id=location_id) elif destination == "requirement_item": object_assignment_submit.requirement_item = requirement_item.objects.get(requirement_item_id=location_id) elif destination == "task": object_assignment_submit.task = task.objects.get(task_id=location_id) # Return the results return object_assignment_submit @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def note_list(request, destination, location_id): # Everyone should have access to the notes section. # Get the notes dependent on the user destination and location note_results = object_note.objects.filter( is_deleted=False, ) # Filter by destination and location_id note_results = get_object_from_destination(note_results, destination, location_id) # Return JSON results return HttpResponse(serializers.serialize('json', note_results), content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def object_link_list(request, destination, location_id): """ :param request: :param destination: :param location_id: :return: """ object_assignment_results = object_assignment.objects.filter( is_deleted=False, ) object_assignment_results = get_object_from_destination(object_assignment_results, destination, location_id) object_assignment_results = object_assignment_results.filter( Q(project__isnull=False) | Q(requirement__isnull=False) | Q(requirement_item__isnull=False) | Q(task__isnull=False) ).values( 'project_id', 'project_id__project_name', 'project_id__project_status', 'task_id', 'task_id__task_short_description', 'task_id__task_status', 'requirement_id', 'requirement_id__requirement_title', 'requirement_id__requirement_status__requirement_status', 'requirement_item_id', 'requirement_item_id__requirement_item_title', 'requirement_item_id__requirement_item_status__requirement_item_status', ) """ As explained on stack overflow here - https://stackoverflow.com/questions/7650448/django-serialize-queryset-values-into-json#31994176 We need to Django's serializers can't handle a ValuesQuerySet. However, you can serialize by using a standard json.dumps() and transforming your ValuesQuerySet to a list by using list().[sic] """ # Send back json data json_results = json.dumps(list(object_assignment_results), cls=DjangoJSONEncoder) return HttpResponse(json_results, content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def query_bug_client(request, destination, location_id): # Insert data into form form = QueryBugClientForm(request.POST) # Check to make sure everything is fine with the form if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Extract the information from the form bug_client_instance = form.cleaned_data['bug_client_id'] search_terms = form.cleaned_data['search'] # Get existing bugs that we want to extract out existing_bugs = bug.objects.filter( is_deleted=False, bug_client_id=bug_client_instance.bug_client_id, ) existing_bugs = get_object_from_destination(existing_bugs, destination, location_id) # The values in the URL f_bugs = '' o_notequals = '' v_values = '' # The for loop for idx, row in enumerate(existing_bugs): nidx = str(idx + 1) f_bugs = f_bugs + "&f" + nidx + "=bug_id" o_notequals = o_notequals + "&o" + nidx + "=notequals" v_values = v_values + "&v" + nidx + "=" + str(row.bug_code) exclude_url = f_bugs + o_notequals + v_values url = bug_client_instance.bug_client_url \ + bug_client_instance.list_of_bug_client.bug_client_api_url \ + bug_client_instance.list_of_bug_client.api_search_bugs \ + urllib.parse.quote(form.cleaned_data['search']) \ + exclude_url """ SECURITY ISSUE ~~~~~~~~~~~~~~ The URL could contain a file. Which we do not want executed by mistake. So we just make sure that the URL starts with a http instead of ftp or file. We place the at the end of the json_data because we have checked the field. This should be just a json response. If it is not at this point then it will produce a server issue. """ if url.lower().startswith('http'): # setup the pool manager for urllib3 http = urllib3.PoolManager() # Plug in the url r = http.request('GET', url) # Extract the data json_data = json.loads(r.data.decode('utf-8')) else: raise ValueError from None # Send back the JSON data return JsonResponse(json_data['bugs'], safe=False) @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def tag_list(request, destination, location_id): # Get the data we want tag_results = tag.objects.filter( is_deleted=False, tag_id__in=tag_assignment.objects.filter( is_deleted=False, object_enum=destination, object_id=location_id, ).values('tag_id') ) return HttpResponse( serializers.serialize('json', tag_results), content_type='application/json', ) @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def tag_list_all(request): # Get the data we want tag_results = tag.objects.filter( is_deleted=False, ) return HttpResponse( serializers.serialize('json', tag_results), content_type='application/json', ) @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def user_list(request, destination, location_id): # Get the data we want user_results = get_user_list(destination, location_id) return HttpResponse(user_results, content_type='application/json') @require_http_methods(['POST']) @login_required(login_url='login', redirect_field_name="") def user_list_all(request, destination, location_id): # ADD IN PERMISSIONS LATER # Get Data we want user_results = get_user_list_all(destination, location_id) return HttpResponse(serializers.serialize('json', user_results), content_type='application/json')
from typing import Optional from dataclasses import dataclass from .Address import Address from .TaxNumber import TaxNumber @dataclass class SupplierInfo: """Invoice supplier (seller) data :param supplier_tax_number: Tax number or group identification number :param group_member_tax_number: Tax number of group member, when the supply of goods or services is done under group identification number :param community_vat_number: Community tax number :param supplier_name: Name of the seller (supplier) :param supplier_address: Address of the seller (supplier) :param supplier_bank_account_number: Bank account number of the seller (supplier) :param individual_exemption: Value is true if the seller (supplier) is individually exempted from VAT :param excise_licence_num: Number of supplier’s tax warehouse license or excise license (Act LXVIII of 2016) """ supplier_tax_number: TaxNumber group_member_tax_number: Optional[TaxNumber] community_vat_number: Optional[str] supplier_name: str supplier_address: Address supplier_bank_account_number: Optional[str] individual_exemption: Optional[bool] excise_licence_num: Optional[str]
'use strict'; /*jshint expr: true*/ var expect = require('chai').expect; var slowEquals = require('../index.js'); describe('slowEquals', function () { it('should return true with equal strings', function () { expect( slowEquals('abc', 'abc') ).to.be.true; }); it('should return false with different length strings', function () { expect( slowEquals('abc', 'abcd') ).to.be.false; expect( slowEquals('abcd', 'abc') ).to.be.false; }); it('should return false with equal length strings with different characters', function () { expect( slowEquals('abcd', 'abce') ).to.be.false; expect( slowEquals('abce', 'abcd') ).to.be.false; expect( slowEquals('abcd', 'Abcd') ).to.be.false; expect( slowEquals('Abcd', 'abcd') ).to.be.false; }); });
const chart = require('../../../../models/event') module.exports = async function getPropertyCountBySpaname(req, res) { try { const propertyCountBySpanameResponse = await chart.aggregate([ { '$group': { '_id': { 'propertyName': '$propertyName', 'spaName': '$spaName' }, 'count': { '$sum': 1 } }, }, { '$project': { '_id': 0, 'propertyName': '$_id.propertyName', 'spaName': '$_id.spaName', 'count': '$count' } }, { $sort: { propertyName: 1, spaName: 1 } } ]); let i = 1; propertyCountBySpanameResponse.forEach((item) => { item.id = i++; }); res.status(200).json(propertyCountBySpanameResponse); } catch (e) { return { "Error": e }; } }
const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8'); const linesSorted = input.split('\n').sort(); const EventType = { START: 1, SLEEP: 2, WAKE: 3, }; let guardId = ''; const events = linesSorted.map(line => { const timestamp = line.substr(0, line.indexOf(']') + 1); let eventType = 0; if (line.indexOf('falls asleep') !== -1) { eventType = EventType.SLEEP; } else if (line.indexOf('wakes up') !== -1) { eventType = EventType.WAKE; } else if (line.indexOf('begins shift') !== -1) { eventType = EventType.START; guardId = line.split(' ')[3].replace('#', ''); } else { throw new Error(`Unexpected event in line: ${line}`); } const [hour, minute] = timestamp.split(' ')[1].replace(']', '').split(':'); return { eventType, guardId: parseInt(guardId), hour: parseInt(hour), minute: parseInt(minute), }; }); const sleepPeriodsForGuard = {}; let sleepTime = 0; events.forEach((event) => { if (!sleepPeriodsForGuard[event.guardId]) { sleepPeriodsForGuard[event.guardId] = []; } if (event.eventType === EventType.SLEEP) { sleepTime = event.minute; } if (event.eventType === EventType.WAKE) { const wakeTime = event.minute; const sleepLength = wakeTime - sleepTime - 1; sleepPeriodsForGuard[event.guardId].push({ sleepTime, wakeTime, sleepLength }); } }); function solveP1() { const sleepTimeForGuard = {}; Object.keys(sleepPeriodsForGuard).forEach((guardId) => { sleepTimeForGuard[guardId] = sleepPeriodsForGuard[guardId].reduce((sum, period) => sum + period.sleepLength, 0); }); let maxSleepTime = 0; let maxGuardId = 0; Object.keys(sleepTimeForGuard).forEach((guardId) => { const sleepTime = sleepTimeForGuard[guardId]; if (sleepTime >= maxSleepTime) { maxSleepTime = sleepTime; maxGuardId = guardId; } }); const timesAsleepForMinute = {}; let maxMinute; sleepPeriodsForGuard[maxGuardId].forEach((sleepPeriod) => { for (let i = sleepPeriod.sleepTime; i < sleepPeriod.wakeTime; i += 1) { if (!timesAsleepForMinute[i]) { timesAsleepForMinute[i] = 1; } else { timesAsleepForMinute[i] += 1; } if (!maxMinute || timesAsleepForMinute[i] > timesAsleepForMinute[maxMinute]) { maxMinute = i; } } }); const solution = maxGuardId * maxMinute; console.log(`Part 1: ${solution}`); } function solveP2() { const timesAsleepForMinutePerGuard = {}; Object.keys(sleepPeriodsForGuard).forEach((guardId) => { if (!timesAsleepForMinutePerGuard[guardId]) { timesAsleepForMinutePerGuard[guardId] = {}; } const timesAsleepForMinute = timesAsleepForMinutePerGuard[guardId]; sleepPeriodsForGuard[guardId].forEach((sleepPeriod) => { for (let i = sleepPeriod.sleepTime; i < sleepPeriod.wakeTime; i += 1) { if (!timesAsleepForMinute[i]) { timesAsleepForMinute[i] = 1; } else { timesAsleepForMinute[i] += 1; } } }); }); let maxGuardId; let maxMinute; let maxTimeAsleep = 0; Object.keys(timesAsleepForMinutePerGuard).forEach((guardId) => { Object.keys(timesAsleepForMinutePerGuard[guardId]).forEach((minute) => { const timeAsleep = timesAsleepForMinutePerGuard[guardId][minute]; if (timeAsleep > maxTimeAsleep) { maxTimeAsleep = timeAsleep; maxMinute = minute; maxGuardId = guardId; } }); }); const solution = maxGuardId * maxMinute; console.log(`Part 2: ${solution}`); } solveP1(); solveP2();
/* eslint-disable no-console */ import { Meteor } from 'meteor/meteor'; export default (url) => { return () => { Meteor.call('callTraktAPI', url, (error, { data }) => { if (error) { console.log('this is erorr'); console.log(error); } else { console.log(data); } }); }; };
/** * Created by kling on 9/28/16. */ 'use strict'; export default class AppController { static get $inject() { return ['$mdSidenav', 'AuthService']; } constructor($mdSidenav, authService) { this.$mdSidenav = $mdSidenav; this.authService = authService; } toggleNav() { this.$mdSidenav('left').toggle(); } logout() { this.authService.logout(); } }