{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); ';\r\n try {\r\n this.myIFrame.doc.open();\r\n this.myIFrame.doc.write(iframeContents);\r\n this.myIFrame.doc.close();\r\n }\r\n catch (e) {\r\n log('frame writing exception');\r\n if (e.stack) {\r\n log(e.stack);\r\n }\r\n log(e);\r\n }\r\n }\r\n }\r\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n */\r\n static createIFrame_() {\r\n const iframe = document.createElement('iframe');\r\n iframe.style.display = 'none';\r\n // This is necessary in order to initialize the document inside the iframe\r\n if (document.body) {\r\n document.body.appendChild(iframe);\r\n try {\r\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\r\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\r\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\r\n const a = iframe.contentWindow.document;\r\n if (!a) {\r\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\r\n log('No IE domain setting required');\r\n }\r\n }\r\n catch (e) {\r\n const domain = document.domain;\r\n iframe.src =\r\n \"javascript:void((function(){document.open();document.domain='\" +\r\n domain +\r\n \"';document.close();})())\";\r\n }\r\n }\r\n else {\r\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\r\n // never gets hit.\r\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\r\n }\r\n // Get the document of the iframe in a browser-specific way.\r\n if (iframe.contentDocument) {\r\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\r\n }\r\n else if (iframe.contentWindow) {\r\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (iframe.document) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n iframe.doc = iframe.document; //others?\r\n }\r\n return iframe;\r\n }\r\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\n */\r\n close() {\r\n //Mark this iframe as dead, so no new requests are sent.\r\n this.alive = false;\r\n if (this.myIFrame) {\r\n //We have to actually remove all of the html inside this iframe before removing it from the\r\n //window, or IE will continue loading and executing the script tags we've already added, which\r\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\r\n this.myIFrame.doc.body.innerHTML = '';\r\n setTimeout(() => {\r\n if (this.myIFrame !== null) {\r\n document.body.removeChild(this.myIFrame);\r\n this.myIFrame = null;\r\n }\r\n }, Math.floor(0));\r\n }\r\n // Protect from being called recursively.\r\n const onDisconnect = this.onDisconnect;\r\n if (onDisconnect) {\r\n this.onDisconnect = null;\r\n onDisconnect();\r\n }\r\n }\r\n /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param id - The ID of this connection\r\n * @param pw - The password for this connection\r\n */\r\n startLongPoll(id, pw) {\r\n this.myID = id;\r\n this.myPW = pw;\r\n this.alive = true;\r\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\r\n while (this.newRequest_()) { }\r\n }\r\n /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\r\n newRequest_() {\r\n // We keep one outstanding request open all the time to receive data, but if we need to send data\r\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\r\n // close the old request.\r\n if (this.alive &&\r\n this.sendNewPolls &&\r\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {\r\n //construct our url\r\n this.currentSerial++;\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\r\n let theURL = this.urlFn(urlParams);\r\n //Now add as much data as we can.\r\n let curDataString = '';\r\n let i = 0;\r\n while (this.pendingSegs.length > 0) {\r\n //first, lets see if the next segment will fit.\r\n const nextSeg = this.pendingSegs[0];\r\n if (nextSeg.d.length +\r\n SEG_HEADER_SIZE +\r\n curDataString.length <=\r\n MAX_URL_DATA_SIZE) {\r\n //great, the segment will fit. Lets append it.\r\n const theSeg = this.pendingSegs.shift();\r\n curDataString =\r\n curDataString +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\r\n i +\r\n '=' +\r\n theSeg.seg +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\r\n i +\r\n '=' +\r\n theSeg.ts +\r\n '&' +\r\n FIREBASE_LONGPOLL_DATA_PARAM +\r\n i +\r\n '=' +\r\n theSeg.d;\r\n i++;\r\n }\r\n else {\r\n break;\r\n }\r\n }\r\n theURL = theURL + curDataString;\r\n this.addLongPollTag_(theURL, this.currentSerial);\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\r\n enqueueSegment(segnum, totalsegs, data) {\r\n //add this to the queue of segments to send.\r\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\r\n //send the data immediately if there isn't already data being transmitted, unless\r\n //startLongPoll hasn't been called yet.\r\n if (this.alive) {\r\n this.newRequest_();\r\n }\r\n }\r\n /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param url - The URL of the script tag.\r\n * @param serial - The serial number of the request.\r\n */\r\n addLongPollTag_(url, serial) {\r\n //remember that we sent this request.\r\n this.outstandingRequests.add(serial);\r\n const doNewRequest = () => {\r\n this.outstandingRequests.delete(serial);\r\n this.newRequest_();\r\n };\r\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\r\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\r\n const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\r\n const readyStateCB = () => {\r\n // Request completed. Cancel the keepalive.\r\n clearTimeout(keepaliveTimeout);\r\n // Trigger a new request so we can continue receiving data.\r\n doNewRequest();\r\n };\r\n this.addTag(url, readyStateCB);\r\n }\r\n /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param url - The URL for the script tag source.\r\n * @param loadCB - A callback to be triggered once the script has loaded.\r\n */\r\n addTag(url, loadCB) {\r\n {\r\n setTimeout(() => {\r\n try {\r\n // if we're already closed, don't add this poll\r\n if (!this.sendNewPolls) {\r\n return;\r\n }\r\n const newScript = this.myIFrame.doc.createElement('script');\r\n newScript.type = 'text/javascript';\r\n newScript.async = true;\r\n newScript.src = url;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange =\r\n function () {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const rstate = newScript.readyState;\r\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange = null;\r\n if (newScript.parentNode) {\r\n newScript.parentNode.removeChild(newScript);\r\n }\r\n loadCB();\r\n }\r\n };\r\n newScript.onerror = () => {\r\n log('Long-poll script failed to load: ' + url);\r\n this.sendNewPolls = false;\r\n this.close();\r\n };\r\n this.myIFrame.doc.body.appendChild(newScript);\r\n }\r\n catch (e) {\r\n // TODO: we should make this error visible somehow\r\n }\r\n }, Math.floor(1));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\r\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\r\nlet WebSocketImpl = null;\r\nif (typeof MozWebSocket !== 'undefined') {\r\n WebSocketImpl = MozWebSocket;\r\n}\r\nelse if (typeof WebSocket !== 'undefined') {\r\n WebSocketImpl = WebSocket;\r\n}\r\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n */\r\nclass WebSocketConnection {\r\n /**\r\n * @param connId identifier for this transport\r\n * @param repoInfo The info for the websocket endpoint.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The App Check Token for this client.\r\n * @param authToken The Auth Token for this client.\r\n * @param transportSessionId Optional transportSessionId if this is connecting\r\n * to an existing transport session\r\n * @param lastSessionId Optional lastSessionId if there was a previous\r\n * connection\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.keepaliveTimer = null;\r\n this.frames = null;\r\n this.totalFrames = 0;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.log_ = logWrapper(this.connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken);\r\n this.nodeAdmin = repoInfo.nodeAdmin;\r\n }\r\n /**\r\n * @param repoInfo - The info for the websocket endpoint.\r\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\r\n * @returns connection url\r\n */\r\n static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken) {\r\n const urlParams = {};\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n if (transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\r\n }\r\n if (lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\r\n }\r\n if (appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\r\n }\r\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.onDisconnect = onDisconnect;\r\n this.onMessage = onMessage;\r\n this.log_('Websocket connecting to ' + this.connURL);\r\n this.everConnected_ = false;\r\n // Assume failure until proven otherwise.\r\n PersistentStorage.set('previous_websocket_failure', true);\r\n try {\r\n if (isNodeSdk()) ;\r\n else {\r\n const options = {\r\n headers: {\r\n 'X-Firebase-GMPID': this.applicationId || '',\r\n 'X-Firebase-AppCheck': this.appCheckToken || ''\r\n }\r\n };\r\n this.mySock = new WebSocketImpl(this.connURL, [], options);\r\n }\r\n }\r\n catch (e) {\r\n this.log_('Error instantiating WebSocket.');\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n return;\r\n }\r\n this.mySock.onopen = () => {\r\n this.log_('Websocket connected.');\r\n this.everConnected_ = true;\r\n };\r\n this.mySock.onclose = () => {\r\n this.log_('Websocket connection was disconnected.');\r\n this.mySock = null;\r\n this.onClosed_();\r\n };\r\n this.mySock.onmessage = m => {\r\n this.handleIncomingFrame(m);\r\n };\r\n this.mySock.onerror = e => {\r\n this.log_('WebSocket error. Closing connection.');\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n };\r\n }\r\n /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\n */\r\n start() { }\r\n static forceDisallow() {\r\n WebSocketConnection.forceDisallow_ = true;\r\n }\r\n static isAvailable() {\r\n let isOldAndroid = false;\r\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\r\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\r\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\r\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\r\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\r\n isOldAndroid = true;\r\n }\r\n }\r\n }\r\n return (!isOldAndroid &&\r\n WebSocketImpl !== null &&\r\n !WebSocketConnection.forceDisallow_);\r\n }\r\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n */\r\n static previouslyFailed() {\r\n // If our persistent storage is actually only in-memory storage,\r\n // we default to assuming that it previously failed to be safe.\r\n return (PersistentStorage.isInMemoryStorage ||\r\n PersistentStorage.get('previous_websocket_failure') === true);\r\n }\r\n markConnectionHealthy() {\r\n PersistentStorage.remove('previous_websocket_failure');\r\n }\r\n appendFrame_(data) {\r\n this.frames.push(data);\r\n if (this.frames.length === this.totalFrames) {\r\n const fullMess = this.frames.join('');\r\n this.frames = null;\r\n const jsonMess = jsonEval(fullMess);\r\n //handle the message\r\n this.onMessage(jsonMess);\r\n }\r\n }\r\n /**\r\n * @param frameCount - The number of frames we are expecting from the server\r\n */\r\n handleNewFrameCount_(frameCount) {\r\n this.totalFrames = frameCount;\r\n this.frames = [];\r\n }\r\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @returns Any remaining data to be process, or null if there is none\r\n */\r\n extractFrameCount_(data) {\r\n assert(this.frames === null, 'We already have a frame buffer');\r\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\r\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\r\n if (data.length <= 6) {\r\n const frameCount = Number(data);\r\n if (!isNaN(frameCount)) {\r\n this.handleNewFrameCount_(frameCount);\r\n return null;\r\n }\r\n }\r\n this.handleNewFrameCount_(1);\r\n return data;\r\n }\r\n /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess - The frame data\r\n */\r\n handleIncomingFrame(mess) {\r\n if (this.mySock === null) {\r\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\r\n }\r\n const data = mess['data'];\r\n this.bytesReceived += data.length;\r\n this.stats_.incrementCounter('bytes_received', data.length);\r\n this.resetKeepAlive();\r\n if (this.frames !== null) {\r\n // we're buffering\r\n this.appendFrame_(data);\r\n }\r\n else {\r\n // try to parse out a frame count, otherwise, assume 1 and process it\r\n const remainingData = this.extractFrameCount_(data);\r\n if (remainingData !== null) {\r\n this.appendFrame_(remainingData);\r\n }\r\n }\r\n }\r\n /**\r\n * Send a message to the server\r\n * @param data - The JSON object to transmit\r\n */\r\n send(data) {\r\n this.resetKeepAlive();\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //We can only fit a certain amount in each websocket frame, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\r\n //Send the length header\r\n if (dataSegs.length > 1) {\r\n this.sendString_(String(dataSegs.length));\r\n }\r\n //Send the actual data in segments.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.sendString_(dataSegs[i]);\r\n }\r\n }\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.keepaliveTimer) {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = null;\r\n }\r\n if (this.mySock) {\r\n this.mySock.close();\r\n this.mySock = null;\r\n }\r\n }\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is closing itself');\r\n this.shutdown_();\r\n // since this is an internal close, trigger the close listener\r\n if (this.onDisconnect) {\r\n this.onDisconnect(this.everConnected_);\r\n this.onDisconnect = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is being closed');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\r\n resetKeepAlive() {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = setInterval(() => {\r\n //If there has been no websocket activity for a while, send a no-op\r\n if (this.mySock) {\r\n this.sendString_('0');\r\n }\r\n this.resetKeepAlive();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\r\n }\r\n /**\r\n * Send a string over the websocket.\r\n *\r\n * @param str - String to send.\r\n */\r\n sendString_(str) {\r\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\r\n // calls for some unknown reason. We treat these as an error and disconnect.\r\n // See https://app.asana.com/0/58926111402292/68021340250410\r\n try {\r\n this.mySock.send(str);\r\n }\r\n catch (e) {\r\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\r\n setTimeout(this.onClosed_.bind(this), 0);\r\n }\r\n }\r\n}\r\n/**\r\n * Number of response before we consider the connection \"healthy.\"\r\n */\r\nWebSocketConnection.responsesRequiredToBeHealthy = 2;\r\n/**\r\n * Time to wait for the connection te become healthy before giving up.\r\n */\r\nWebSocketConnection.healthyTimeout = 30000;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\r\n * lifecycle.\r\n *\r\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\r\n * they are available.\r\n */\r\nclass TransportManager {\r\n /**\r\n * @param repoInfo - Metadata around the namespace we're connecting to\r\n */\r\n constructor(repoInfo) {\r\n this.initTransports_(repoInfo);\r\n }\r\n static get ALL_TRANSPORTS() {\r\n return [BrowserPollConnection, WebSocketConnection];\r\n }\r\n initTransports_(repoInfo) {\r\n const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\r\n let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\r\n if (repoInfo.webSocketOnly) {\r\n if (!isWebSocketsAvailable) {\r\n warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\r\n }\r\n isSkipPollConnection = true;\r\n }\r\n if (isSkipPollConnection) {\r\n this.transports_ = [WebSocketConnection];\r\n }\r\n else {\r\n const transports = (this.transports_ = []);\r\n for (const transport of TransportManager.ALL_TRANSPORTS) {\r\n if (transport && transport['isAvailable']()) {\r\n transports.push(transport);\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the initial transport to use\r\n */\r\n initialTransport() {\r\n if (this.transports_.length > 0) {\r\n return this.transports_[0];\r\n }\r\n else {\r\n throw new Error('No transports available');\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the next transport, or null\r\n */\r\n upgradeTransport() {\r\n if (this.transports_.length > 1) {\r\n return this.transports_[1];\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Abort upgrade attempt if it takes longer than 60s.\r\nconst UPGRADE_TIMEOUT = 60000;\r\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\r\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\r\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\r\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\r\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\r\n// but we've sent/received enough bytes, we don't cancel the connection.\r\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\r\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\r\nconst MESSAGE_TYPE = 't';\r\nconst MESSAGE_DATA = 'd';\r\nconst CONTROL_SHUTDOWN = 's';\r\nconst CONTROL_RESET = 'r';\r\nconst CONTROL_ERROR = 'e';\r\nconst CONTROL_PONG = 'o';\r\nconst SWITCH_ACK = 'a';\r\nconst END_TRANSMISSION = 'n';\r\nconst PING = 'p';\r\nconst SERVER_HELLO = 'h';\r\n/**\r\n * Creates a new real-time connection to the server using whichever method works\r\n * best in the current browser.\r\n */\r\nclass Connection {\r\n /**\r\n * @param id - an id for this connection\r\n * @param repoInfo_ - the info for the endpoint to connect to\r\n * @param applicationId_ - the Firebase App ID for this project\r\n * @param appCheckToken_ - The App Check Token for this device.\r\n * @param authToken_ - The auth token for this session.\r\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\r\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\r\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\r\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\r\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\r\n */\r\n constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\r\n this.id = id;\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.appCheckToken_ = appCheckToken_;\r\n this.authToken_ = authToken_;\r\n this.onMessage_ = onMessage_;\r\n this.onReady_ = onReady_;\r\n this.onDisconnect_ = onDisconnect_;\r\n this.onKill_ = onKill_;\r\n this.lastSessionId = lastSessionId;\r\n this.connectionCount = 0;\r\n this.pendingDataMessages = [];\r\n this.state_ = 0 /* CONNECTING */;\r\n this.log_ = logWrapper('c:' + this.id + ':');\r\n this.transportManager_ = new TransportManager(repoInfo_);\r\n this.log_('Connection created');\r\n this.start_();\r\n }\r\n /**\r\n * Starts a connection attempt\r\n */\r\n start_() {\r\n const conn = this.transportManager_.initialTransport();\r\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessageReceived = this.connReceiver_(this.conn_);\r\n const onConnectionLost = this.disconnReceiver_(this.conn_);\r\n this.tx_ = this.conn_;\r\n this.rx_ = this.conn_;\r\n this.secondaryConn_ = null;\r\n this.isHealthy_ = false;\r\n /*\r\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\r\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\r\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\r\n * still have the context of your originating frame.\r\n */\r\n setTimeout(() => {\r\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\r\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\r\n }, Math.floor(0));\r\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\r\n if (healthyTimeoutMS > 0) {\r\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\r\n this.healthyTimeout_ = null;\r\n if (!this.isHealthy_) {\r\n if (this.conn_ &&\r\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has received ' +\r\n this.conn_.bytesReceived +\r\n ' bytes. Marking connection healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n else if (this.conn_ &&\r\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has sent ' +\r\n this.conn_.bytesSent +\r\n ' bytes. Leaving connection alive.');\r\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\r\n // the server.\r\n }\r\n else {\r\n this.log_('Closing unhealthy connection after timeout.');\r\n this.close();\r\n }\r\n }\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(healthyTimeoutMS));\r\n }\r\n }\r\n nextTransportId_() {\r\n return 'c:' + this.id + ':' + this.connectionCount++;\r\n }\r\n disconnReceiver_(conn) {\r\n return everConnected => {\r\n if (conn === this.conn_) {\r\n this.onConnectionLost_(everConnected);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.log_('Secondary connection lost.');\r\n this.onSecondaryConnectionLost_();\r\n }\r\n else {\r\n this.log_('closing an old connection');\r\n }\r\n };\r\n }\r\n connReceiver_(conn) {\r\n return (message) => {\r\n if (this.state_ !== 2 /* DISCONNECTED */) {\r\n if (conn === this.rx_) {\r\n this.onPrimaryMessageReceived_(message);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.onSecondaryMessageReceived_(message);\r\n }\r\n else {\r\n this.log_('message on old connection');\r\n }\r\n }\r\n };\r\n }\r\n /**\r\n * @param dataMsg - An arbitrary data message to be sent to the server\r\n */\r\n sendRequest(dataMsg) {\r\n // wrap in a data message envelope and send it on\r\n const msg = { t: 'd', d: dataMsg };\r\n this.sendData_(msg);\r\n }\r\n tryCleanupConnection() {\r\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\r\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\r\n this.conn_ = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n // the server will shutdown the old connection\r\n }\r\n }\r\n onSecondaryControl_(controlData) {\r\n if (MESSAGE_TYPE in controlData) {\r\n const cmd = controlData[MESSAGE_TYPE];\r\n if (cmd === SWITCH_ACK) {\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // Most likely the session wasn't valid. Abandon the switch attempt\r\n this.log_('Got a reset on secondary, closing it');\r\n this.secondaryConn_.close();\r\n // If we were already using this connection for something, than we need to fully close\r\n if (this.tx_ === this.secondaryConn_ ||\r\n this.rx_ === this.secondaryConn_) {\r\n this.close();\r\n }\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on secondary.');\r\n this.secondaryResponsesRequired_--;\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n }\r\n }\r\n onSecondaryMessageReceived_(parsedData) {\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onSecondaryControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n // got a data message, but we're still second connection. Need to buffer it up\r\n this.pendingDataMessages.push(data);\r\n }\r\n else {\r\n throw new Error('Unknown protocol layer: ' + layer);\r\n }\r\n }\r\n upgradeIfSecondaryHealthy_() {\r\n if (this.secondaryResponsesRequired_ <= 0) {\r\n this.log_('Secondary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.secondaryConn_.markConnectionHealthy();\r\n this.proceedWithUpgrade_();\r\n }\r\n else {\r\n // Send a ping to make sure the connection is healthy.\r\n this.log_('sending ping on secondary.');\r\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n proceedWithUpgrade_() {\r\n // tell this connection to consider itself open\r\n this.secondaryConn_.start();\r\n // send ack\r\n this.log_('sending client ack on secondary');\r\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\r\n // send end packet on primary transport, switch to sending on this one\r\n // can receive on this one, buffer responses until end received on primary transport\r\n this.log_('Ending transmission on primary');\r\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\r\n this.tx_ = this.secondaryConn_;\r\n this.tryCleanupConnection();\r\n }\r\n onPrimaryMessageReceived_(parsedData) {\r\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n this.onDataMessage_(data);\r\n }\r\n }\r\n onDataMessage_(message) {\r\n this.onPrimaryResponse_();\r\n // We don't do anything with data messages, just kick them up a level\r\n this.onMessage_(message);\r\n }\r\n onPrimaryResponse_() {\r\n if (!this.isHealthy_) {\r\n this.primaryResponsesRequired_--;\r\n if (this.primaryResponsesRequired_ <= 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n }\r\n }\r\n onControl_(controlData) {\r\n const cmd = requireKey(MESSAGE_TYPE, controlData);\r\n if (MESSAGE_DATA in controlData) {\r\n const payload = controlData[MESSAGE_DATA];\r\n if (cmd === SERVER_HELLO) {\r\n this.onHandshake_(payload);\r\n }\r\n else if (cmd === END_TRANSMISSION) {\r\n this.log_('recvd end transmission on primary');\r\n this.rx_ = this.secondaryConn_;\r\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\r\n this.onDataMessage_(this.pendingDataMessages[i]);\r\n }\r\n this.pendingDataMessages = [];\r\n this.tryCleanupConnection();\r\n }\r\n else if (cmd === CONTROL_SHUTDOWN) {\r\n // This was previously the 'onKill' callback passed to the lower-level connection\r\n // payload in this case is the reason for the shutdown. Generally a human-readable error\r\n this.onConnectionShutdown_(payload);\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // payload in this case is the host we should contact\r\n this.onReset_(payload);\r\n }\r\n else if (cmd === CONTROL_ERROR) {\r\n error('Server Error: ' + payload);\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on primary.');\r\n this.onPrimaryResponse_();\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }\r\n else {\r\n error('Unknown control packet command: ' + cmd);\r\n }\r\n }\r\n }\r\n /**\r\n * @param handshake - The handshake data returned from the server\r\n */\r\n onHandshake_(handshake) {\r\n const timestamp = handshake.ts;\r\n const version = handshake.v;\r\n const host = handshake.h;\r\n this.sessionId = handshake.s;\r\n this.repoInfo_.host = host;\r\n // if we've already closed the connection, then don't bother trying to progress further\r\n if (this.state_ === 0 /* CONNECTING */) {\r\n this.conn_.start();\r\n this.onConnectionEstablished_(this.conn_, timestamp);\r\n if (PROTOCOL_VERSION !== version) {\r\n warn('Protocol version mismatch detected');\r\n }\r\n // TODO: do we want to upgrade? when? maybe a delay?\r\n this.tryStartUpgrade_();\r\n }\r\n }\r\n tryStartUpgrade_() {\r\n const conn = this.transportManager_.upgradeTransport();\r\n if (conn) {\r\n this.startUpgrade_(conn);\r\n }\r\n }\r\n startUpgrade_(conn) {\r\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.secondaryResponsesRequired_ =\r\n conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessage = this.connReceiver_(this.secondaryConn_);\r\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\r\n this.secondaryConn_.open(onMessage, onDisconnect);\r\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\r\n setTimeoutNonBlocking(() => {\r\n if (this.secondaryConn_) {\r\n this.log_('Timed out trying to upgrade.');\r\n this.secondaryConn_.close();\r\n }\r\n }, Math.floor(UPGRADE_TIMEOUT));\r\n }\r\n onReset_(host) {\r\n this.log_('Reset packet received. New host: ' + host);\r\n this.repoInfo_.host = host;\r\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\r\n // We don't currently support resets after the connection has already been established\r\n if (this.state_ === 1 /* CONNECTED */) {\r\n this.close();\r\n }\r\n else {\r\n // Close whatever connections we have open and start again.\r\n this.closeConnections_();\r\n this.start_();\r\n }\r\n }\r\n onConnectionEstablished_(conn, timestamp) {\r\n this.log_('Realtime connection established.');\r\n this.conn_ = conn;\r\n this.state_ = 1 /* CONNECTED */;\r\n if (this.onReady_) {\r\n this.onReady_(timestamp, this.sessionId);\r\n this.onReady_ = null;\r\n }\r\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\r\n // send some pings.\r\n if (this.primaryResponsesRequired_ === 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n }\r\n else {\r\n setTimeoutNonBlocking(() => {\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\r\n }\r\n }\r\n sendPingOnPrimaryIfNecessary_() {\r\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\r\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\r\n this.log_('sending ping on primary.');\r\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n onSecondaryConnectionLost_() {\r\n const conn = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n if (this.tx_ === conn || this.rx_ === conn) {\r\n // we are relying on this connection already in some capacity. Therefore, a failure is real\r\n this.close();\r\n }\r\n }\r\n /**\r\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\r\n * we should flush the host cache\r\n */\r\n onConnectionLost_(everConnected) {\r\n this.conn_ = null;\r\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\r\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\r\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\r\n this.log_('Realtime connection failed.');\r\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\r\n if (this.repoInfo_.isCacheableHost()) {\r\n PersistentStorage.remove('host:' + this.repoInfo_.host);\r\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\r\n this.repoInfo_.internalHost = this.repoInfo_.host;\r\n }\r\n }\r\n else if (this.state_ === 1 /* CONNECTED */) {\r\n this.log_('Realtime connection lost.');\r\n }\r\n this.close();\r\n }\r\n onConnectionShutdown_(reason) {\r\n this.log_('Connection shutdown command received. Shutting down...');\r\n if (this.onKill_) {\r\n this.onKill_(reason);\r\n this.onKill_ = null;\r\n }\r\n // We intentionally don't want to fire onDisconnect (kill is a different case),\r\n // so clear the callback.\r\n this.onDisconnect_ = null;\r\n this.close();\r\n }\r\n sendData_(data) {\r\n if (this.state_ !== 1 /* CONNECTED */) {\r\n throw 'Connection is not connected';\r\n }\r\n else {\r\n this.tx_.send(data);\r\n }\r\n }\r\n /**\r\n * Cleans up this connection, calling the appropriate callbacks\r\n */\r\n close() {\r\n if (this.state_ !== 2 /* DISCONNECTED */) {\r\n this.log_('Closing realtime connection.');\r\n this.state_ = 2 /* DISCONNECTED */;\r\n this.closeConnections_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_();\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n closeConnections_() {\r\n this.log_('Shutting down all connections');\r\n if (this.conn_) {\r\n this.conn_.close();\r\n this.conn_ = null;\r\n }\r\n if (this.secondaryConn_) {\r\n this.secondaryConn_.close();\r\n this.secondaryConn_ = null;\r\n }\r\n if (this.healthyTimeout_) {\r\n clearTimeout(this.healthyTimeout_);\r\n this.healthyTimeout_ = null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\r\nclass ServerActions {\r\n put(pathString, data, onComplete, hash) { }\r\n merge(pathString, data, onComplete, hash) { }\r\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param token - The authentication token\r\n */\r\n refreshAuthToken(token) { }\r\n /**\r\n * Refreshes the app check token for the current connection.\r\n * @param token The app check token\r\n */\r\n refreshAppCheckToken(token) { }\r\n onDisconnectPut(pathString, data, onComplete) { }\r\n onDisconnectMerge(pathString, data, onComplete) { }\r\n onDisconnectCancel(pathString, onComplete) { }\r\n reportStats(stats) { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Base class to be used if you want to emit events. Call the constructor with\r\n * the set of allowed event names.\r\n */\r\nclass EventEmitter {\r\n constructor(allowedEvents_) {\r\n this.allowedEvents_ = allowedEvents_;\r\n this.listeners_ = {};\r\n assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\r\n }\r\n /**\r\n * To be called by derived classes to trigger events.\r\n */\r\n trigger(eventType, ...varArgs) {\r\n if (Array.isArray(this.listeners_[eventType])) {\r\n // Clone the list, since callbacks could add/remove listeners.\r\n const listeners = [...this.listeners_[eventType]];\r\n for (let i = 0; i < listeners.length; i++) {\r\n listeners[i].callback.apply(listeners[i].context, varArgs);\r\n }\r\n }\r\n }\r\n on(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n this.listeners_[eventType] = this.listeners_[eventType] || [];\r\n this.listeners_[eventType].push({ callback, context });\r\n const eventData = this.getInitialEvent(eventType);\r\n if (eventData) {\r\n callback.apply(context, eventData);\r\n }\r\n }\r\n off(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n const listeners = this.listeners_[eventType] || [];\r\n for (let i = 0; i < listeners.length; i++) {\r\n if (listeners[i].callback === callback &&\r\n (!context || context === listeners[i].context)) {\r\n listeners.splice(i, 1);\r\n return;\r\n }\r\n }\r\n }\r\n validateEventType_(eventType) {\r\n assert(this.allowedEvents_.find(et => {\r\n return et === eventType;\r\n }), 'Unknown event: ' + eventType);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Monitors online state (as reported by window.online/offline events).\r\n *\r\n * The expectation is that this could have many false positives (thinks we are online\r\n * when we're not), but no false negatives. So we can safely use it to determine when\r\n * we definitely cannot reach the internet.\r\n */\r\nclass OnlineMonitor extends EventEmitter {\r\n constructor() {\r\n super(['online']);\r\n this.online_ = true;\r\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\r\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\r\n // It would seem that the 'online' event does not always fire consistently. So we disable it\r\n // for Cordova.\r\n if (typeof window !== 'undefined' &&\r\n typeof window.addEventListener !== 'undefined' &&\r\n !isMobileCordova()) {\r\n window.addEventListener('online', () => {\r\n if (!this.online_) {\r\n this.online_ = true;\r\n this.trigger('online', true);\r\n }\r\n }, false);\r\n window.addEventListener('offline', () => {\r\n if (this.online_) {\r\n this.online_ = false;\r\n this.trigger('online', false);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new OnlineMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\r\n return [this.online_];\r\n }\r\n currentlyOnline() {\r\n return this.online_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Maximum key depth. */\r\nconst MAX_PATH_DEPTH = 32;\r\n/** Maximum number of (UTF8) bytes in a Firebase path. */\r\nconst MAX_PATH_LENGTH_BYTES = 768;\r\n/**\r\n * An immutable object representing a parsed path. It's immutable so that you\r\n * can pass them around to other functions without worrying about them changing\r\n * it.\r\n */\r\nclass Path {\r\n /**\r\n * @param pathOrString - Path string to parse, or another path, or the raw\r\n * tokens array\r\n */\r\n constructor(pathOrString, pieceNum) {\r\n if (pieceNum === void 0) {\r\n this.pieces_ = pathOrString.split('/');\r\n // Remove empty pieces.\r\n let copyTo = 0;\r\n for (let i = 0; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i].length > 0) {\r\n this.pieces_[copyTo] = this.pieces_[i];\r\n copyTo++;\r\n }\r\n }\r\n this.pieces_.length = copyTo;\r\n this.pieceNum_ = 0;\r\n }\r\n else {\r\n this.pieces_ = pathOrString;\r\n this.pieceNum_ = pieceNum;\r\n }\r\n }\r\n toString() {\r\n let pathString = '';\r\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i] !== '') {\r\n pathString += '/' + this.pieces_[i];\r\n }\r\n }\r\n return pathString || '/';\r\n }\r\n}\r\nfunction newEmptyPath() {\r\n return new Path('');\r\n}\r\nfunction pathGetFront(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n return path.pieces_[path.pieceNum_];\r\n}\r\n/**\r\n * @returns The number of segments in this path\r\n */\r\nfunction pathGetLength(path) {\r\n return path.pieces_.length - path.pieceNum_;\r\n}\r\nfunction pathPopFront(path) {\r\n let pieceNum = path.pieceNum_;\r\n if (pieceNum < path.pieces_.length) {\r\n pieceNum++;\r\n }\r\n return new Path(path.pieces_, pieceNum);\r\n}\r\nfunction pathGetBack(path) {\r\n if (path.pieceNum_ < path.pieces_.length) {\r\n return path.pieces_[path.pieces_.length - 1];\r\n }\r\n return null;\r\n}\r\nfunction pathToUrlEncodedString(path) {\r\n let pathString = '';\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n if (path.pieces_[i] !== '') {\r\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\r\n }\r\n }\r\n return pathString || '/';\r\n}\r\n/**\r\n * Shallow copy of the parts of the path.\r\n *\r\n */\r\nfunction pathSlice(path, begin = 0) {\r\n return path.pieces_.slice(path.pieceNum_ + begin);\r\n}\r\nfunction pathParent(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n return new Path(pieces, 0);\r\n}\r\nfunction pathChild(path, childPathObj) {\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n if (childPathObj instanceof Path) {\r\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\r\n pieces.push(childPathObj.pieces_[i]);\r\n }\r\n }\r\n else {\r\n const childPieces = childPathObj.split('/');\r\n for (let i = 0; i < childPieces.length; i++) {\r\n if (childPieces[i].length > 0) {\r\n pieces.push(childPieces[i]);\r\n }\r\n }\r\n }\r\n return new Path(pieces, 0);\r\n}\r\n/**\r\n * @returns True if there are no segments in this path\r\n */\r\nfunction pathIsEmpty(path) {\r\n return path.pieceNum_ >= path.pieces_.length;\r\n}\r\n/**\r\n * @returns The path from outerPath to innerPath\r\n */\r\nfunction newRelativePath(outerPath, innerPath) {\r\n const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);\r\n if (outer === null) {\r\n return innerPath;\r\n }\r\n else if (outer === inner) {\r\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\r\n }\r\n else {\r\n throw new Error('INTERNAL ERROR: innerPath (' +\r\n innerPath +\r\n ') is not within ' +\r\n 'outerPath (' +\r\n outerPath +\r\n ')');\r\n }\r\n}\r\n/**\r\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\r\n */\r\nfunction pathCompare(left, right) {\r\n const leftKeys = pathSlice(left, 0);\r\n const rightKeys = pathSlice(right, 0);\r\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\r\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\r\n if (cmp !== 0) {\r\n return cmp;\r\n }\r\n }\r\n if (leftKeys.length === rightKeys.length) {\r\n return 0;\r\n }\r\n return leftKeys.length < rightKeys.length ? -1 : 1;\r\n}\r\n/**\r\n * @returns true if paths are the same.\r\n */\r\nfunction pathEquals(path, other) {\r\n if (pathGetLength(path) !== pathGetLength(other)) {\r\n return false;\r\n }\r\n for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * @returns True if this path is a parent (or the same as) other\r\n */\r\nfunction pathContains(path, other) {\r\n let i = path.pieceNum_;\r\n let j = other.pieceNum_;\r\n if (pathGetLength(path) > pathGetLength(other)) {\r\n return false;\r\n }\r\n while (i < path.pieces_.length) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n ++i;\r\n ++j;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Dynamic (mutable) path used to count path lengths.\r\n *\r\n * This class is used to efficiently check paths for valid\r\n * length (in UTF8 bytes) and depth (used in path validation).\r\n *\r\n * Throws Error exception if path is ever invalid.\r\n *\r\n * The definition of a path always begins with '/'.\r\n */\r\nclass ValidationPath {\r\n /**\r\n * @param path - Initial Path.\r\n * @param errorPrefix_ - Prefix for any error messages.\r\n */\r\n constructor(path, errorPrefix_) {\r\n this.errorPrefix_ = errorPrefix_;\r\n this.parts_ = pathSlice(path, 0);\r\n /** Initialize to number of '/' chars needed in path. */\r\n this.byteLength_ = Math.max(1, this.parts_.length);\r\n for (let i = 0; i < this.parts_.length; i++) {\r\n this.byteLength_ += stringLength(this.parts_[i]);\r\n }\r\n validationPathCheckValid(this);\r\n }\r\n}\r\nfunction validationPathPush(validationPath, child) {\r\n // Count the needed '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ += 1;\r\n }\r\n validationPath.parts_.push(child);\r\n validationPath.byteLength_ += stringLength(child);\r\n validationPathCheckValid(validationPath);\r\n}\r\nfunction validationPathPop(validationPath) {\r\n const last = validationPath.parts_.pop();\r\n validationPath.byteLength_ -= stringLength(last);\r\n // Un-count the previous '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ -= 1;\r\n }\r\n}\r\nfunction validationPathCheckValid(validationPath) {\r\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'has a key path longer than ' +\r\n MAX_PATH_LENGTH_BYTES +\r\n ' bytes (' +\r\n validationPath.byteLength_ +\r\n ').');\r\n }\r\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'path specified exceeds the maximum depth that can be written (' +\r\n MAX_PATH_DEPTH +\r\n ') or object contains a cycle ' +\r\n validationPathToErrorString(validationPath));\r\n }\r\n}\r\n/**\r\n * String for use in error messages - uses '.' notation for path.\r\n */\r\nfunction validationPathToErrorString(validationPath) {\r\n if (validationPath.parts_.length === 0) {\r\n return '';\r\n }\r\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass VisibilityMonitor extends EventEmitter {\r\n constructor() {\r\n super(['visible']);\r\n let hidden;\r\n let visibilityChange;\r\n if (typeof document !== 'undefined' &&\r\n typeof document.addEventListener !== 'undefined') {\r\n if (typeof document['hidden'] !== 'undefined') {\r\n // Opera 12.10 and Firefox 18 and later support\r\n visibilityChange = 'visibilitychange';\r\n hidden = 'hidden';\r\n }\r\n else if (typeof document['mozHidden'] !== 'undefined') {\r\n visibilityChange = 'mozvisibilitychange';\r\n hidden = 'mozHidden';\r\n }\r\n else if (typeof document['msHidden'] !== 'undefined') {\r\n visibilityChange = 'msvisibilitychange';\r\n hidden = 'msHidden';\r\n }\r\n else if (typeof document['webkitHidden'] !== 'undefined') {\r\n visibilityChange = 'webkitvisibilitychange';\r\n hidden = 'webkitHidden';\r\n }\r\n }\r\n // Initially, we always assume we are visible. This ensures that in browsers\r\n // without page visibility support or in cases where we are never visible\r\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\r\n // reconnects\r\n this.visible_ = true;\r\n if (visibilityChange) {\r\n document.addEventListener(visibilityChange, () => {\r\n const visible = !document[hidden];\r\n if (visible !== this.visible_) {\r\n this.visible_ = visible;\r\n this.trigger('visible', visible);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new VisibilityMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\r\n return [this.visible_];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECONNECT_MIN_DELAY = 1000;\r\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\r\nconst GET_CONNECT_TIMEOUT = 3 * 1000;\r\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\r\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\r\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\r\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\r\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\r\nconst INVALID_TOKEN_THRESHOLD = 3;\r\n/**\r\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\r\n *\r\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\r\n * in quotes to make sure the closure compiler does not minify them.\r\n */\r\nclass PersistentConnection extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param applicationId_ - The Firebase App ID for this project\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.onConnectStatus_ = onConnectStatus_;\r\n this.onServerInfoUpdate_ = onServerInfoUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n this.authOverride_ = authOverride_;\r\n // Used for diagnostic logging.\r\n this.id = PersistentConnection.nextPersistentConnectionId_++;\r\n this.log_ = logWrapper('p:' + this.id + ':');\r\n this.interruptReasons_ = {};\r\n this.listens = new Map();\r\n this.outstandingPuts_ = [];\r\n this.outstandingGets_ = [];\r\n this.outstandingPutCount_ = 0;\r\n this.outstandingGetCount_ = 0;\r\n this.onDisconnectRequestQueue_ = [];\r\n this.connected_ = false;\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\r\n this.securityDebugCallback_ = null;\r\n this.lastSessionId = null;\r\n this.establishConnectionTimer_ = null;\r\n this.visible_ = false;\r\n // Before we get connected, we keep a queue of pending messages to send.\r\n this.requestCBHash_ = {};\r\n this.requestNumber_ = 0;\r\n this.realtime_ = null;\r\n this.authToken_ = null;\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = false;\r\n this.invalidAuthTokenCount_ = 0;\r\n this.invalidAppCheckTokenCount_ = 0;\r\n this.firstConnection_ = true;\r\n this.lastConnectionAttemptTime_ = null;\r\n this.lastConnectionEstablishedTime_ = null;\r\n if (authOverride_ && !isNodeSdk()) {\r\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\r\n }\r\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\r\n if (repoInfo_.host.indexOf('fblocal') === -1) {\r\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\r\n }\r\n }\r\n sendRequest(action, body, onResponse) {\r\n const curReqNum = ++this.requestNumber_;\r\n const msg = { r: curReqNum, a: action, b: body };\r\n this.log_(stringify(msg));\r\n assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\r\n this.realtime_.sendRequest(msg);\r\n if (onResponse) {\r\n this.requestCBHash_[curReqNum] = onResponse;\r\n }\r\n }\r\n get(query) {\r\n this.initConnection_();\r\n const deferred = new Deferred();\r\n const request = {\r\n p: query._path.toString(),\r\n q: query._queryObject\r\n };\r\n const outstandingGet = {\r\n action: 'g',\r\n request,\r\n onComplete: (message) => {\r\n const payload = message['d'];\r\n if (message['s'] === 'ok') {\r\n this.onDataUpdate_(request['p'], payload, \r\n /*isMerge*/ false, \r\n /*tag*/ null);\r\n deferred.resolve(payload);\r\n }\r\n else {\r\n deferred.reject(payload);\r\n }\r\n }\r\n };\r\n this.outstandingGets_.push(outstandingGet);\r\n this.outstandingGetCount_++;\r\n const index = this.outstandingGets_.length - 1;\r\n if (!this.connected_) {\r\n setTimeout(() => {\r\n const get = this.outstandingGets_[index];\r\n if (get === undefined || outstandingGet !== get) {\r\n return;\r\n }\r\n delete this.outstandingGets_[index];\r\n this.outstandingGetCount_--;\r\n if (this.outstandingGetCount_ === 0) {\r\n this.outstandingGets_ = [];\r\n }\r\n this.log_('get ' + index + ' timed out on connection');\r\n deferred.reject(new Error('Client is offline.'));\r\n }, GET_CONNECT_TIMEOUT);\r\n }\r\n if (this.connected_) {\r\n this.sendGet_(index);\r\n }\r\n return deferred.promise;\r\n }\r\n listen(query, currentHashFn, tag, onComplete) {\r\n this.initConnection_();\r\n const queryId = query._queryIdentifier;\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + queryId);\r\n if (!this.listens.has(pathString)) {\r\n this.listens.set(pathString, new Map());\r\n }\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');\r\n assert(!this.listens.get(pathString).has(queryId), 'listen() called twice for same path/queryId.');\r\n const listenSpec = {\r\n onComplete,\r\n hashFn: currentHashFn,\r\n query,\r\n tag\r\n };\r\n this.listens.get(pathString).set(queryId, listenSpec);\r\n if (this.connected_) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n sendGet_(index) {\r\n const get = this.outstandingGets_[index];\r\n this.sendRequest('g', get.request, (message) => {\r\n delete this.outstandingGets_[index];\r\n this.outstandingGetCount_--;\r\n if (this.outstandingGetCount_ === 0) {\r\n this.outstandingGets_ = [];\r\n }\r\n if (get.onComplete) {\r\n get.onComplete(message);\r\n }\r\n });\r\n }\r\n sendListen_(listenSpec) {\r\n const query = listenSpec.query;\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Listen on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'q';\r\n // Only bother to send query if it's non-default.\r\n if (listenSpec.tag) {\r\n req['q'] = query._queryObject;\r\n req['t'] = listenSpec.tag;\r\n }\r\n req[ /*hash*/'h'] = listenSpec.hashFn();\r\n this.sendRequest(action, req, (message) => {\r\n const payload = message[ /*data*/'d'];\r\n const status = message[ /*status*/'s'];\r\n // print warnings in any case...\r\n PersistentConnection.warnOnListenWarnings_(payload, query);\r\n const currentListenSpec = this.listens.get(pathString) &&\r\n this.listens.get(pathString).get(queryId);\r\n // only trigger actions if the listen hasn't been removed and readded\r\n if (currentListenSpec === listenSpec) {\r\n this.log_('listen response', message);\r\n if (status !== 'ok') {\r\n this.removeListen_(pathString, queryId);\r\n }\r\n if (listenSpec.onComplete) {\r\n listenSpec.onComplete(status, payload);\r\n }\r\n }\r\n });\r\n }\r\n static warnOnListenWarnings_(payload, query) {\r\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const warnings = safeGet(payload, 'w');\r\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\r\n const indexSpec = '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\r\n const indexPath = query._path.toString();\r\n warn(`Using an unspecified index. Your data will be downloaded and ` +\r\n `filtered on the client. Consider adding ${indexSpec} at ` +\r\n `${indexPath} to your security rules for better performance.`);\r\n }\r\n }\r\n }\r\n refreshAuthToken(token) {\r\n this.authToken_ = token;\r\n this.log_('Auth token refreshed');\r\n if (this.authToken_) {\r\n this.tryAuth();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\r\n //the credential so we dont become authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unauth', {}, () => { });\r\n }\r\n }\r\n this.reduceReconnectDelayIfAdminCredential_(token);\r\n }\r\n reduceReconnectDelayIfAdminCredential_(credential) {\r\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\r\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\r\n const isFirebaseSecret = credential && credential.length === 40;\r\n if (isFirebaseSecret || isAdmin(credential)) {\r\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n }\r\n }\r\n refreshAppCheckToken(token) {\r\n this.appCheckToken_ = token;\r\n this.log_('App check token refreshed');\r\n if (this.appCheckToken_) {\r\n this.tryAppCheck();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us.\r\n //If we're not connected, simply delete the credential so we dont become\r\n // authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unappeck', {}, () => { });\r\n }\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\r\n * a auth revoked (the connection is closed).\r\n */\r\n tryAuth() {\r\n if (this.connected_ && this.authToken_) {\r\n const token = this.authToken_;\r\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\r\n const requestData = { cred: token };\r\n if (this.authOverride_ === null) {\r\n requestData['noauth'] = true;\r\n }\r\n else if (typeof this.authOverride_ === 'object') {\r\n requestData['authvar'] = this.authOverride_;\r\n }\r\n this.sendRequest(authMethod, requestData, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (this.authToken_ === token) {\r\n if (status === 'ok') {\r\n this.invalidAuthTokenCount_ = 0;\r\n }\r\n else {\r\n // Triggers reconnect and force refresh for auth token\r\n this.onAuthRevoked_(status, data);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given token. If the authentication\r\n * attempt fails, it's triggered like the token was revoked (the connection is\r\n * closed).\r\n */\r\n tryAppCheck() {\r\n if (this.connected_ && this.appCheckToken_) {\r\n this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (status === 'ok') {\r\n this.invalidAppCheckTokenCount_ = 0;\r\n }\r\n else {\r\n this.onAppCheckRevoked_(status, data);\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n unlisten(query, tag) {\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && this.connected_) {\r\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\r\n }\r\n }\r\n sendUnlisten_(pathString, queryId, queryObj, tag) {\r\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'n';\r\n // Only bother sending queryId if it's non-default.\r\n if (tag) {\r\n req['q'] = queryObj;\r\n req['t'] = tag;\r\n }\r\n this.sendRequest(action, req);\r\n }\r\n onDisconnectPut(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('o', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'o',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectMerge(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('om', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'om',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectCancel(pathString, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'oc',\r\n data: null,\r\n onComplete\r\n });\r\n }\r\n }\r\n sendOnDisconnect_(action, pathString, data, onComplete) {\r\n const request = { /*path*/ p: pathString, /*data*/ d: data };\r\n this.log_('onDisconnect ' + action, request);\r\n this.sendRequest(action, request, (response) => {\r\n if (onComplete) {\r\n setTimeout(() => {\r\n onComplete(response[ /*status*/'s'], response[ /* data */'d']);\r\n }, Math.floor(0));\r\n }\r\n });\r\n }\r\n put(pathString, data, onComplete, hash) {\r\n this.putInternal('p', pathString, data, onComplete, hash);\r\n }\r\n merge(pathString, data, onComplete, hash) {\r\n this.putInternal('m', pathString, data, onComplete, hash);\r\n }\r\n putInternal(action, pathString, data, onComplete, hash) {\r\n this.initConnection_();\r\n const request = {\r\n /*path*/ p: pathString,\r\n /*data*/ d: data\r\n };\r\n if (hash !== undefined) {\r\n request[ /*hash*/'h'] = hash;\r\n }\r\n // TODO: Only keep track of the most recent put for a given path?\r\n this.outstandingPuts_.push({\r\n action,\r\n request,\r\n onComplete\r\n });\r\n this.outstandingPutCount_++;\r\n const index = this.outstandingPuts_.length - 1;\r\n if (this.connected_) {\r\n this.sendPut_(index);\r\n }\r\n else {\r\n this.log_('Buffering put: ' + pathString);\r\n }\r\n }\r\n sendPut_(index) {\r\n const action = this.outstandingPuts_[index].action;\r\n const request = this.outstandingPuts_[index].request;\r\n const onComplete = this.outstandingPuts_[index].onComplete;\r\n this.outstandingPuts_[index].queued = this.connected_;\r\n this.sendRequest(action, request, (message) => {\r\n this.log_(action + ' response', message);\r\n delete this.outstandingPuts_[index];\r\n this.outstandingPutCount_--;\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n if (onComplete) {\r\n onComplete(message[ /*status*/'s'], message[ /* data */'d']);\r\n }\r\n });\r\n }\r\n reportStats(stats) {\r\n // If we're not connected, we just drop the stats.\r\n if (this.connected_) {\r\n const request = { /*counters*/ c: stats };\r\n this.log_('reportStats', request);\r\n this.sendRequest(/*stats*/ 's', request, result => {\r\n const status = result[ /*status*/'s'];\r\n if (status !== 'ok') {\r\n const errorReason = result[ /* data */'d'];\r\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\r\n }\r\n });\r\n }\r\n }\r\n onDataMessage_(message) {\r\n if ('r' in message) {\r\n // this is a response\r\n this.log_('from server: ' + stringify(message));\r\n const reqNum = message['r'];\r\n const onResponse = this.requestCBHash_[reqNum];\r\n if (onResponse) {\r\n delete this.requestCBHash_[reqNum];\r\n onResponse(message[ /*body*/'b']);\r\n }\r\n }\r\n else if ('error' in message) {\r\n throw 'A server-side error has occurred: ' + message['error'];\r\n }\r\n else if ('a' in message) {\r\n // a and b are action and body, respectively\r\n this.onDataPush_(message['a'], message['b']);\r\n }\r\n }\r\n onDataPush_(action, body) {\r\n this.log_('handleServerMessage', action, body);\r\n if (action === 'd') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge*/ false, body['t']);\r\n }\r\n else if (action === 'm') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge=*/ true, body['t']);\r\n }\r\n else if (action === 'c') {\r\n this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\r\n }\r\n else if (action === 'ac') {\r\n this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'apc') {\r\n this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'sd') {\r\n this.onSecurityDebugPacket_(body);\r\n }\r\n else {\r\n error('Unrecognized action received from server: ' +\r\n stringify(action) +\r\n '\\nAre you using the latest client?');\r\n }\r\n }\r\n onReady_(timestamp, sessionId) {\r\n this.log_('connection ready');\r\n this.connected_ = true;\r\n this.lastConnectionEstablishedTime_ = new Date().getTime();\r\n this.handleTimestamp_(timestamp);\r\n this.lastSessionId = sessionId;\r\n if (this.firstConnection_) {\r\n this.sendConnectStats_();\r\n }\r\n this.restoreState_();\r\n this.firstConnection_ = false;\r\n this.onConnectStatus_(true);\r\n }\r\n scheduleConnect_(timeout) {\r\n assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n }\r\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\r\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\r\n this.establishConnectionTimer_ = setTimeout(() => {\r\n this.establishConnectionTimer_ = null;\r\n this.establishConnection_();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(timeout));\r\n }\r\n initConnection_() {\r\n if (!this.realtime_ && this.firstConnection_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n onVisible_(visible) {\r\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\r\n if (visible &&\r\n !this.visible_ &&\r\n this.reconnectDelay_ === this.maxReconnectDelay_) {\r\n this.log_('Window became visible. Reducing delay.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n this.visible_ = visible;\r\n }\r\n onOnline_(online) {\r\n if (online) {\r\n this.log_('Browser went online.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n else {\r\n this.log_('Browser went offline. Killing connection.');\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n }\r\n }\r\n onRealtimeDisconnect_() {\r\n this.log_('data client disconnected');\r\n this.connected_ = false;\r\n this.realtime_ = null;\r\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\r\n this.cancelSentTransactions_();\r\n // Clear out the pending requests.\r\n this.requestCBHash_ = {};\r\n if (this.shouldReconnect_()) {\r\n if (!this.visible_) {\r\n this.log_(\"Window isn't visible. Delaying reconnect.\");\r\n this.reconnectDelay_ = this.maxReconnectDelay_;\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n }\r\n else if (this.lastConnectionEstablishedTime_) {\r\n // If we've been connected long enough, reset reconnect delay to minimum.\r\n const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\r\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n }\r\n this.lastConnectionEstablishedTime_ = null;\r\n }\r\n const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\r\n let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\r\n reconnectDelay = Math.random() * reconnectDelay;\r\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\r\n this.scheduleConnect_(reconnectDelay);\r\n // Adjust reconnect delay for next time.\r\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\r\n }\r\n this.onConnectStatus_(false);\r\n }\r\n async establishConnection_() {\r\n if (this.shouldReconnect_()) {\r\n this.log_('Making a connection attempt');\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n this.lastConnectionEstablishedTime_ = null;\r\n const onDataMessage = this.onDataMessage_.bind(this);\r\n const onReady = this.onReady_.bind(this);\r\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\r\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\r\n const lastSessionId = this.lastSessionId;\r\n let canceled = false;\r\n let connection = null;\r\n const closeFn = function () {\r\n if (connection) {\r\n connection.close();\r\n }\r\n else {\r\n canceled = true;\r\n onDisconnect();\r\n }\r\n };\r\n const sendRequestFn = function (msg) {\r\n assert(connection, \"sendRequest call when we're not connected not allowed.\");\r\n connection.sendRequest(msg);\r\n };\r\n this.realtime_ = {\r\n close: closeFn,\r\n sendRequest: sendRequestFn\r\n };\r\n const forceRefresh = this.forceTokenRefresh_;\r\n this.forceTokenRefresh_ = false;\r\n try {\r\n // First fetch auth and app check token, and establish connection after\r\n // fetching the token was successful\r\n const [authToken, appCheckToken] = await Promise.all([\r\n this.authTokenProvider_.getToken(forceRefresh),\r\n this.appCheckTokenProvider_.getToken(forceRefresh)\r\n ]);\r\n if (!canceled) {\r\n log('getToken() completed. Creating connection.');\r\n this.authToken_ = authToken && authToken.accessToken;\r\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\r\n connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, \r\n /* onKill= */ reason => {\r\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\r\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\r\n }, lastSessionId);\r\n }\r\n else {\r\n log('getToken() completed but was canceled');\r\n }\r\n }\r\n catch (error) {\r\n this.log_('Failed to get token: ' + error);\r\n if (!canceled) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\r\n // But getToken() may also just have temporarily failed, so we still want to\r\n // continue retrying.\r\n warn(error);\r\n }\r\n closeFn();\r\n }\r\n }\r\n }\r\n }\r\n interrupt(reason) {\r\n log('Interrupting connection for reason: ' + reason);\r\n this.interruptReasons_[reason] = true;\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n else {\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n this.establishConnectionTimer_ = null;\r\n }\r\n if (this.connected_) {\r\n this.onRealtimeDisconnect_();\r\n }\r\n }\r\n }\r\n resume(reason) {\r\n log('Resuming connection for reason: ' + reason);\r\n delete this.interruptReasons_[reason];\r\n if (isEmpty(this.interruptReasons_)) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n }\r\n handleTimestamp_(timestamp) {\r\n const delta = timestamp - new Date().getTime();\r\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\r\n }\r\n cancelSentTransactions_() {\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n const put = this.outstandingPuts_[i];\r\n if (put && /*hash*/ 'h' in put.request && put.queued) {\r\n if (put.onComplete) {\r\n put.onComplete('disconnect');\r\n }\r\n delete this.outstandingPuts_[i];\r\n this.outstandingPutCount_--;\r\n }\r\n }\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n }\r\n onListenRevoked_(pathString, query) {\r\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\r\n let queryId;\r\n if (!query) {\r\n queryId = 'default';\r\n }\r\n else {\r\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\r\n }\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && listen.onComplete) {\r\n listen.onComplete('permission_denied');\r\n }\r\n }\r\n removeListen_(pathString, queryId) {\r\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\r\n let listen;\r\n if (this.listens.has(normalizedPathString)) {\r\n const map = this.listens.get(normalizedPathString);\r\n listen = map.get(queryId);\r\n map.delete(queryId);\r\n if (map.size === 0) {\r\n this.listens.delete(normalizedPathString);\r\n }\r\n }\r\n else {\r\n // all listens for this path has already been removed\r\n listen = undefined;\r\n }\r\n return listen;\r\n }\r\n onAuthRevoked_(statusCode, explanation) {\r\n log('Auth token revoked: ' + statusCode + '/' + explanation);\r\n this.authToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n this.realtime_.close();\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAuthTokenCount_++;\r\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n // Set a long reconnect delay because recovery is unlikely\r\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n // Notify the auth token provider that the token is invalid, which will log\r\n // a warning\r\n this.authTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onAppCheckRevoked_(statusCode, explanation) {\r\n log('App check token revoked: ' + statusCode + '/' + explanation);\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n // Note: We don't close the connection as the developer may not have\r\n // enforcement enabled. The backend closes connections with enforcements.\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAppCheckTokenCount_++;\r\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n this.appCheckTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onSecurityDebugPacket_(body) {\r\n if (this.securityDebugCallback_) {\r\n this.securityDebugCallback_(body);\r\n }\r\n else {\r\n if ('msg' in body) {\r\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\r\n }\r\n }\r\n }\r\n restoreState_() {\r\n //Re-authenticate ourselves if we have a credential stored.\r\n this.tryAuth();\r\n this.tryAppCheck();\r\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\r\n // make sure to send listens before puts.\r\n for (const queries of this.listens.values()) {\r\n for (const listenSpec of queries.values()) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n if (this.outstandingPuts_[i]) {\r\n this.sendPut_(i);\r\n }\r\n }\r\n while (this.onDisconnectRequestQueue_.length) {\r\n const request = this.onDisconnectRequestQueue_.shift();\r\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\r\n }\r\n for (let i = 0; i < this.outstandingGets_.length; i++) {\r\n if (this.outstandingGets_[i]) {\r\n this.sendGet_(i);\r\n }\r\n }\r\n }\r\n /**\r\n * Sends client stats for first connection\r\n */\r\n sendConnectStats_() {\r\n const stats = {};\r\n let clientName = 'js';\r\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\r\n if (isMobileCordova()) {\r\n stats['framework.cordova'] = 1;\r\n }\r\n else if (isReactNative()) {\r\n stats['framework.reactnative'] = 1;\r\n }\r\n this.reportStats(stats);\r\n }\r\n shouldReconnect_() {\r\n const online = OnlineMonitor.getInstance().currentlyOnline();\r\n return isEmpty(this.interruptReasons_) && online;\r\n }\r\n}\r\nPersistentConnection.nextPersistentConnectionId_ = 0;\r\n/**\r\n * Counter for number of connections created. Mainly used for tagging in the logs\r\n */\r\nPersistentConnection.nextConnectionId_ = 0;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass NamedNode {\r\n constructor(name, node) {\r\n this.name = name;\r\n this.node = node;\r\n }\r\n static Wrap(name, node) {\r\n return new NamedNode(name, node);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Index {\r\n /**\r\n * @returns A standalone comparison function for\r\n * this index\r\n */\r\n getCompare() {\r\n return this.compare.bind(this);\r\n }\r\n /**\r\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\r\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\r\n *\r\n *\r\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\r\n */\r\n indexedValueChanged(oldNode, newNode) {\r\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\r\n const newWrapped = new NamedNode(MIN_NAME, newNode);\r\n return this.compare(oldWrapped, newWrapped) !== 0;\r\n }\r\n /**\r\n * @returns a node wrapper that will sort equal to or less than\r\n * any other node wrapper, using this index\r\n */\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __EMPTY_NODE;\r\nclass KeyIndex extends Index {\r\n static get __EMPTY_NODE() {\r\n return __EMPTY_NODE;\r\n }\r\n static set __EMPTY_NODE(val) {\r\n __EMPTY_NODE = val;\r\n }\r\n compare(a, b) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n isDefinedOn(node) {\r\n // We could probably return true here (since every node has a key), but it's never called\r\n // so just leaving unimplemented for now.\r\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return false; // The key for a node never changes.\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // TODO: This should really be created once and cached in a static property, but\r\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\r\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\r\n }\r\n makePost(indexValue, name) {\r\n assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\r\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\r\n return new NamedNode(indexValue, __EMPTY_NODE);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.key';\r\n }\r\n}\r\nconst KEY_INDEX = new KeyIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An iterator over an LLRBNode.\r\n */\r\nclass SortedMapIterator {\r\n /**\r\n * @param node - Node to iterate.\r\n * @param isReverse_ - Whether or not to iterate in reverse\r\n */\r\n constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {\r\n this.isReverse_ = isReverse_;\r\n this.resultGenerator_ = resultGenerator_;\r\n this.nodeStack_ = [];\r\n let cmp = 1;\r\n while (!node.isEmpty()) {\r\n node = node;\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse_) {\r\n cmp *= -1;\r\n }\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse_) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\r\n this.nodeStack_.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move to the next one\r\n this.nodeStack_.push(node);\r\n if (this.isReverse_) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n getNext() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n let node = this.nodeStack_.pop();\r\n let result;\r\n if (this.resultGenerator_) {\r\n result = this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n result = { key: node.key, value: node.value };\r\n }\r\n if (this.isReverse_) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n }\r\n hasNext() {\r\n return this.nodeStack_.length > 0;\r\n }\r\n peek() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n const node = this.nodeStack_[this.nodeStack_.length - 1];\r\n if (this.resultGenerator_) {\r\n return this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n return { key: node.key, value: node.value };\r\n }\r\n }\r\n}\r\n/**\r\n * Represents a node in a Left-leaning Red-Black tree.\r\n */\r\nclass LLRBNode {\r\n /**\r\n * @param key - Key associated with this node.\r\n * @param value - Value associated with this node.\r\n * @param color - Whether this node is red.\r\n * @param left - Left child.\r\n * @param right - Right child.\r\n */\r\n constructor(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left =\r\n left != null ? left : SortedMap.EMPTY_NODE;\r\n this.right =\r\n right != null ? right : SortedMap.EMPTY_NODE;\r\n }\r\n /**\r\n * Returns a copy of the current node, optionally replacing pieces of it.\r\n *\r\n * @param key - New key for the node, or null.\r\n * @param value - New value for the node, or null.\r\n * @param color - New color for the node, or null.\r\n * @param left - New left child for the node, or null.\r\n * @param right - New right child for the node, or null.\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return this.left.count() + 1 + this.right.count();\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return (this.left.inorderTraversal(action) ||\r\n !!action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n }\r\n /**\r\n * @returns The minimum node in the tree.\r\n */\r\n min_() {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min_();\r\n }\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n minKey() {\r\n return this.min_().key;\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n maxKey() {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n }\r\n /**\r\n * @param key - Key to insert.\r\n * @param value - Value to insert.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the key/value added.\r\n */\r\n insert(key, value, comparator) {\r\n let n = this;\r\n const cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns New tree, with the minimum key removed.\r\n */\r\n removeMin_() {\r\n if (this.left.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n let n = this;\r\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.removeMin_(), null);\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @param key - The key of the item to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the specified item removed.\r\n */\r\n remove(key, comparator) {\r\n let n, smallest;\r\n n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\r\n n = n.moveRedRight_();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n else {\r\n smallest = n.right.min_();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns Whether this is a RED node.\r\n */\r\n isRed_() {\r\n return this.color;\r\n }\r\n /**\r\n * @returns New tree after performing any needed rotations.\r\n */\r\n fixUp_() {\r\n let n = this;\r\n if (n.right.isRed_() && !n.left.isRed_()) {\r\n n = n.rotateLeft_();\r\n }\r\n if (n.left.isRed_() && n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (n.left.isRed_() && n.right.isRed_()) {\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedLeft.\r\n */\r\n moveRedLeft_() {\r\n let n = this.colorFlip_();\r\n if (n.right.left.isRed_()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight_());\r\n n = n.rotateLeft_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedRight.\r\n */\r\n moveRedRight_() {\r\n let n = this.colorFlip_();\r\n if (n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after rotateLeft.\r\n */\r\n rotateLeft_() {\r\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n }\r\n /**\r\n * @returns New tree, after rotateRight.\r\n */\r\n rotateRight_() {\r\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n }\r\n /**\r\n * @returns Newt ree, after colorFlip.\r\n */\r\n colorFlip_() {\r\n const left = this.left.copy(null, null, !this.left.color, null, null);\r\n const right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n }\r\n /**\r\n * For testing.\r\n *\r\n * @returns True if all is well.\r\n */\r\n checkMaxDepth_() {\r\n const blackDepth = this.check_();\r\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\r\n }\r\n check_() {\r\n if (this.isRed_() && this.left.isRed_()) {\r\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed_()) {\r\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n const blackDepth = this.left.check_();\r\n if (blackDepth !== this.right.check_()) {\r\n throw new Error('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed_() ? 0 : 1);\r\n }\r\n }\r\n}\r\nLLRBNode.RED = true;\r\nLLRBNode.BLACK = false;\r\n/**\r\n * Represents an empty node (a leaf node in the Red-Black Tree).\r\n */\r\nclass LLRBEmptyNode {\r\n /**\r\n * Returns a copy of the current node.\r\n *\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return this;\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key/value added.\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item added.\r\n */\r\n insert(key, value, comparator) {\r\n return new LLRBNode(key, value, null);\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item removed.\r\n */\r\n remove(key, comparator) {\r\n return this;\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return 0;\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return true;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n inorderTraversal(action) {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return false;\r\n }\r\n minKey() {\r\n return null;\r\n }\r\n maxKey() {\r\n return null;\r\n }\r\n check_() {\r\n return 0;\r\n }\r\n /**\r\n * @returns Whether this node is red.\r\n */\r\n isRed_() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n * tree.\r\n */\r\nclass SortedMap {\r\n /**\r\n * @param comparator_ - Key comparator.\r\n * @param root_ - Optional root node for the map.\r\n */\r\n constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {\r\n this.comparator_ = comparator_;\r\n this.root_ = root_;\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key/value added or replaced.\r\n * (TODO: We should perhaps rename this method to 'put')\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @returns New map, with item added.\r\n */\r\n insert(key, value) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .insert(key, value, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @returns New map, with item removed.\r\n */\r\n remove(key) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .remove(key, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns the value of the node with the given key, or null.\r\n *\r\n * @param key - The key to look up.\r\n * @returns The value of the node with the given key, or null if the\r\n * key doesn't exist.\r\n */\r\n get(key) {\r\n let cmp;\r\n let node = this.root_;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns the key of the item *before* the specified key, or null if key is the first item.\r\n * @param key - The key to find the predecessor of\r\n * @returns The predecessor key.\r\n */\r\n getPredecessorKey(key) {\r\n let cmp, node = this.root_, rightParent = null;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n if (!node.left.isEmpty()) {\r\n node = node.left;\r\n while (!node.right.isEmpty()) {\r\n node = node.right;\r\n }\r\n return node.key;\r\n }\r\n else if (rightParent) {\r\n return rightParent.key;\r\n }\r\n else {\r\n return null; // first item.\r\n }\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n rightParent = node;\r\n node = node.right;\r\n }\r\n }\r\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\r\n }\r\n /**\r\n * @returns True if the map is empty.\r\n */\r\n isEmpty() {\r\n return this.root_.isEmpty();\r\n }\r\n /**\r\n * @returns The total number of nodes in the map.\r\n */\r\n count() {\r\n return this.root_.count();\r\n }\r\n /**\r\n * @returns The minimum key in the map.\r\n */\r\n minKey() {\r\n return this.root_.minKey();\r\n }\r\n /**\r\n * @returns The maximum key in the map.\r\n */\r\n maxKey() {\r\n return this.root_.maxKey();\r\n }\r\n /**\r\n * Traverses the map in key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return this.root_.inorderTraversal(action);\r\n }\r\n /**\r\n * Traverses the map in reverse key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns True if the traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return this.root_.reverseTraversal(action);\r\n }\r\n /**\r\n * Returns an iterator over the SortedMap.\r\n * @returns The iterator.\r\n */\r\n getIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\r\n }\r\n getIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\r\n }\r\n getReverseIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\r\n }\r\n getReverseIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\r\n }\r\n}\r\n/**\r\n * Always use the same empty node, to reduce memory.\r\n */\r\nSortedMap.EMPTY_NODE = new LLRBEmptyNode();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction NAME_ONLY_COMPARATOR(left, right) {\r\n return nameCompare(left.name, right.name);\r\n}\r\nfunction NAME_COMPARATOR(left, right) {\r\n return nameCompare(left, right);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet MAX_NODE$2;\r\nfunction setMaxNode$1(val) {\r\n MAX_NODE$2 = val;\r\n}\r\nconst priorityHashText = function (priority) {\r\n if (typeof priority === 'number') {\r\n return 'number:' + doubleToIEEE754String(priority);\r\n }\r\n else {\r\n return 'string:' + priority;\r\n }\r\n};\r\n/**\r\n * Validates that a priority snapshot Node is valid.\r\n */\r\nconst validatePriorityNode = function (priorityNode) {\r\n if (priorityNode.isLeafNode()) {\r\n const val = priorityNode.val();\r\n assert(typeof val === 'string' ||\r\n typeof val === 'number' ||\r\n (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');\r\n }\r\n else {\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');\r\n }\r\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __childrenNodeConstructor;\r\n/**\r\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\r\n * implements Node and stores the value of the node (a string,\r\n * number, or boolean) accessible via getValue().\r\n */\r\nclass LeafNode {\r\n /**\r\n * @param value_ - The value to store in this leaf node. The object type is\r\n * possible in the event of a deferred value\r\n * @param priorityNode_ - The priority of this node.\r\n */\r\n constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n this.value_ = value_;\r\n this.priorityNode_ = priorityNode_;\r\n this.lazyHash_ = null;\r\n assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n static set __childrenNodeConstructor(val) {\r\n __childrenNodeConstructor = val;\r\n }\r\n static get __childrenNodeConstructor() {\r\n return __childrenNodeConstructor;\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return true;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n return new LeafNode(this.value_, newPriorityNode);\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n if (pathIsEmpty(path)) {\r\n return this;\r\n }\r\n else if (pathGetFront(path) === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n hasChild() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode) {\r\n return null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else if (newChildNode.isEmpty() && childName !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else if (newChildNode.isEmpty() && front !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return 0;\r\n }\r\n /** @inheritDoc */\r\n forEachChild(index, action) {\r\n return false;\r\n }\r\n val(exportFormat) {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n return {\r\n '.value': this.getValue(),\r\n '.priority': this.getPriority().val()\r\n };\r\n }\r\n else {\r\n return this.getValue();\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.priorityNode_.isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.priorityNode_.val()) +\r\n ':';\r\n }\r\n const type = typeof this.value_;\r\n toHash += type + ':';\r\n if (type === 'number') {\r\n toHash += doubleToIEEE754String(this.value_);\r\n }\r\n else {\r\n toHash += this.value_;\r\n }\r\n this.lazyHash_ = sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /**\r\n * Returns the value of the leaf node.\r\n * @returns The value of the node.\r\n */\r\n getValue() {\r\n return this.value_;\r\n }\r\n compareTo(other) {\r\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n return 1;\r\n }\r\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\r\n return -1;\r\n }\r\n else {\r\n assert(other.isLeafNode(), 'Unknown node type');\r\n return this.compareToLeafNode_(other);\r\n }\r\n }\r\n /**\r\n * Comparison specifically for two leaf nodes\r\n */\r\n compareToLeafNode_(otherLeaf) {\r\n const otherLeafType = typeof otherLeaf.value_;\r\n const thisLeafType = typeof this.value_;\r\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\r\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\r\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\r\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\r\n if (otherIndex === thisIndex) {\r\n // Same type, compare values\r\n if (thisLeafType === 'object') {\r\n // Deferred value nodes are all equal, but we should also never get to this point...\r\n return 0;\r\n }\r\n else {\r\n // Note that this works because true > false, all others are number or string comparisons\r\n if (this.value_ < otherLeaf.value_) {\r\n return -1;\r\n }\r\n else if (this.value_ === otherLeaf.value_) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n }\r\n else {\r\n return thisIndex - otherIndex;\r\n }\r\n }\r\n withIndex() {\r\n return this;\r\n }\r\n isIndexed() {\r\n return true;\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n const otherLeaf = other;\r\n return (this.value_ === otherLeaf.value_ &&\r\n this.priorityNode_.equals(otherLeaf.priorityNode_));\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n}\r\n/**\r\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\r\n * the same type, the comparison falls back to their value\r\n */\r\nLeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet nodeFromJSON$1;\r\nlet MAX_NODE$1;\r\nfunction setNodeFromJSON(val) {\r\n nodeFromJSON$1 = val;\r\n}\r\nfunction setMaxNode(val) {\r\n MAX_NODE$1 = val;\r\n}\r\nclass PriorityIndex extends Index {\r\n compare(a, b) {\r\n const aPriority = a.node.getPriority();\r\n const bPriority = b.node.getPriority();\r\n const indexCmp = aPriority.compareTo(bPriority);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return !node.getPriority().isEmpty();\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.getPriority().equals(newNode.getPriority());\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\r\n }\r\n makePost(indexValue, name) {\r\n const priorityNode = nodeFromJSON$1(indexValue);\r\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.priority';\r\n }\r\n}\r\nconst PRIORITY_INDEX = new PriorityIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst LOG_2 = Math.log(2);\r\nclass Base12Num {\r\n constructor(length) {\r\n const logBase2 = (num) => \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n parseInt((Math.log(num) / LOG_2), 10);\r\n const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);\r\n this.count = logBase2(length + 1);\r\n this.current_ = this.count - 1;\r\n const mask = bitMask(this.count);\r\n this.bits_ = (length + 1) & mask;\r\n }\r\n nextBitIsOne() {\r\n //noinspection JSBitwiseOperatorUsage\r\n const result = !(this.bits_ & (0x1 << this.current_));\r\n this.current_--;\r\n return result;\r\n }\r\n}\r\n/**\r\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\r\n * function\r\n *\r\n * Uses the algorithm described in the paper linked here:\r\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\r\n *\r\n * @param childList - Unsorted list of children\r\n * @param cmp - The comparison method to be used\r\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\r\n * type is not NamedNode\r\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\r\n */\r\nconst buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\r\n childList.sort(cmp);\r\n const buildBalancedTree = function (low, high) {\r\n const length = high - low;\r\n let namedNode;\r\n let key;\r\n if (length === 0) {\r\n return null;\r\n }\r\n else if (length === 1) {\r\n namedNode = childList[low];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\r\n }\r\n else {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const middle = parseInt((length / 2), 10) + low;\r\n const left = buildBalancedTree(low, middle);\r\n const right = buildBalancedTree(middle + 1, high);\r\n namedNode = childList[middle];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\r\n }\r\n };\r\n const buildFrom12Array = function (base12) {\r\n let node = null;\r\n let root = null;\r\n let index = childList.length;\r\n const buildPennant = function (chunkSize, color) {\r\n const low = index - chunkSize;\r\n const high = index;\r\n index -= chunkSize;\r\n const childTree = buildBalancedTree(low + 1, high);\r\n const namedNode = childList[low];\r\n const key = keyFn ? keyFn(namedNode) : namedNode;\r\n attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\r\n };\r\n const attachPennant = function (pennant) {\r\n if (node) {\r\n node.left = pennant;\r\n node = pennant;\r\n }\r\n else {\r\n root = pennant;\r\n node = pennant;\r\n }\r\n };\r\n for (let i = 0; i < base12.count; ++i) {\r\n const isOne = base12.nextBitIsOne();\r\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\r\n const chunkSize = Math.pow(2, base12.count - (i + 1));\r\n if (isOne) {\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n }\r\n else {\r\n // current == 2\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n buildPennant(chunkSize, LLRBNode.RED);\r\n }\r\n }\r\n return root;\r\n };\r\n const base12 = new Base12Num(childList.length);\r\n const root = buildFrom12Array(base12);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return new SortedMap(mapSortFn || cmp, root);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet _defaultIndexMap;\r\nconst fallbackObject = {};\r\nclass IndexMap {\r\n constructor(indexes_, indexSet_) {\r\n this.indexes_ = indexes_;\r\n this.indexSet_ = indexSet_;\r\n }\r\n /**\r\n * The default IndexMap for nodes without a priority\r\n */\r\n static get Default() {\r\n assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\r\n _defaultIndexMap =\r\n _defaultIndexMap ||\r\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\r\n return _defaultIndexMap;\r\n }\r\n get(indexKey) {\r\n const sortedMap = safeGet(this.indexes_, indexKey);\r\n if (!sortedMap) {\r\n throw new Error('No index defined for ' + indexKey);\r\n }\r\n if (sortedMap instanceof SortedMap) {\r\n return sortedMap;\r\n }\r\n else {\r\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\r\n // regular child map\r\n return null;\r\n }\r\n }\r\n hasIndex(indexDefinition) {\r\n return contains(this.indexSet_, indexDefinition.toString());\r\n }\r\n addIndex(indexDefinition, existingChildren) {\r\n assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\r\n const childList = [];\r\n let sawIndexedValue = false;\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n sawIndexedValue =\r\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\r\n childList.push(next);\r\n next = iter.getNext();\r\n }\r\n let newIndex;\r\n if (sawIndexedValue) {\r\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\r\n }\r\n else {\r\n newIndex = fallbackObject;\r\n }\r\n const indexName = indexDefinition.toString();\r\n const newIndexSet = Object.assign({}, this.indexSet_);\r\n newIndexSet[indexName] = indexDefinition;\r\n const newIndexes = Object.assign({}, this.indexes_);\r\n newIndexes[indexName] = newIndex;\r\n return new IndexMap(newIndexes, newIndexSet);\r\n }\r\n /**\r\n * Ensure that this node is properly tracked in any indexes that we're maintaining\r\n */\r\n addToIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {\r\n const index = safeGet(this.indexSet_, indexName);\r\n assert(index, 'Missing index implementation for ' + indexName);\r\n if (indexedChildren === fallbackObject) {\r\n // Check to see if we need to index everything\r\n if (index.isDefinedOn(namedNode.node)) {\r\n // We need to build this index\r\n const childList = [];\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n if (next.name !== namedNode.name) {\r\n childList.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n childList.push(namedNode);\r\n return buildChildSet(childList, index.getCompare());\r\n }\r\n else {\r\n // No change, this remains a fallback\r\n return fallbackObject;\r\n }\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n let newChildren = indexedChildren;\r\n if (existingSnap) {\r\n newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n return newChildren.insert(namedNode, namedNode.node);\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n /**\r\n * Create a new IndexMap instance with the given value removed\r\n */\r\n removeFromIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren) => {\r\n if (indexedChildren === fallbackObject) {\r\n // This is the fallback. Just return it, nothing to do in this case\r\n return indexedChildren;\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n if (existingSnap) {\r\n return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n else {\r\n // No record of this child\r\n return indexedChildren;\r\n }\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\r\nlet EMPTY_NODE;\r\n/**\r\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\r\n * (i.e. nodes with children). It implements Node and stores the\r\n * list of children in the children property, sorted by child name.\r\n */\r\nclass ChildrenNode {\r\n /**\r\n * @param children_ - List of children of this node..\r\n * @param priorityNode_ - The priority of this node (as a snapshot node).\r\n */\r\n constructor(children_, priorityNode_, indexMap_) {\r\n this.children_ = children_;\r\n this.priorityNode_ = priorityNode_;\r\n this.indexMap_ = indexMap_;\r\n this.lazyHash_ = null;\r\n /**\r\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\r\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\r\n * class instead of an empty ChildrenNode.\r\n */\r\n if (this.priorityNode_) {\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n if (this.children_.isEmpty()) {\r\n assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\r\n }\r\n }\r\n static get EMPTY_NODE() {\r\n return (EMPTY_NODE ||\r\n (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_ || EMPTY_NODE;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n if (this.children_.isEmpty()) {\r\n // Don't allow priorities on empty nodes\r\n return this;\r\n }\r\n else {\r\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.getPriority();\r\n }\r\n else {\r\n const child = this.children_.get(childName);\r\n return child === null ? EMPTY_NODE : child;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return this;\r\n }\r\n return this.getImmediateChild(front).getChild(pathPopFront(path));\r\n }\r\n /** @inheritDoc */\r\n hasChild(childName) {\r\n return this.children_.get(childName) !== null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n assert(newChildNode, 'We should always be passing snapshot nodes');\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else {\r\n const namedNode = new NamedNode(childName, newChildNode);\r\n let newChildren, newIndexMap;\r\n if (newChildNode.isEmpty()) {\r\n newChildren = this.children_.remove(childName);\r\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\r\n }\r\n else {\r\n newChildren = this.children_.insert(childName, newChildNode);\r\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\r\n }\r\n const newPriority = newChildren.isEmpty()\r\n ? EMPTY_NODE\r\n : this.priorityNode_;\r\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else {\r\n assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);\r\n return this.updateImmediateChild(front, newImmediateChild);\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return this.children_.isEmpty();\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return this.children_.count();\r\n }\r\n /** @inheritDoc */\r\n val(exportFormat) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const obj = {};\r\n let numKeys = 0, maxKey = 0, allIntegerKeys = true;\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n obj[key] = childNode.val(exportFormat);\r\n numKeys++;\r\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\r\n maxKey = Math.max(maxKey, Number(key));\r\n }\r\n else {\r\n allIntegerKeys = false;\r\n }\r\n });\r\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\r\n // convert to array.\r\n const array = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const key in obj) {\r\n array[key] = obj[key];\r\n }\r\n return array;\r\n }\r\n else {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n obj['.priority'] = this.getPriority().val();\r\n }\r\n return obj;\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.getPriority().isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.getPriority().val()) +\r\n ':';\r\n }\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n const childHash = childNode.hash();\r\n if (childHash !== '') {\r\n toHash += ':' + key + ':' + childHash;\r\n }\r\n });\r\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode, index) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\r\n return predecessor ? predecessor.name : null;\r\n }\r\n else {\r\n return this.children_.getPredecessorKey(childName);\r\n }\r\n }\r\n getFirstChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const minKey = idx.minKey();\r\n return minKey && minKey.name;\r\n }\r\n else {\r\n return this.children_.minKey();\r\n }\r\n }\r\n getFirstChild(indexDefinition) {\r\n const minKey = this.getFirstChildName(indexDefinition);\r\n if (minKey) {\r\n return new NamedNode(minKey, this.children_.get(minKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n /**\r\n * Given an index, return the key name of the largest value we have, according to that index\r\n */\r\n getLastChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const maxKey = idx.maxKey();\r\n return maxKey && maxKey.name;\r\n }\r\n else {\r\n return this.children_.maxKey();\r\n }\r\n }\r\n getLastChild(indexDefinition) {\r\n const maxKey = this.getLastChildName(indexDefinition);\r\n if (maxKey) {\r\n return new NamedNode(maxKey, this.children_.get(maxKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n forEachChild(index, action) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n return idx.inorderTraversal(wrappedNode => {\r\n return action(wrappedNode.name, wrappedNode.node);\r\n });\r\n }\r\n else {\r\n return this.children_.inorderTraversal(action);\r\n }\r\n }\r\n getIterator(indexDefinition) {\r\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\r\n }\r\n getIteratorFrom(startPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getIteratorFrom(startPost, key => key);\r\n }\r\n else {\r\n const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n getReverseIterator(indexDefinition) {\r\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\r\n }\r\n getReverseIteratorFrom(endPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getReverseIteratorFrom(endPost, key => {\r\n return key;\r\n });\r\n }\r\n else {\r\n const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n compareTo(other) {\r\n if (this.isEmpty()) {\r\n if (other.isEmpty()) {\r\n return 0;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (other.isLeafNode() || other.isEmpty()) {\r\n return 1;\r\n }\r\n else if (other === MAX_NODE) {\r\n return -1;\r\n }\r\n else {\r\n // Must be another node with children.\r\n return 0;\r\n }\r\n }\r\n withIndex(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX ||\r\n this.indexMap_.hasIndex(indexDefinition)) {\r\n return this;\r\n }\r\n else {\r\n const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\r\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\r\n }\r\n }\r\n isIndexed(index) {\r\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n const otherChildrenNode = other;\r\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\r\n return false;\r\n }\r\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\r\n const thisIter = this.getIterator(PRIORITY_INDEX);\r\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\r\n let thisCurrent = thisIter.getNext();\r\n let otherCurrent = otherIter.getNext();\r\n while (thisCurrent && otherCurrent) {\r\n if (thisCurrent.name !== otherCurrent.name ||\r\n !thisCurrent.node.equals(otherCurrent.node)) {\r\n return false;\r\n }\r\n thisCurrent = thisIter.getNext();\r\n otherCurrent = otherIter.getNext();\r\n }\r\n return thisCurrent === null && otherCurrent === null;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n }\r\n /**\r\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\r\n * instead.\r\n *\r\n */\r\n resolveIndex_(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX) {\r\n return null;\r\n }\r\n else {\r\n return this.indexMap_.get(indexDefinition.toString());\r\n }\r\n }\r\n}\r\nChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\r\nclass MaxNode extends ChildrenNode {\r\n constructor() {\r\n super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);\r\n }\r\n compareTo(other) {\r\n if (other === this) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n equals(other) {\r\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\r\n return other === this;\r\n }\r\n getPriority() {\r\n return this;\r\n }\r\n getImmediateChild(childName) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n isEmpty() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Marker that will sort higher than any other snapshot.\r\n */\r\nconst MAX_NODE = new MaxNode();\r\nObject.defineProperties(NamedNode, {\r\n MIN: {\r\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\r\n },\r\n MAX: {\r\n value: new NamedNode(MAX_NAME, MAX_NODE)\r\n }\r\n});\r\n/**\r\n * Reference Extensions\r\n */\r\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\r\nLeafNode.__childrenNodeConstructor = ChildrenNode;\r\nsetMaxNode$1(MAX_NODE);\r\nsetMaxNode(MAX_NODE);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst USE_HINZE = true;\r\n/**\r\n * Constructs a snapshot node representing the passed JSON and returns it.\r\n * @param json - JSON to create a node for.\r\n * @param priority - Optional priority to use. This will be ignored if the\r\n * passed JSON contains a .priority property.\r\n */\r\nfunction nodeFromJSON(json, priority = null) {\r\n if (json === null) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n if (typeof json === 'object' && '.priority' in json) {\r\n priority = json['.priority'];\r\n }\r\n assert(priority === null ||\r\n typeof priority === 'string' ||\r\n typeof priority === 'number' ||\r\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\r\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\r\n json = json['.value'];\r\n }\r\n // Valid leaf nodes include non-objects or server-value wrapper objects\r\n if (typeof json !== 'object' || '.sv' in json) {\r\n const jsonLeaf = json;\r\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\r\n }\r\n if (!(json instanceof Array) && USE_HINZE) {\r\n const children = [];\r\n let childrenHavePriority = false;\r\n const hinzeJsonObj = json;\r\n each(hinzeJsonObj, (key, child) => {\r\n if (key.substring(0, 1) !== '.') {\r\n // Ignore metadata nodes\r\n const childNode = nodeFromJSON(child);\r\n if (!childNode.isEmpty()) {\r\n childrenHavePriority =\r\n childrenHavePriority || !childNode.getPriority().isEmpty();\r\n children.push(new NamedNode(key, childNode));\r\n }\r\n }\r\n });\r\n if (children.length === 0) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);\r\n if (childrenHavePriority) {\r\n const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\r\n }\r\n else {\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);\r\n }\r\n }\r\n else {\r\n let node = ChildrenNode.EMPTY_NODE;\r\n each(json, (key, childData) => {\r\n if (contains(json, key)) {\r\n if (key.substring(0, 1) !== '.') {\r\n // ignore metadata nodes.\r\n const childNode = nodeFromJSON(childData);\r\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\r\n node = node.updateImmediateChild(key, childNode);\r\n }\r\n }\r\n }\r\n });\r\n return node.updatePriority(nodeFromJSON(priority));\r\n }\r\n}\r\nsetNodeFromJSON(nodeFromJSON);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PathIndex extends Index {\r\n constructor(indexPath_) {\r\n super();\r\n this.indexPath_ = indexPath_;\r\n assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\r\n }\r\n extractChild(snap) {\r\n return snap.getChild(this.indexPath_);\r\n }\r\n isDefinedOn(node) {\r\n return !node.getChild(this.indexPath_).isEmpty();\r\n }\r\n compare(a, b) {\r\n const aChild = this.extractChild(a.node);\r\n const bChild = this.extractChild(b.node);\r\n const indexCmp = aChild.compareTo(bChild);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\r\n return new NamedNode(name, node);\r\n }\r\n maxPost() {\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\r\n return new NamedNode(MAX_NAME, node);\r\n }\r\n toString() {\r\n return pathSlice(this.indexPath_, 0).join('/');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ValueIndex extends Index {\r\n compare(a, b) {\r\n const indexCmp = a.node.compareTo(b.node);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return true;\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.equals(newNode);\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MAX;\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n return new NamedNode(name, valueNode);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.value';\r\n }\r\n}\r\nconst VALUE_INDEX = new ValueIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Modeled after base64 web-safe chars, but ordered by ASCII.\r\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\r\nconst MIN_PUSH_CHAR = '-';\r\nconst MAX_PUSH_CHAR = 'z';\r\nconst MAX_KEY_LEN = 786;\r\n/**\r\n * Fancy ID generator that creates 20-character string identifiers with the\r\n * following properties:\r\n *\r\n * 1. They're based on timestamp so that they sort *after* any existing ids.\r\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\r\n * collide with other clients' IDs.\r\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\r\n * that will sort properly).\r\n * 4. They're monotonically increasing. Even if you generate more than one in\r\n * the same timestamp, the latter ones will sort after the former ones. We do\r\n * this by using the previous random bits but \"incrementing\" them by 1 (only\r\n * in the case of a timestamp collision).\r\n */\r\nconst nextPushId = (function () {\r\n // Timestamp of last push, used to prevent local collisions if you push twice\r\n // in one ms.\r\n let lastPushTime = 0;\r\n // We generate 72-bits of randomness which get turned into 12 characters and\r\n // appended to the timestamp to prevent collisions with other clients. We\r\n // store the last characters we generated because in the event of a collision,\r\n // we'll use those same characters except \"incremented\" by one.\r\n const lastRandChars = [];\r\n return function (now) {\r\n const duplicateTime = now === lastPushTime;\r\n lastPushTime = now;\r\n let i;\r\n const timeStampChars = new Array(8);\r\n for (i = 7; i >= 0; i--) {\r\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\r\n // NOTE: Can't use << here because javascript will convert to int and lose\r\n // the upper bits.\r\n now = Math.floor(now / 64);\r\n }\r\n assert(now === 0, 'Cannot push at time == 0');\r\n let id = timeStampChars.join('');\r\n if (!duplicateTime) {\r\n for (i = 0; i < 12; i++) {\r\n lastRandChars[i] = Math.floor(Math.random() * 64);\r\n }\r\n }\r\n else {\r\n // If the timestamp hasn't changed since last push, use the same random\r\n // number, except incremented by 1.\r\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\r\n lastRandChars[i] = 0;\r\n }\r\n lastRandChars[i]++;\r\n }\r\n for (i = 0; i < 12; i++) {\r\n id += PUSH_CHARS.charAt(lastRandChars[i]);\r\n }\r\n assert(id.length === 20, 'nextPushId: Length should be 20.');\r\n return id;\r\n };\r\n})();\r\nconst successor = function (key) {\r\n if (key === '' + INTEGER_32_MAX) {\r\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\r\n return MIN_PUSH_CHAR;\r\n }\r\n const keyAsInt = tryParseInt(key);\r\n if (keyAsInt != null) {\r\n return '' + (keyAsInt + 1);\r\n }\r\n const next = new Array(key.length);\r\n for (let i = 0; i < next.length; i++) {\r\n next[i] = key.charAt(i);\r\n }\r\n if (next.length < MAX_KEY_LEN) {\r\n next.push(MIN_PUSH_CHAR);\r\n return next.join('');\r\n }\r\n let i = next.length - 1;\r\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\r\n i--;\r\n }\r\n // `successor` was called on the largest possible key, so return the\r\n // MAX_NAME, which sorts larger than all keys.\r\n if (i === -1) {\r\n return MAX_NAME;\r\n }\r\n const source = next[i];\r\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\r\n next[i] = sourcePlusOne;\r\n return next.slice(0, i + 1).join('');\r\n};\r\n// `key` is assumed to be non-empty.\r\nconst predecessor = function (key) {\r\n if (key === '' + INTEGER_32_MIN) {\r\n return MIN_NAME;\r\n }\r\n const keyAsInt = tryParseInt(key);\r\n if (keyAsInt != null) {\r\n return '' + (keyAsInt - 1);\r\n }\r\n const next = new Array(key.length);\r\n for (let i = 0; i < next.length; i++) {\r\n next[i] = key.charAt(i);\r\n }\r\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\r\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\r\n // than that, `predecessor(predecessor(key))`, is\r\n //\r\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\r\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\r\n //\r\n // analogous to increment/decrement for base-10 integers.\r\n //\r\n // This works because lexigographic comparison works character-by-character,\r\n // using length as a tie-breaker if one key is a prefix of the other.\r\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\r\n if (next.length === 1) {\r\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\r\n return '' + INTEGER_32_MAX;\r\n }\r\n delete next[next.length - 1];\r\n return next.join('');\r\n }\r\n // Replace the last character with it's immediate predecessor, and\r\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\r\n // lexicographically largest possible key smaller than `key`.\r\n next[next.length - 1] = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(next[next.length - 1]) - 1);\r\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction changeValue(snapshotNode) {\r\n return { type: \"value\" /* VALUE */, snapshotNode };\r\n}\r\nfunction changeChildAdded(childName, snapshotNode) {\r\n return { type: \"child_added\" /* CHILD_ADDED */, snapshotNode, childName };\r\n}\r\nfunction changeChildRemoved(childName, snapshotNode) {\r\n return { type: \"child_removed\" /* CHILD_REMOVED */, snapshotNode, childName };\r\n}\r\nfunction changeChildChanged(childName, snapshotNode, oldSnap) {\r\n return {\r\n type: \"child_changed\" /* CHILD_CHANGED */,\r\n snapshotNode,\r\n childName,\r\n oldSnap\r\n };\r\n}\r\nfunction changeChildMoved(childName, snapshotNode) {\r\n return { type: \"child_moved\" /* CHILD_MOVED */, snapshotNode, childName };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\r\n */\r\nclass IndexedFilter {\r\n constructor(index_) {\r\n this.index_ = index_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\r\n const oldChild = snap.getImmediateChild(key);\r\n // Check if anything actually changed.\r\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\r\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\r\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\r\n // to avoid treating these cases as \"nothing changed.\"\r\n if (oldChild.isEmpty() === newChild.isEmpty()) {\r\n // Nothing changed.\r\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\r\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\r\n return snap;\r\n }\r\n }\r\n if (optChangeAccumulator != null) {\r\n if (newChild.isEmpty()) {\r\n if (snap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));\r\n }\r\n else {\r\n assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\r\n }\r\n }\r\n else if (oldChild.isEmpty()) {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));\r\n }\r\n }\r\n if (snap.isLeafNode() && newChild.isEmpty()) {\r\n return snap;\r\n }\r\n else {\r\n // Make sure the node is indexed\r\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (optChangeAccumulator != null) {\r\n if (!oldSnap.isLeafNode()) {\r\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!newSnap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));\r\n }\r\n });\r\n }\r\n if (!newSnap.isLeafNode()) {\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (oldSnap.hasChild(key)) {\r\n const oldChild = oldSnap.getImmediateChild(key);\r\n if (!oldChild.equals(childNode)) {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));\r\n }\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));\r\n }\r\n });\r\n }\r\n }\r\n return newSnap.withIndex(this.index_);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n if (oldSnap.isEmpty()) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n else {\r\n return oldSnap.updatePriority(newPriority);\r\n }\r\n }\r\n filtersNodes() {\r\n return false;\r\n }\r\n getIndexedFilter() {\r\n return this;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\r\n */\r\nclass RangedFilter {\r\n constructor(params) {\r\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\r\n this.index_ = params.getIndex();\r\n this.startPost_ = RangedFilter.getStartPost_(params);\r\n this.endPost_ = RangedFilter.getEndPost_(params);\r\n }\r\n getStartPost() {\r\n return this.startPost_;\r\n }\r\n getEndPost() {\r\n return this.endPost_;\r\n }\r\n matches(node) {\r\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\r\n this.index_.compare(node, this.getEndPost()) <= 0);\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (newSnap.isLeafNode()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n newSnap = ChildrenNode.EMPTY_NODE;\r\n }\r\n let filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n const self = this;\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!self.matches(new NamedNode(key, childNode))) {\r\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\r\n }\r\n });\r\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.indexedFilter_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n static getStartPost_(params) {\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\r\n }\r\n else {\r\n return params.getIndex().minPost();\r\n }\r\n }\r\n static getEndPost_(params) {\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\r\n }\r\n else {\r\n return params.getIndex().maxPost();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\r\n */\r\nclass LimitedFilter {\r\n constructor(params) {\r\n this.rangedFilter_ = new RangedFilter(params);\r\n this.index_ = params.getIndex();\r\n this.limit_ = params.getLimit();\r\n this.reverse_ = !params.isViewFromLeft();\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n if (snap.getImmediateChild(key).equals(newChild)) {\r\n // No change\r\n return snap;\r\n }\r\n else if (snap.numChildren() < this.limit_) {\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n else {\r\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n let filtered;\r\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n }\r\n else {\r\n if (this.limit_ * 2 < newSnap.numChildren() &&\r\n newSnap.isIndexed(this.index_)) {\r\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n // anchor to the startPost, endPost, or last element as appropriate\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\r\n }\r\n else {\r\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext() && count < this.limit_) {\r\n const next = iterator.getNext();\r\n let inRange;\r\n if (this.reverse_) {\r\n inRange =\r\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\r\n }\r\n else {\r\n inRange =\r\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\r\n }\r\n if (inRange) {\r\n filtered = filtered.updateImmediateChild(next.name, next.node);\r\n count++;\r\n }\r\n else {\r\n // if we have reached the end post, we cannot keep adding elemments\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\r\n filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n let startPost;\r\n let endPost;\r\n let cmp;\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = filtered.getReverseIterator(this.index_);\r\n startPost = this.rangedFilter_.getEndPost();\r\n endPost = this.rangedFilter_.getStartPost();\r\n const indexCompare = this.index_.getCompare();\r\n cmp = (a, b) => indexCompare(b, a);\r\n }\r\n else {\r\n iterator = filtered.getIterator(this.index_);\r\n startPost = this.rangedFilter_.getStartPost();\r\n endPost = this.rangedFilter_.getEndPost();\r\n cmp = this.index_.getCompare();\r\n }\r\n let count = 0;\r\n let foundStartPost = false;\r\n while (iterator.hasNext()) {\r\n const next = iterator.getNext();\r\n if (!foundStartPost && cmp(startPost, next) <= 0) {\r\n // start adding\r\n foundStartPost = true;\r\n }\r\n const inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\r\n if (inRange) {\r\n count++;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n }\r\n }\r\n }\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.rangedFilter_.getIndexedFilter();\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {\r\n // TODO: rename all cache stuff etc to general snap terminology\r\n let cmp;\r\n if (this.reverse_) {\r\n const indexCmp = this.index_.getCompare();\r\n cmp = (a, b) => indexCmp(b, a);\r\n }\r\n else {\r\n cmp = this.index_.getCompare();\r\n }\r\n const oldEventCache = snap;\r\n assert(oldEventCache.numChildren() === this.limit_, '');\r\n const newChildNamedNode = new NamedNode(childKey, childSnap);\r\n const windowBoundary = this.reverse_\r\n ? oldEventCache.getFirstChild(this.index_)\r\n : oldEventCache.getLastChild(this.index_);\r\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\r\n if (oldEventCache.hasChild(childKey)) {\r\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\r\n let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\r\n while (nextChild != null &&\r\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {\r\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\r\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\r\n // the limited filter...\r\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\r\n }\r\n const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\r\n const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\r\n if (remainsInWindow) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));\r\n }\r\n return oldEventCache.updateImmediateChild(childKey, childSnap);\r\n }\r\n else {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));\r\n }\r\n const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\r\n const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\r\n if (nextChildInRange) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));\r\n }\r\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\r\n }\r\n else {\r\n return newEventCache;\r\n }\r\n }\r\n }\r\n else if (childSnap.isEmpty()) {\r\n // we're deleting a node, but it was not in the window, so ignore it\r\n return snap;\r\n }\r\n else if (inRange) {\r\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));\r\n changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));\r\n }\r\n return oldEventCache\r\n .updateImmediateChild(childKey, childSnap)\r\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\r\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\r\n * user-facing API level, so it is not done here.\r\n *\r\n * @internal\r\n */\r\nclass QueryParams {\r\n constructor() {\r\n this.limitSet_ = false;\r\n this.startSet_ = false;\r\n this.startNameSet_ = false;\r\n this.startAfterSet_ = false;\r\n this.endSet_ = false;\r\n this.endNameSet_ = false;\r\n this.endBeforeSet_ = false;\r\n this.limit_ = 0;\r\n this.viewFrom_ = '';\r\n this.indexStartValue_ = null;\r\n this.indexStartName_ = '';\r\n this.indexEndValue_ = null;\r\n this.indexEndName_ = '';\r\n this.index_ = PRIORITY_INDEX;\r\n }\r\n hasStart() {\r\n return this.startSet_;\r\n }\r\n hasStartAfter() {\r\n return this.startAfterSet_;\r\n }\r\n hasEndBefore() {\r\n return this.endBeforeSet_;\r\n }\r\n /**\r\n * @returns True if it would return from left.\r\n */\r\n isViewFromLeft() {\r\n if (this.viewFrom_ === '') {\r\n // limit(), rather than limitToFirst or limitToLast was called.\r\n // This means that only one of startSet_ and endSet_ is true. Use them\r\n // to calculate which side of the view to anchor to. If neither is set,\r\n // anchor to the end.\r\n return this.startSet_;\r\n }\r\n else {\r\n return this.viewFrom_ === \"l\" /* VIEW_FROM_LEFT */;\r\n }\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true\r\n */\r\n getIndexStartValue() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n return this.indexStartValue_;\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true.\r\n * Returns the starting key name for the range defined by these query parameters\r\n */\r\n getIndexStartName() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n if (this.startNameSet_) {\r\n return this.indexStartName_;\r\n }\r\n else {\r\n return MIN_NAME;\r\n }\r\n }\r\n hasEnd() {\r\n return this.endSet_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n */\r\n getIndexEndValue() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n return this.indexEndValue_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * Returns the end key name for the range defined by these query parameters\r\n */\r\n getIndexEndName() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n if (this.endNameSet_) {\r\n return this.indexEndName_;\r\n }\r\n else {\r\n return MAX_NAME;\r\n }\r\n }\r\n hasLimit() {\r\n return this.limitSet_;\r\n }\r\n /**\r\n * @returns True if a limit has been set and it has been explicitly anchored\r\n */\r\n hasAnchoredLimit() {\r\n return this.limitSet_ && this.viewFrom_ !== '';\r\n }\r\n /**\r\n * Only valid to call if hasLimit() returns true\r\n */\r\n getLimit() {\r\n assert(this.limitSet_, 'Only valid if limit has been set');\r\n return this.limit_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n loadsAllData() {\r\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\r\n }\r\n isDefault() {\r\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\r\n }\r\n copy() {\r\n const copy = new QueryParams();\r\n copy.limitSet_ = this.limitSet_;\r\n copy.limit_ = this.limit_;\r\n copy.startSet_ = this.startSet_;\r\n copy.indexStartValue_ = this.indexStartValue_;\r\n copy.startNameSet_ = this.startNameSet_;\r\n copy.indexStartName_ = this.indexStartName_;\r\n copy.endSet_ = this.endSet_;\r\n copy.indexEndValue_ = this.indexEndValue_;\r\n copy.endNameSet_ = this.endNameSet_;\r\n copy.indexEndName_ = this.indexEndName_;\r\n copy.index_ = this.index_;\r\n copy.viewFrom_ = this.viewFrom_;\r\n return copy;\r\n }\r\n}\r\nfunction queryParamsGetNodeFilter(queryParams) {\r\n if (queryParams.loadsAllData()) {\r\n return new IndexedFilter(queryParams.getIndex());\r\n }\r\n else if (queryParams.hasLimit()) {\r\n return new LimitedFilter(queryParams);\r\n }\r\n else {\r\n return new RangedFilter(queryParams);\r\n }\r\n}\r\nfunction queryParamsLimitToFirst(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"l\" /* VIEW_FROM_LEFT */;\r\n return newParams;\r\n}\r\nfunction queryParamsLimitToLast(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"r\" /* VIEW_FROM_RIGHT */;\r\n return newParams;\r\n}\r\nfunction queryParamsStartAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.startSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexStartValue_ = indexValue;\r\n if (key != null) {\r\n newParams.startNameSet_ = true;\r\n newParams.indexStartName_ = key;\r\n }\r\n else {\r\n newParams.startNameSet_ = false;\r\n newParams.indexStartName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsStartAfter(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX) {\r\n if (typeof indexValue === 'string') {\r\n indexValue = successor(indexValue);\r\n }\r\n params = queryParamsStartAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n let childKey;\r\n if (key == null) {\r\n childKey = MAX_NAME;\r\n }\r\n else {\r\n childKey = successor(key);\r\n }\r\n params = queryParamsStartAt(queryParams, indexValue, childKey);\r\n }\r\n params.startAfterSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsEndAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.endSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexEndValue_ = indexValue;\r\n if (key !== undefined) {\r\n newParams.endNameSet_ = true;\r\n newParams.indexEndName_ = key;\r\n }\r\n else {\r\n newParams.endNameSet_ = false;\r\n newParams.indexEndName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsEndBefore(queryParams, indexValue, key) {\r\n let childKey;\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX) {\r\n if (typeof indexValue === 'string') {\r\n indexValue = predecessor(indexValue);\r\n }\r\n params = queryParamsEndAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n if (key == null) {\r\n childKey = MIN_NAME;\r\n }\r\n else {\r\n childKey = predecessor(key);\r\n }\r\n params = queryParamsEndAt(queryParams, indexValue, childKey);\r\n }\r\n params.endBeforeSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsOrderBy(queryParams, index) {\r\n const newParams = queryParams.copy();\r\n newParams.index_ = index;\r\n return newParams;\r\n}\r\n/**\r\n * Returns a set of REST query string parameters representing this query.\r\n *\r\n * @returns query string parameters\r\n */\r\nfunction queryParamsToRestQueryStringParameters(queryParams) {\r\n const qs = {};\r\n if (queryParams.isDefault()) {\r\n return qs;\r\n }\r\n let orderBy;\r\n if (queryParams.index_ === PRIORITY_INDEX) {\r\n orderBy = \"$priority\" /* PRIORITY_INDEX */;\r\n }\r\n else if (queryParams.index_ === VALUE_INDEX) {\r\n orderBy = \"$value\" /* VALUE_INDEX */;\r\n }\r\n else if (queryParams.index_ === KEY_INDEX) {\r\n orderBy = \"$key\" /* KEY_INDEX */;\r\n }\r\n else {\r\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\r\n orderBy = queryParams.index_.toString();\r\n }\r\n qs[\"orderBy\" /* ORDER_BY */] = stringify(orderBy);\r\n if (queryParams.startSet_) {\r\n qs[\"startAt\" /* START_AT */] = stringify(queryParams.indexStartValue_);\r\n if (queryParams.startNameSet_) {\r\n qs[\"startAt\" /* START_AT */] +=\r\n ',' + stringify(queryParams.indexStartName_);\r\n }\r\n }\r\n if (queryParams.endSet_) {\r\n qs[\"endAt\" /* END_AT */] = stringify(queryParams.indexEndValue_);\r\n if (queryParams.endNameSet_) {\r\n qs[\"endAt\" /* END_AT */] +=\r\n ',' + stringify(queryParams.indexEndName_);\r\n }\r\n }\r\n if (queryParams.limitSet_) {\r\n if (queryParams.isViewFromLeft()) {\r\n qs[\"limitToFirst\" /* LIMIT_TO_FIRST */] = queryParams.limit_;\r\n }\r\n else {\r\n qs[\"limitToLast\" /* LIMIT_TO_LAST */] = queryParams.limit_;\r\n }\r\n }\r\n return qs;\r\n}\r\nfunction queryParamsGetQueryObject(queryParams) {\r\n const obj = {};\r\n if (queryParams.startSet_) {\r\n obj[\"sp\" /* INDEX_START_VALUE */] =\r\n queryParams.indexStartValue_;\r\n if (queryParams.startNameSet_) {\r\n obj[\"sn\" /* INDEX_START_NAME */] =\r\n queryParams.indexStartName_;\r\n }\r\n }\r\n if (queryParams.endSet_) {\r\n obj[\"ep\" /* INDEX_END_VALUE */] = queryParams.indexEndValue_;\r\n if (queryParams.endNameSet_) {\r\n obj[\"en\" /* INDEX_END_NAME */] = queryParams.indexEndName_;\r\n }\r\n }\r\n if (queryParams.limitSet_) {\r\n obj[\"l\" /* LIMIT */] = queryParams.limit_;\r\n let viewFrom = queryParams.viewFrom_;\r\n if (viewFrom === '') {\r\n if (queryParams.isViewFromLeft()) {\r\n viewFrom = \"l\" /* VIEW_FROM_LEFT */;\r\n }\r\n else {\r\n viewFrom = \"r\" /* VIEW_FROM_RIGHT */;\r\n }\r\n }\r\n obj[\"vf\" /* VIEW_FROM */] = viewFrom;\r\n }\r\n // For now, priority index is the default, so we only specify if it's some other index\r\n if (queryParams.index_ !== PRIORITY_INDEX) {\r\n obj[\"i\" /* INDEX */] = queryParams.index_.toString();\r\n }\r\n return obj;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of ServerActions that communicates with the server via REST requests.\r\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\r\n * persistent connection (using WebSockets or long-polling)\r\n */\r\nclass ReadonlyRestClient extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n /** @private {function(...[*])} */\r\n this.log_ = logWrapper('p:rest:');\r\n /**\r\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\r\n * that's been removed. :-/\r\n */\r\n this.listens_ = {};\r\n }\r\n reportStats(stats) {\r\n throw new Error('Method not implemented.');\r\n }\r\n static getListenId_(query, tag) {\r\n if (tag !== undefined) {\r\n return 'tag$' + tag;\r\n }\r\n else {\r\n assert(query._queryParams.isDefault(), \"should have a tag if it's not a default query.\");\r\n return query._path.toString();\r\n }\r\n }\r\n /** @inheritDoc */\r\n listen(query, currentHashFn, tag, onComplete) {\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\r\n // Mark this listener so we can tell if it's removed.\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n const thisListen = {};\r\n this.listens_[listenId] = thisListen;\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\r\n }\r\n if (safeGet(this.listens_, listenId) === thisListen) {\r\n let status;\r\n if (!error) {\r\n status = 'ok';\r\n }\r\n else if (error === 401) {\r\n status = 'permission_denied';\r\n }\r\n else {\r\n status = 'rest_error:' + error;\r\n }\r\n onComplete(status, null);\r\n }\r\n });\r\n }\r\n /** @inheritDoc */\r\n unlisten(query, tag) {\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n delete this.listens_[listenId];\r\n }\r\n get(query) {\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n const pathString = query._path.toString();\r\n const deferred = new Deferred();\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, \r\n /*isMerge=*/ false, \r\n /*tag=*/ null);\r\n deferred.resolve(data);\r\n }\r\n else {\r\n deferred.reject(new Error(data));\r\n }\r\n });\r\n return deferred.promise;\r\n }\r\n /** @inheritDoc */\r\n refreshAuthToken(token) {\r\n // no-op since we just always call getToken.\r\n }\r\n /**\r\n * Performs a REST request to the given path, with the provided query string parameters,\r\n * and any auth credentials we have.\r\n */\r\n restRequest_(pathString, queryStringParameters = {}, callback) {\r\n queryStringParameters['format'] = 'export';\r\n return Promise.all([\r\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\r\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\r\n ]).then(([authToken, appCheckToken]) => {\r\n if (authToken && authToken.accessToken) {\r\n queryStringParameters['auth'] = authToken.accessToken;\r\n }\r\n if (appCheckToken && appCheckToken.token) {\r\n queryStringParameters['ac'] = appCheckToken.token;\r\n }\r\n const url = (this.repoInfo_.secure ? 'https://' : 'http://') +\r\n this.repoInfo_.host +\r\n pathString +\r\n '?' +\r\n 'ns=' +\r\n this.repoInfo_.namespace +\r\n querystring(queryStringParameters);\r\n this.log_('Sending REST request for ' + url);\r\n const xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange = () => {\r\n if (callback && xhr.readyState === 4) {\r\n this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\r\n let res = null;\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n try {\r\n res = jsonEval(xhr.responseText);\r\n }\r\n catch (e) {\r\n warn('Failed to parse JSON response for ' +\r\n url +\r\n ': ' +\r\n xhr.responseText);\r\n }\r\n callback(null, res);\r\n }\r\n else {\r\n // 401 and 404 are expected.\r\n if (xhr.status !== 401 && xhr.status !== 404) {\r\n warn('Got unsuccessful REST response for ' +\r\n url +\r\n ' Status: ' +\r\n xhr.status);\r\n }\r\n callback(xhr.status);\r\n }\r\n callback = null;\r\n }\r\n };\r\n xhr.open('GET', url, /*asynchronous=*/ true);\r\n xhr.send();\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\r\n */\r\nclass SnapshotHolder {\r\n constructor() {\r\n this.rootNode_ = ChildrenNode.EMPTY_NODE;\r\n }\r\n getNode(path) {\r\n return this.rootNode_.getChild(path);\r\n }\r\n updateSnapshot(path, newSnapshotNode) {\r\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newSparseSnapshotTree() {\r\n return {\r\n value: null,\r\n children: new Map()\r\n };\r\n}\r\n/**\r\n * Stores the given node at the specified path. If there is already a node\r\n * at a shallower path, it merges the new data into that snapshot node.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @param data - The new data, or null.\r\n */\r\nfunction sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = data;\r\n sparseSnapshotTree.children.clear();\r\n }\r\n else if (sparseSnapshotTree.value !== null) {\r\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n if (!sparseSnapshotTree.children.has(childKey)) {\r\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\r\n }\r\n const child = sparseSnapshotTree.children.get(childKey);\r\n path = pathPopFront(path);\r\n sparseSnapshotTreeRemember(child, path, data);\r\n }\r\n}\r\n/**\r\n * Purge the data at path from the cache.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @returns True if this node should now be removed.\r\n */\r\nfunction sparseSnapshotTreeForget(sparseSnapshotTree, path) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = null;\r\n sparseSnapshotTree.children.clear();\r\n return true;\r\n }\r\n else {\r\n if (sparseSnapshotTree.value !== null) {\r\n if (sparseSnapshotTree.value.isLeafNode()) {\r\n // We're trying to forget a node that doesn't exist\r\n return false;\r\n }\r\n else {\r\n const value = sparseSnapshotTree.value;\r\n sparseSnapshotTree.value = null;\r\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\r\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\r\n });\r\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\r\n }\r\n }\r\n else if (sparseSnapshotTree.children.size > 0) {\r\n const childKey = pathGetFront(path);\r\n path = pathPopFront(path);\r\n if (sparseSnapshotTree.children.has(childKey)) {\r\n const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);\r\n if (safeToRemove) {\r\n sparseSnapshotTree.children.delete(childKey);\r\n }\r\n }\r\n return sparseSnapshotTree.children.size === 0;\r\n }\r\n else {\r\n return true;\r\n }\r\n }\r\n}\r\n/**\r\n * Recursively iterates through all of the stored tree and calls the\r\n * callback on each one.\r\n *\r\n * @param prefixPath - Path to look up node for.\r\n * @param func - The function to invoke for each tree.\r\n */\r\nfunction sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {\r\n if (sparseSnapshotTree.value !== null) {\r\n func(prefixPath, sparseSnapshotTree.value);\r\n }\r\n else {\r\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\r\n const path = new Path(prefixPath.toString() + '/' + key);\r\n sparseSnapshotTreeForEachTree(tree, path, func);\r\n });\r\n }\r\n}\r\n/**\r\n * Iterates through each immediate child and triggers the callback.\r\n * Only seems to be used in tests.\r\n *\r\n * @param func - The function to invoke for each child.\r\n */\r\nfunction sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {\r\n sparseSnapshotTree.children.forEach((tree, key) => {\r\n func(key, tree);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the delta from the previous call to get stats.\r\n *\r\n * @param collection_ - The collection to \"listen\" to.\r\n */\r\nclass StatsListener {\r\n constructor(collection_) {\r\n this.collection_ = collection_;\r\n this.last_ = null;\r\n }\r\n get() {\r\n const newStats = this.collection_.get();\r\n const delta = Object.assign({}, newStats);\r\n if (this.last_) {\r\n each(this.last_, (stat, value) => {\r\n delta[stat] = delta[stat] - value;\r\n });\r\n }\r\n this.last_ = newStats;\r\n return delta;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\r\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\r\n// seconds to try to ensure the Firebase connection is established / settled.\r\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\r\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\r\n// We'll continue to report stats on average every 5 minutes.\r\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\r\nclass StatsReporter {\r\n constructor(collection, server_) {\r\n this.server_ = server_;\r\n this.statsToReport_ = {};\r\n this.statsListener_ = new StatsListener(collection);\r\n const timeout = FIRST_STATS_MIN_TIME +\r\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\r\n }\r\n reportStats_() {\r\n const stats = this.statsListener_.get();\r\n const reportedStats = {};\r\n let haveStatsToReport = false;\r\n each(stats, (stat, value) => {\r\n if (value > 0 && contains(this.statsToReport_, stat)) {\r\n reportedStats[stat] = value;\r\n haveStatsToReport = true;\r\n }\r\n });\r\n if (haveStatsToReport) {\r\n this.server_.reportStats(reportedStats);\r\n }\r\n // queue our next run.\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n *\r\n * @enum\r\n */\r\nvar OperationType;\r\n(function (OperationType) {\r\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\r\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\r\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\r\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\r\n})(OperationType || (OperationType = {}));\r\nfunction newOperationSourceUser() {\r\n return {\r\n fromUser: true,\r\n fromServer: false,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServer() {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServerTaggedQuery(queryId) {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId,\r\n tagged: true\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AckUserWrite {\r\n /**\r\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\r\n */\r\n constructor(\r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ affectedTree, \r\n /** @inheritDoc */ revert) {\r\n this.path = path;\r\n this.affectedTree = affectedTree;\r\n this.revert = revert;\r\n /** @inheritDoc */\r\n this.type = OperationType.ACK_USER_WRITE;\r\n /** @inheritDoc */\r\n this.source = newOperationSourceUser();\r\n }\r\n operationForChild(childName) {\r\n if (!pathIsEmpty(this.path)) {\r\n assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');\r\n return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);\r\n }\r\n else if (this.affectedTree.value != null) {\r\n assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\r\n // All child locations are affected as well; just return same operation.\r\n return this;\r\n }\r\n else {\r\n const childTree = this.affectedTree.subtree(new Path(childName));\r\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ListenComplete {\r\n constructor(source, path) {\r\n this.source = source;\r\n this.path = path;\r\n /** @inheritDoc */\r\n this.type = OperationType.LISTEN_COMPLETE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new ListenComplete(this.source, newEmptyPath());\r\n }\r\n else {\r\n return new ListenComplete(this.source, pathPopFront(this.path));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Overwrite {\r\n constructor(source, path, snap) {\r\n this.source = source;\r\n this.path = path;\r\n this.snap = snap;\r\n /** @inheritDoc */\r\n this.type = OperationType.OVERWRITE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));\r\n }\r\n else {\r\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Merge {\r\n constructor(\r\n /** @inheritDoc */ source, \r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ children) {\r\n this.source = source;\r\n this.path = path;\r\n this.children = children;\r\n /** @inheritDoc */\r\n this.type = OperationType.MERGE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n const childTree = this.children.subtree(new Path(childName));\r\n if (childTree.isEmpty()) {\r\n // This child is unaffected\r\n return null;\r\n }\r\n else if (childTree.value) {\r\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\r\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\r\n }\r\n else {\r\n // This is a merge at a deeper level\r\n return new Merge(this.source, newEmptyPath(), childTree);\r\n }\r\n }\r\n else {\r\n assert(pathGetFront(this.path) === childName, \"Can't get a merge for a child not on the path of the operation\");\r\n return new Merge(this.source, pathPopFront(this.path), this.children);\r\n }\r\n }\r\n toString() {\r\n return ('Operation(' +\r\n this.path +\r\n ': ' +\r\n this.source.toString() +\r\n ' merge: ' +\r\n this.children.toString() +\r\n ')');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\r\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\r\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\r\n * whether a node potentially had children removed due to a filter.\r\n */\r\nclass CacheNode {\r\n constructor(node_, fullyInitialized_, filtered_) {\r\n this.node_ = node_;\r\n this.fullyInitialized_ = fullyInitialized_;\r\n this.filtered_ = filtered_;\r\n }\r\n /**\r\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\r\n */\r\n isFullyInitialized() {\r\n return this.fullyInitialized_;\r\n }\r\n /**\r\n * Returns whether this node is potentially missing children due to a filter applied to the node\r\n */\r\n isFiltered() {\r\n return this.filtered_;\r\n }\r\n isCompleteForPath(path) {\r\n if (pathIsEmpty(path)) {\r\n return this.isFullyInitialized() && !this.filtered_;\r\n }\r\n const childKey = pathGetFront(path);\r\n return this.isCompleteForChild(childKey);\r\n }\r\n isCompleteForChild(key) {\r\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\r\n }\r\n getNode() {\r\n return this.node_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\r\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\r\n * for details.\r\n *\r\n */\r\nclass EventGenerator {\r\n constructor(query_) {\r\n this.query_ = query_;\r\n this.index_ = this.query_._queryParams.getIndex();\r\n }\r\n}\r\n/**\r\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\r\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\r\n *\r\n * Notes:\r\n * - child_moved events will be synthesized at this time for any child_changed events that affect\r\n * our index.\r\n * - prevName will be calculated based on the index ordering.\r\n */\r\nfunction eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {\r\n const events = [];\r\n const moves = [];\r\n changes.forEach(change => {\r\n if (change.type === \"child_changed\" /* CHILD_CHANGED */ &&\r\n eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\r\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\r\n }\r\n });\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_removed\" /* CHILD_REMOVED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_added\" /* CHILD_ADDED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_moved\" /* CHILD_MOVED */, moves, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_changed\" /* CHILD_CHANGED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"value\" /* VALUE */, changes, eventRegistrations, eventCache);\r\n return events;\r\n}\r\n/**\r\n * Given changes of a single change type, generate the corresponding events.\r\n */\r\nfunction eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {\r\n const filteredChanges = changes.filter(change => change.type === eventType);\r\n filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));\r\n filteredChanges.forEach(change => {\r\n const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);\r\n registrations.forEach(registration => {\r\n if (registration.respondsTo(change.type)) {\r\n events.push(registration.createEvent(materializedChange, eventGenerator.query_));\r\n }\r\n });\r\n });\r\n}\r\nfunction eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {\r\n if (change.type === 'value' || change.type === 'child_removed') {\r\n return change;\r\n }\r\n else {\r\n change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);\r\n return change;\r\n }\r\n}\r\nfunction eventGeneratorCompareChanges(eventGenerator, a, b) {\r\n if (a.childName == null || b.childName == null) {\r\n throw assertionError('Should only compare child_ events.');\r\n }\r\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\r\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\r\n return eventGenerator.index_.compare(aWrapped, bWrapped);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewCache(eventCache, serverCache) {\r\n return { eventCache, serverCache };\r\n}\r\nfunction viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {\r\n return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);\r\n}\r\nfunction viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {\r\n return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));\r\n}\r\nfunction viewCacheGetCompleteEventSnap(viewCache) {\r\n return viewCache.eventCache.isFullyInitialized()\r\n ? viewCache.eventCache.getNode()\r\n : null;\r\n}\r\nfunction viewCacheGetCompleteServerSnap(viewCache) {\r\n return viewCache.serverCache.isFullyInitialized()\r\n ? viewCache.serverCache.getNode()\r\n : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet emptyChildrenSingleton;\r\n/**\r\n * Singleton empty children collection.\r\n *\r\n */\r\nconst EmptyChildren = () => {\r\n if (!emptyChildrenSingleton) {\r\n emptyChildrenSingleton = new SortedMap(stringCompare);\r\n }\r\n return emptyChildrenSingleton;\r\n};\r\n/**\r\n * A tree with immutable elements.\r\n */\r\nclass ImmutableTree {\r\n constructor(value, children = EmptyChildren()) {\r\n this.value = value;\r\n this.children = children;\r\n }\r\n static fromObject(obj) {\r\n let tree = new ImmutableTree(null);\r\n each(obj, (childPath, childSnap) => {\r\n tree = tree.set(new Path(childPath), childSnap);\r\n });\r\n return tree;\r\n }\r\n /**\r\n * True if the value is empty and there are no children\r\n */\r\n isEmpty() {\r\n return this.value === null && this.children.isEmpty();\r\n }\r\n /**\r\n * Given a path and predicate, return the first node and the path to that node\r\n * where the predicate returns true.\r\n *\r\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\r\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\r\n *\r\n * @param relativePath - The remainder of the path\r\n * @param predicate - The predicate to satisfy to return a node\r\n */\r\n findRootMostMatchingPathAndValue(relativePath, predicate) {\r\n if (this.value != null && predicate(this.value)) {\r\n return { path: newEmptyPath(), value: this.value };\r\n }\r\n else {\r\n if (pathIsEmpty(relativePath)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child !== null) {\r\n const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);\r\n if (childExistingPathAndValue != null) {\r\n const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);\r\n return { path: fullPath, value: childExistingPathAndValue.value };\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * Find, if it exists, the shortest subpath of the given path that points a defined\r\n * value in the tree\r\n */\r\n findRootMostValueAndPath(relativePath) {\r\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\r\n }\r\n /**\r\n * @returns The subtree at the given path\r\n */\r\n subtree(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const childTree = this.children.get(front);\r\n if (childTree !== null) {\r\n return childTree.subtree(pathPopFront(relativePath));\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Sets a value at the specified path.\r\n *\r\n * @param relativePath - Path to set value at.\r\n * @param toSet - Value to set.\r\n * @returns Resulting tree.\r\n */\r\n set(relativePath, toSet) {\r\n if (pathIsEmpty(relativePath)) {\r\n return new ImmutableTree(toSet, this.children);\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.set(pathPopFront(relativePath), toSet);\r\n const newChildren = this.children.insert(front, newChild);\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Removes the value at the specified path.\r\n *\r\n * @param relativePath - Path to value to remove.\r\n * @returns Resulting tree.\r\n */\r\n remove(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n if (this.children.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(null, this.children);\r\n }\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n const newChild = child.remove(pathPopFront(relativePath));\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n if (this.value === null && newChildren.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n else {\r\n return this;\r\n }\r\n }\r\n }\r\n /**\r\n * Gets a value from the tree.\r\n *\r\n * @param relativePath - Path to get value for.\r\n * @returns Value at path, or null.\r\n */\r\n get(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this.value;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n return child.get(pathPopFront(relativePath));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n /**\r\n * Replace the subtree at the specified path with the given new tree.\r\n *\r\n * @param relativePath - Path to replace subtree for.\r\n * @param newTree - New tree.\r\n * @returns Resulting tree.\r\n */\r\n setTree(relativePath, newTree) {\r\n if (pathIsEmpty(relativePath)) {\r\n return newTree;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Performs a depth first fold on this tree. Transforms a tree into a single\r\n * value, given a function that operates on the path to a node, an optional\r\n * current value, and a map of child names to folded subtrees\r\n */\r\n fold(fn) {\r\n return this.fold_(newEmptyPath(), fn);\r\n }\r\n /**\r\n * Recursive helper for public-facing fold() method\r\n */\r\n fold_(pathSoFar, fn) {\r\n const accum = {};\r\n this.children.inorderTraversal((childKey, childTree) => {\r\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\r\n });\r\n return fn(pathSoFar, this.value, accum);\r\n }\r\n /**\r\n * Find the first matching value on the given path. Return the result of applying f to it.\r\n */\r\n findOnPath(path, f) {\r\n return this.findOnPath_(path, newEmptyPath(), f);\r\n }\r\n findOnPath_(pathToFollow, pathSoFar, f) {\r\n const result = this.value ? f(pathSoFar, this.value) : false;\r\n if (result) {\r\n return result;\r\n }\r\n else {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n foreachOnPath(path, f) {\r\n return this.foreachOnPath_(path, newEmptyPath(), f);\r\n }\r\n foreachOnPath_(pathToFollow, currentRelativePath, f) {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return this;\r\n }\r\n else {\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Calls the given function for each node in the tree that has a value.\r\n *\r\n * @param f - A function to be called with the path from the root of the tree to\r\n * a node, and the value at that node. Called in depth-first order.\r\n */\r\n foreach(f) {\r\n this.foreach_(newEmptyPath(), f);\r\n }\r\n foreach_(currentRelativePath, f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\r\n });\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n }\r\n foreachChild(f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value) {\r\n f(childName, childTree.value);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\r\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\r\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\r\n * to reflect the write added.\r\n */\r\nclass CompoundWrite {\r\n constructor(writeTree_) {\r\n this.writeTree_ = writeTree_;\r\n }\r\n static empty() {\r\n return new CompoundWrite(new ImmutableTree(null));\r\n }\r\n}\r\nfunction compoundWriteAddWrite(compoundWrite, path, node) {\r\n if (pathIsEmpty(path)) {\r\n return new CompoundWrite(new ImmutableTree(node));\r\n }\r\n else {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n const rootMostPath = rootmost.path;\r\n let value = rootmost.value;\r\n const relativePath = newRelativePath(rootMostPath, path);\r\n value = value.updateChild(relativePath, node);\r\n return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));\r\n }\r\n else {\r\n const subtree = new ImmutableTree(node);\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n }\r\n}\r\nfunction compoundWriteAddWrites(compoundWrite, path, updates) {\r\n let newWrite = compoundWrite;\r\n each(updates, (childKey, node) => {\r\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\r\n });\r\n return newWrite;\r\n}\r\n/**\r\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\r\n * location, which must be removed by calling this method with that path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to remove.\r\n * @param path - The path at which a write and all deeper writes should be removed\r\n * @returns The new CompoundWrite with the removed path\r\n */\r\nfunction compoundWriteRemoveWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return CompoundWrite.empty();\r\n }\r\n else {\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n}\r\n/**\r\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\r\n * considered \"complete\".\r\n *\r\n * @param compoundWrite - The CompoundWrite to check.\r\n * @param path - The path to check for\r\n * @returns Whether there is a complete write at that path\r\n */\r\nfunction compoundWriteHasCompleteWrite(compoundWrite, path) {\r\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\r\n}\r\n/**\r\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\r\n * writes from deeper paths, but will return child nodes from a more shallow path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get the node from.\r\n * @param path - The path to get a complete write\r\n * @returns The node if complete at that path, or null otherwise.\r\n */\r\nfunction compoundWriteGetCompleteNode(compoundWrite, path) {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n return compoundWrite.writeTree_\r\n .get(rootmost.path)\r\n .getChild(newRelativePath(rootmost.path, path));\r\n }\r\n else {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Returns all children that are guaranteed to be a complete overwrite.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get children from.\r\n * @returns A list of all complete children.\r\n */\r\nfunction compoundWriteGetCompleteChildren(compoundWrite) {\r\n const children = [];\r\n const node = compoundWrite.writeTree_.value;\r\n if (node != null) {\r\n // If it's a leaf node, it has no children; so nothing to do.\r\n if (!node.isLeafNode()) {\r\n node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n children.push(new NamedNode(childName, childNode));\r\n });\r\n }\r\n }\r\n else {\r\n compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value != null) {\r\n children.push(new NamedNode(childName, childTree.value));\r\n }\r\n });\r\n }\r\n return children;\r\n}\r\nfunction compoundWriteChildCompoundWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return compoundWrite;\r\n }\r\n else {\r\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\r\n if (shadowingNode != null) {\r\n return new CompoundWrite(new ImmutableTree(shadowingNode));\r\n }\r\n else {\r\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\r\n * @returns Whether this CompoundWrite is empty\r\n */\r\nfunction compoundWriteIsEmpty(compoundWrite) {\r\n return compoundWrite.writeTree_.isEmpty();\r\n}\r\n/**\r\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\r\n * node\r\n * @param node - The node to apply this CompoundWrite to\r\n * @returns The node with all writes applied\r\n */\r\nfunction compoundWriteApply(compoundWrite, node) {\r\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\r\n}\r\nfunction applySubtreeWrite(relativePath, writeTree, node) {\r\n if (writeTree.value != null) {\r\n // Since there a write is always a leaf, we're done here\r\n return node.updateChild(relativePath, writeTree.value);\r\n }\r\n else {\r\n let priorityWrite = null;\r\n writeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (childKey === '.priority') {\r\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\r\n // to apply priorities to empty nodes that are later filled\r\n assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\r\n priorityWrite = childTree.value;\r\n }\r\n else {\r\n node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);\r\n }\r\n });\r\n // If there was a priority write, we only apply it if the node is not empty\r\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\r\n node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);\r\n }\r\n return node;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\r\n *\r\n */\r\nfunction writeTreeChildWrites(writeTree, path) {\r\n return newWriteTreeRef(path, writeTree);\r\n}\r\n/**\r\n * Record a new overwrite from user code.\r\n *\r\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\r\n */\r\nfunction writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');\r\n if (visible === undefined) {\r\n visible = true;\r\n }\r\n writeTree.allWrites.push({\r\n path,\r\n snap,\r\n writeId,\r\n visible\r\n });\r\n if (visible) {\r\n writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);\r\n }\r\n writeTree.lastWriteId = writeId;\r\n}\r\n/**\r\n * Record a new merge from user code.\r\n */\r\nfunction writeTreeAddMerge(writeTree, path, changedChildren, writeId) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');\r\n writeTree.allWrites.push({\r\n path,\r\n children: changedChildren,\r\n writeId,\r\n visible: true\r\n });\r\n writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);\r\n writeTree.lastWriteId = writeId;\r\n}\r\nfunction writeTreeGetWrite(writeTree, writeId) {\r\n for (let i = 0; i < writeTree.allWrites.length; i++) {\r\n const record = writeTree.allWrites[i];\r\n if (record.writeId === writeId) {\r\n return record;\r\n }\r\n }\r\n return null;\r\n}\r\n/**\r\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\r\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\r\n *\r\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\r\n * events as a result).\r\n */\r\nfunction writeTreeRemoveWrite(writeTree, writeId) {\r\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\r\n // out of order.\r\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\r\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\r\n const idx = writeTree.allWrites.findIndex(s => {\r\n return s.writeId === writeId;\r\n });\r\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\r\n const writeToRemove = writeTree.allWrites[idx];\r\n writeTree.allWrites.splice(idx, 1);\r\n let removedWriteWasVisible = writeToRemove.visible;\r\n let removedWriteOverlapsWithOtherWrites = false;\r\n let i = writeTree.allWrites.length - 1;\r\n while (removedWriteWasVisible && i >= 0) {\r\n const currentWrite = writeTree.allWrites[i];\r\n if (currentWrite.visible) {\r\n if (i >= idx &&\r\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {\r\n // The removed write was completely shadowed by a subsequent write.\r\n removedWriteWasVisible = false;\r\n }\r\n else if (pathContains(writeToRemove.path, currentWrite.path)) {\r\n // Either we're covering some writes or they're covering part of us (depending on which came first).\r\n removedWriteOverlapsWithOtherWrites = true;\r\n }\r\n }\r\n i--;\r\n }\r\n if (!removedWriteWasVisible) {\r\n return false;\r\n }\r\n else if (removedWriteOverlapsWithOtherWrites) {\r\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\r\n writeTreeResetTree_(writeTree);\r\n return true;\r\n }\r\n else {\r\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\r\n if (writeToRemove.snap) {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);\r\n }\r\n else {\r\n const children = writeToRemove.children;\r\n each(children, (childName) => {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));\r\n });\r\n }\r\n return true;\r\n }\r\n}\r\nfunction writeTreeRecordContainsPath_(writeRecord, path) {\r\n if (writeRecord.snap) {\r\n return pathContains(writeRecord.path, path);\r\n }\r\n else {\r\n for (const childName in writeRecord.children) {\r\n if (writeRecord.children.hasOwnProperty(childName) &&\r\n pathContains(pathChild(writeRecord.path, childName), path)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n}\r\n/**\r\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\r\n */\r\nfunction writeTreeResetTree_(writeTree) {\r\n writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());\r\n if (writeTree.allWrites.length > 0) {\r\n writeTree.lastWriteId =\r\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\r\n }\r\n else {\r\n writeTree.lastWriteId = -1;\r\n }\r\n}\r\n/**\r\n * The default filter used when constructing the tree. Keep everything that's visible.\r\n */\r\nfunction writeTreeDefaultFilter_(write) {\r\n return write.visible;\r\n}\r\n/**\r\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\r\n * event data at that path.\r\n */\r\nfunction writeTreeLayerTree_(writes, filter, treeRoot) {\r\n let compoundWrite = CompoundWrite.empty();\r\n for (let i = 0; i < writes.length; ++i) {\r\n const write = writes[i];\r\n // Theory, a later set will either:\r\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\r\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\r\n if (filter(write)) {\r\n const writePath = write.path;\r\n let relativePath;\r\n if (write.snap) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));\r\n }\r\n else ;\r\n }\r\n else if (write.children) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n if (pathIsEmpty(relativePath)) {\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);\r\n }\r\n else {\r\n const child = safeGet(write.children, pathGetFront(relativePath));\r\n if (child) {\r\n // There exists a child in this node that matches the root path\r\n const deepNode = child.getChild(pathPopFront(relativePath));\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);\r\n }\r\n }\r\n }\r\n else ;\r\n }\r\n else {\r\n throw assertionError('WriteRecord should have .snap or .children');\r\n }\r\n }\r\n }\r\n return compoundWrite;\r\n}\r\n/**\r\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\r\n * writes), attempt to calculate a complete snapshot for the given path\r\n *\r\n * @param writeIdsToExclude - An optional set to be excluded\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n if (!writeIdsToExclude && !includeHiddenWrites) {\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (compoundWriteIsEmpty(subMerge)) {\r\n return completeServerCache;\r\n }\r\n else if (completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {\r\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\r\n return null;\r\n }\r\n else {\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(subMerge, layeredCache);\r\n }\r\n }\r\n }\r\n else {\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\r\n return completeServerCache;\r\n }\r\n else {\r\n // If the server cache is null, and we don't have a complete cache, we need to return null\r\n if (!includeHiddenWrites &&\r\n completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {\r\n return null;\r\n }\r\n else {\r\n const filter = function (write) {\r\n return ((write.visible || includeHiddenWrites) &&\r\n (!writeIdsToExclude ||\r\n !~writeIdsToExclude.indexOf(write.writeId)) &&\r\n (pathContains(write.path, treePath) ||\r\n pathContains(treePath, write.path)));\r\n };\r\n const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(mergeAtPath, layeredCache);\r\n }\r\n }\r\n }\r\n}\r\n/**\r\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\r\n * Used when creating new views, to pre-fill their complete event children snapshot.\r\n */\r\nfunction writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {\r\n let completeChildren = ChildrenNode.EMPTY_NODE;\r\n const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (topLevelSet) {\r\n if (!topLevelSet.isLeafNode()) {\r\n // we're shadowing everything. Return the children.\r\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\r\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\r\n });\r\n }\r\n return completeChildren;\r\n }\r\n else if (completeServerChildren) {\r\n // Layer any children we have on top of this\r\n // We know we don't have a top-level set, so just enumerate existing children\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);\r\n completeChildren = completeChildren.updateImmediateChild(childName, node);\r\n });\r\n // Add any complete children we have from the set\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n else {\r\n // We don't have anything to layer on top of. Layer on any children we have\r\n // Note that we can return an empty snap if we have a defined delete\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n}\r\n/**\r\n * Given that the underlying server data has updated, determine what, if anything, needs to be\r\n * applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist\r\n */\r\nfunction writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {\r\n assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\r\n const path = pathChild(treePath, childPath);\r\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\r\n // At this point we can probably guarantee that we're in case 2, meaning no events\r\n // May need to check visibility while doing the findRootMostValueAndPath call\r\n return null;\r\n }\r\n else {\r\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n if (compoundWriteIsEmpty(childMerge)) {\r\n // We're not shadowing at all. Case 1\r\n return existingServerSnap.getChild(childPath);\r\n }\r\n else {\r\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\r\n // However this is tricky to find out, since user updates don't necessary change the server\r\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\r\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\r\n // only check if the updates change the serverNode.\r\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\r\n return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {\r\n const path = pathChild(treePath, childKey);\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n if (existingServerSnap.isCompleteForChild(childKey)) {\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n */\r\nfunction writeTreeShadowingWrite(writeTree, path) {\r\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window.\r\n */\r\nfunction writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {\r\n let toIterate;\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\r\n if (shadowingNode != null) {\r\n toIterate = shadowingNode;\r\n }\r\n else if (completeServerData != null) {\r\n toIterate = compoundWriteApply(merge, completeServerData);\r\n }\r\n else {\r\n // no children to iterate on\r\n return [];\r\n }\r\n toIterate = toIterate.withIndex(index);\r\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\r\n const nodes = [];\r\n const cmp = index.getCompare();\r\n const iter = reverse\r\n ? toIterate.getReverseIteratorFrom(startPost, index)\r\n : toIterate.getIteratorFrom(startPost, index);\r\n let next = iter.getNext();\r\n while (next && nodes.length < count) {\r\n if (cmp(next, startPost) !== 0) {\r\n nodes.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n return nodes;\r\n }\r\n else {\r\n return [];\r\n }\r\n}\r\nfunction newWriteTree() {\r\n return {\r\n visibleWrites: CompoundWrite.empty(),\r\n allWrites: [],\r\n lastWriteId: -1\r\n };\r\n}\r\n/**\r\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\r\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\r\n * can lead to a more expensive calculation.\r\n *\r\n * @param writeIdsToExclude - Optional writes to exclude.\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);\r\n}\r\n/**\r\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\r\n * mix of the given server data and write data.\r\n *\r\n */\r\nfunction writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {\r\n return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);\r\n}\r\n/**\r\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\r\n * if anything, needs to be applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events should be raised\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\r\n *\r\n *\r\n */\r\nfunction writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {\r\n return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n *\r\n */\r\nfunction writeTreeRefShadowingWrite(writeTreeRef, path) {\r\n return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window\r\n */\r\nfunction writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {\r\n return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {\r\n return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);\r\n}\r\n/**\r\n * Return a WriteTreeRef for a child.\r\n */\r\nfunction writeTreeRefChild(writeTreeRef, childName) {\r\n return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);\r\n}\r\nfunction newWriteTreeRef(path, writeTree) {\r\n return {\r\n treePath: path,\r\n writeTree\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ChildChangeAccumulator {\r\n constructor() {\r\n this.changeMap = new Map();\r\n }\r\n trackChildChange(change) {\r\n const type = change.type;\r\n const childKey = change.childName;\r\n assert(type === \"child_added\" /* CHILD_ADDED */ ||\r\n type === \"child_changed\" /* CHILD_CHANGED */ ||\r\n type === \"child_removed\" /* CHILD_REMOVED */, 'Only child changes supported for tracking');\r\n assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\r\n const oldChange = this.changeMap.get(childKey);\r\n if (oldChange) {\r\n const oldType = oldChange.type;\r\n if (type === \"child_added\" /* CHILD_ADDED */ &&\r\n oldType === \"child_removed\" /* CHILD_REMOVED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));\r\n }\r\n else if (type === \"child_removed\" /* CHILD_REMOVED */ &&\r\n oldType === \"child_added\" /* CHILD_ADDED */) {\r\n this.changeMap.delete(childKey);\r\n }\r\n else if (type === \"child_removed\" /* CHILD_REMOVED */ &&\r\n oldType === \"child_changed\" /* CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));\r\n }\r\n else if (type === \"child_changed\" /* CHILD_CHANGED */ &&\r\n oldType === \"child_added\" /* CHILD_ADDED */) {\r\n this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));\r\n }\r\n else if (type === \"child_changed\" /* CHILD_CHANGED */ &&\r\n oldType === \"child_changed\" /* CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));\r\n }\r\n else {\r\n throw assertionError('Illegal combination of changes: ' +\r\n change +\r\n ' occurred after ' +\r\n oldChange);\r\n }\r\n }\r\n else {\r\n this.changeMap.set(childKey, change);\r\n }\r\n }\r\n getChanges() {\r\n return Array.from(this.changeMap.values());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of CompleteChildSource that never returns any additional children\r\n */\r\n// eslint-disable-next-line @typescript-eslint/naming-convention\r\nclass NoCompleteChildSource_ {\r\n getCompleteChild(childKey) {\r\n return null;\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Singleton instance.\r\n */\r\nconst NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\r\n/**\r\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\r\n * old event caches available to calculate complete children.\r\n */\r\nclass WriteTreeCompleteChildSource {\r\n constructor(writes_, viewCache_, optCompleteServerCache_ = null) {\r\n this.writes_ = writes_;\r\n this.viewCache_ = viewCache_;\r\n this.optCompleteServerCache_ = optCompleteServerCache_;\r\n }\r\n getCompleteChild(childKey) {\r\n const node = this.viewCache_.eventCache;\r\n if (node.isCompleteForChild(childKey)) {\r\n return node.getNode().getImmediateChild(childKey);\r\n }\r\n else {\r\n const serverNode = this.optCompleteServerCache_ != null\r\n ? new CacheNode(this.optCompleteServerCache_, true, false)\r\n : this.viewCache_.serverCache;\r\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\r\n }\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n const completeServerData = this.optCompleteServerCache_ != null\r\n ? this.optCompleteServerCache_\r\n : viewCacheGetCompleteServerSnap(this.viewCache_);\r\n const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);\r\n if (nodes.length === 0) {\r\n return null;\r\n }\r\n else {\r\n return nodes[0];\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewProcessor(filter) {\r\n return { filter };\r\n}\r\nfunction viewProcessorAssertIndexed(viewProcessor, viewCache) {\r\n assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');\r\n assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');\r\n}\r\nfunction viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {\r\n const accumulator = new ChildChangeAccumulator();\r\n let newViewCache, filterServerNode;\r\n if (operation.type === OperationType.OVERWRITE) {\r\n const overwrite = operation;\r\n if (overwrite.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(overwrite.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered and the\r\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\r\n // again\r\n filterServerNode =\r\n overwrite.source.tagged ||\r\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\r\n newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.MERGE) {\r\n const merge = operation;\r\n if (merge.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(merge.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered\r\n filterServerNode =\r\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\r\n newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.ACK_USER_WRITE) {\r\n const ackUserWrite = operation;\r\n if (!ackUserWrite.revert) {\r\n newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.LISTEN_COMPLETE) {\r\n newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);\r\n }\r\n else {\r\n throw assertionError('Unknown operation type: ' + operation.type);\r\n }\r\n const changes = accumulator.getChanges();\r\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\r\n return { viewCache: newViewCache, changes };\r\n}\r\nfunction viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {\r\n const eventSnap = newViewCache.eventCache;\r\n if (eventSnap.isFullyInitialized()) {\r\n const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\r\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\r\n if (accumulator.length > 0 ||\r\n !oldViewCache.eventCache.isFullyInitialized() ||\r\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\r\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {\r\n accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));\r\n }\r\n }\r\n}\r\nfunction viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {\r\n const oldEventSnap = viewCache.eventCache;\r\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\r\n // we have a shadowing write, ignore changes\r\n return viewCache;\r\n }\r\n else {\r\n let newEventCache, serverNode;\r\n if (pathIsEmpty(changePath)) {\r\n // TODO: figure out how this plays with \"sliding ack windows\"\r\n assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');\r\n if (viewCache.serverCache.isFiltered()) {\r\n // We need to special case this, because we need to only apply writes to complete children, or\r\n // we might end up raising events for incomplete children. If the server data is filtered deep\r\n // writes cannot be guaranteed to be complete\r\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\r\n const completeChildren = serverCache instanceof ChildrenNode\r\n ? serverCache\r\n : ChildrenNode.EMPTY_NODE;\r\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);\r\n }\r\n else {\r\n const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);\r\n }\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n assert(pathGetLength(changePath) === 1, \"Can't have a priority with additional path components\");\r\n const oldEventNode = oldEventSnap.getNode();\r\n serverNode = viewCache.serverCache.getNode();\r\n // we might have overwrites for this priority\r\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);\r\n if (updatedPriority != null) {\r\n newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);\r\n }\r\n else {\r\n // priority didn't change, keep old node\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n // update child\r\n let newEventChild;\r\n if (oldEventSnap.isCompleteForChild(childKey)) {\r\n serverNode = viewCache.serverCache.getNode();\r\n const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);\r\n if (eventChildUpdate != null) {\r\n newEventChild = oldEventSnap\r\n .getNode()\r\n .getImmediateChild(childKey)\r\n .updateChild(childChangePath, eventChildUpdate);\r\n }\r\n else {\r\n // Nothing changed, just keep the old child\r\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n }\r\n }\r\n else {\r\n newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n }\r\n if (newEventChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\r\n }\r\n else {\r\n // no complete child available or no change\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n }\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());\r\n }\r\n}\r\nfunction viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\r\n const oldServerSnap = oldViewCache.serverCache;\r\n let newServerCache;\r\n const serverFilter = filterServerNode\r\n ? viewProcessor.filter\r\n : viewProcessor.filter.getIndexedFilter();\r\n if (pathIsEmpty(changePath)) {\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\r\n }\r\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\r\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\r\n const newServerNode = oldServerSnap\r\n .getNode()\r\n .updateChild(changePath, changedSnap);\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (!oldServerSnap.isCompleteForPath(changePath) &&\r\n pathGetLength(changePath) > 1) {\r\n // We don't update incomplete nodes with updates intended for other listeners\r\n return oldViewCache;\r\n }\r\n const childChangePath = pathPopFront(changePath);\r\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\r\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\r\n if (childKey === '.priority') {\r\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\r\n }\r\n else {\r\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\r\n }\r\n }\r\n const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());\r\n const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);\r\n}\r\nfunction viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\r\n const oldEventSnap = oldViewCache.eventCache;\r\n let newViewCache, newEventCache;\r\n const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\r\n if (pathIsEmpty(changePath)) {\r\n newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n let newChild;\r\n if (pathIsEmpty(childChangePath)) {\r\n // Child overwrite, we can replace the child\r\n newChild = changedSnap;\r\n }\r\n else {\r\n const childNode = source.getCompleteChild(childKey);\r\n if (childNode != null) {\r\n if (pathGetBack(childChangePath) === '.priority' &&\r\n childNode.getChild(pathParent(childChangePath)).isEmpty()) {\r\n // This is a priority update on an empty node. If this node exists on the server, the\r\n // server will send down the priority in the update, so ignore for now\r\n newChild = childNode;\r\n }\r\n else {\r\n newChild = childNode.updateChild(childChangePath, changedSnap);\r\n }\r\n }\r\n else {\r\n // There is no complete child node available\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n }\r\n if (!oldChild.equals(newChild)) {\r\n const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n newViewCache = oldViewCache;\r\n }\r\n }\r\n }\r\n return newViewCache;\r\n}\r\nfunction viewProcessorCacheHasChild(viewCache, childKey) {\r\n return viewCache.eventCache.isCompleteForChild(childKey);\r\n}\r\nfunction viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorApplyMerge(viewProcessor, node, merge) {\r\n merge.foreach((relativePath, childNode) => {\r\n node = node.updateChild(relativePath, childNode);\r\n });\r\n return node;\r\n}\r\nfunction viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\r\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\r\n // wait for the complete data update coming soon.\r\n if (viewCache.serverCache.getNode().isEmpty() &&\r\n !viewCache.serverCache.isFullyInitialized()) {\r\n return viewCache;\r\n }\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n let viewMergeTree;\r\n if (pathIsEmpty(path)) {\r\n viewMergeTree = changedChildren;\r\n }\r\n else {\r\n viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);\r\n }\r\n const serverNode = viewCache.serverCache.getNode();\r\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (serverNode.hasChild(childKey)) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\r\n const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&\r\n childMergeTree.value === undefined;\r\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\r\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\r\n return viewCache;\r\n }\r\n // Only filter server node if it is currently filtered\r\n const filterServerNode = viewCache.serverCache.isFiltered();\r\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\r\n // now that it won't be shadowed.\r\n const serverCache = viewCache.serverCache;\r\n if (affectedTree.value != null) {\r\n // This is an overwrite.\r\n if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\r\n serverCache.isCompleteForPath(ackPath)) {\r\n return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else if (pathIsEmpty(ackPath)) {\r\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\r\n // should just re-apply whatever we have in our cache as a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\r\n changedChildren = changedChildren.set(new Path(name), node);\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else {\r\n return viewCache;\r\n }\r\n }\r\n else {\r\n // This is a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n affectedTree.foreach((mergePath, value) => {\r\n const serverCachePath = pathChild(ackPath, mergePath);\r\n if (serverCache.isCompleteForPath(serverCachePath)) {\r\n changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));\r\n }\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n}\r\nfunction viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {\r\n const oldServerNode = viewCache.serverCache;\r\n const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\r\n}\r\nfunction viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {\r\n let complete;\r\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\r\n return viewCache;\r\n }\r\n else {\r\n const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\r\n const oldEventCache = viewCache.eventCache.getNode();\r\n let newEventCache;\r\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\r\n let newNode;\r\n if (viewCache.serverCache.isFullyInitialized()) {\r\n newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n }\r\n else {\r\n const serverChildren = viewCache.serverCache.getNode();\r\n assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\r\n newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);\r\n }\r\n newNode = newNode;\r\n newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n if (newChild == null &&\r\n viewCache.serverCache.isCompleteForChild(childKey)) {\r\n newChild = oldEventCache.getImmediateChild(childKey);\r\n }\r\n if (newChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);\r\n }\r\n else if (viewCache.eventCache.getNode().hasChild(childKey)) {\r\n // No complete child available, delete the existing one, if any\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);\r\n }\r\n else {\r\n newEventCache = oldEventCache;\r\n }\r\n if (newEventCache.isEmpty() &&\r\n viewCache.serverCache.isFullyInitialized()) {\r\n // We might have reverted all child writes. Maybe the old event was a leaf node\r\n complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n if (complete.isLeafNode()) {\r\n newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);\r\n }\r\n }\r\n }\r\n complete =\r\n viewCache.serverCache.isFullyInitialized() ||\r\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A view represents a specific location and query that has 1 or more event registrations.\r\n *\r\n * It does several things:\r\n * - Maintains the list of event registrations for this location/query.\r\n * - Maintains a cache of the data visible for this location/query.\r\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\r\n * registrations returns the set of events to be raised.\r\n */\r\nclass View {\r\n constructor(query_, initialViewCache) {\r\n this.query_ = query_;\r\n this.eventRegistrations_ = [];\r\n const params = this.query_._queryParams;\r\n const indexFilter = new IndexedFilter(params.getIndex());\r\n const filter = queryParamsGetNodeFilter(params);\r\n this.processor_ = newViewProcessor(filter);\r\n const initialServerCache = initialViewCache.serverCache;\r\n const initialEventCache = initialViewCache.eventCache;\r\n // Don't filter server node with other filter than index, wait for tagged listen\r\n const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\r\n const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\r\n const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\r\n const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\r\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\r\n this.eventGenerator_ = new EventGenerator(this.query_);\r\n }\r\n get query() {\r\n return this.query_;\r\n }\r\n}\r\nfunction viewGetServerCache(view) {\r\n return view.viewCache_.serverCache.getNode();\r\n}\r\nfunction viewGetCompleteNode(view) {\r\n return viewCacheGetCompleteEventSnap(view.viewCache_);\r\n}\r\nfunction viewGetCompleteServerCache(view, path) {\r\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\r\n if (cache) {\r\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\r\n // we need to see if it contains the child we're interested in.\r\n if (view.query._queryParams.loadsAllData() ||\r\n (!pathIsEmpty(path) &&\r\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {\r\n return cache.getChild(path);\r\n }\r\n }\r\n return null;\r\n}\r\nfunction viewIsEmpty(view) {\r\n return view.eventRegistrations_.length === 0;\r\n}\r\nfunction viewAddEventRegistration(view, eventRegistration) {\r\n view.eventRegistrations_.push(eventRegistration);\r\n}\r\n/**\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction viewRemoveEventRegistration(view, eventRegistration, cancelError) {\r\n const cancelEvents = [];\r\n if (cancelError) {\r\n assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\r\n const path = view.query._path;\r\n view.eventRegistrations_.forEach(registration => {\r\n const maybeEvent = registration.createCancelEvent(cancelError, path);\r\n if (maybeEvent) {\r\n cancelEvents.push(maybeEvent);\r\n }\r\n });\r\n }\r\n if (eventRegistration) {\r\n let remaining = [];\r\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\r\n const existing = view.eventRegistrations_[i];\r\n if (!existing.matches(eventRegistration)) {\r\n remaining.push(existing);\r\n }\r\n else if (eventRegistration.hasAnyCallback()) {\r\n // We're removing just this one\r\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\r\n break;\r\n }\r\n }\r\n view.eventRegistrations_ = remaining;\r\n }\r\n else {\r\n view.eventRegistrations_ = [];\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Applies the given Operation, updates our cache, and returns the appropriate events.\r\n */\r\nfunction viewApplyOperation(view, operation, writesCache, completeServerCache) {\r\n if (operation.type === OperationType.MERGE &&\r\n operation.source.queryId !== null) {\r\n assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');\r\n assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');\r\n }\r\n const oldViewCache = view.viewCache_;\r\n const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);\r\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\r\n assert(result.viewCache.serverCache.isFullyInitialized() ||\r\n !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');\r\n view.viewCache_ = result.viewCache;\r\n return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);\r\n}\r\nfunction viewGetInitialEvents(view, registration) {\r\n const eventSnap = view.viewCache_.eventCache;\r\n const initialChanges = [];\r\n if (!eventSnap.getNode().isLeafNode()) {\r\n const eventNode = eventSnap.getNode();\r\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n initialChanges.push(changeChildAdded(key, childNode));\r\n });\r\n }\r\n if (eventSnap.isFullyInitialized()) {\r\n initialChanges.push(changeValue(eventSnap.getNode()));\r\n }\r\n return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);\r\n}\r\nfunction viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {\r\n const registrations = eventRegistration\r\n ? [eventRegistration]\r\n : view.eventRegistrations_;\r\n return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor$1;\r\n/**\r\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\r\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\r\n * and user writes (set, transaction, update).\r\n *\r\n * It's responsible for:\r\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\r\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\r\n * applyUserOverwrite, etc.)\r\n */\r\nclass SyncPoint {\r\n constructor() {\r\n /**\r\n * The Views being tracked at this location in the tree, stored as a map where the key is a\r\n * queryId and the value is the View for that query.\r\n *\r\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\r\n */\r\n this.views = new Map();\r\n }\r\n}\r\nfunction syncPointSetReferenceConstructor(val) {\r\n assert(!referenceConstructor$1, '__referenceConstructor has already been defined');\r\n referenceConstructor$1 = val;\r\n}\r\nfunction syncPointGetReferenceConstructor() {\r\n assert(referenceConstructor$1, 'Reference.ts has not been loaded');\r\n return referenceConstructor$1;\r\n}\r\nfunction syncPointIsEmpty(syncPoint) {\r\n return syncPoint.views.size === 0;\r\n}\r\nfunction syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {\r\n const queryId = operation.source.queryId;\r\n if (queryId !== null) {\r\n const view = syncPoint.views.get(queryId);\r\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\r\n return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);\r\n }\r\n else {\r\n let events = [];\r\n for (const view of syncPoint.views.values()) {\r\n events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Get a view for the specified query.\r\n *\r\n * @param query - The query to return a view for\r\n * @param writesCache\r\n * @param serverCache\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {\r\n const queryId = query._queryIdentifier;\r\n const view = syncPoint.views.get(queryId);\r\n if (!view) {\r\n // TODO: make writesCache take flag for complete server node\r\n let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);\r\n let eventCacheComplete = false;\r\n if (eventCache) {\r\n eventCacheComplete = true;\r\n }\r\n else if (serverCache instanceof ChildrenNode) {\r\n eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);\r\n eventCacheComplete = false;\r\n }\r\n else {\r\n eventCache = ChildrenNode.EMPTY_NODE;\r\n eventCacheComplete = false;\r\n }\r\n const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));\r\n return new View(query, viewCache);\r\n }\r\n return view;\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @param query\r\n * @param eventRegistration\r\n * @param writesCache\r\n * @param serverCache - Complete server cache, if we have it.\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);\r\n if (!syncPoint.views.has(query._queryIdentifier)) {\r\n syncPoint.views.set(query._queryIdentifier, view);\r\n }\r\n // This is guaranteed to exist now, we just created anything that was missing\r\n viewAddEventRegistration(view, eventRegistration);\r\n return viewGetInitialEvents(view, eventRegistration);\r\n}\r\n/**\r\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\r\n *\r\n * If query is the default query, we'll check all views for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\r\n *\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns removed queries and any cancel events\r\n */\r\nfunction syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {\r\n const queryId = query._queryIdentifier;\r\n const removed = [];\r\n let cancelEvents = [];\r\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\r\n if (queryId === 'default') {\r\n // When you do ref.off(...), we search all views for the registration to remove.\r\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(viewQueryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // remove the callback from the specific view.\r\n const view = syncPoint.views.get(queryId);\r\n if (view) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(queryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\r\n // We removed our last complete view.\r\n removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));\r\n }\r\n return { removed, events: cancelEvents };\r\n}\r\nfunction syncPointGetQueryViews(syncPoint) {\r\n const result = [];\r\n for (const view of syncPoint.views.values()) {\r\n if (!view.query._queryParams.loadsAllData()) {\r\n result.push(view);\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * @param path - The path to the desired complete snapshot\r\n * @returns A complete cache, if it exists\r\n */\r\nfunction syncPointGetCompleteServerCache(syncPoint, path) {\r\n let serverCache = null;\r\n for (const view of syncPoint.views.values()) {\r\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\r\n }\r\n return serverCache;\r\n}\r\nfunction syncPointViewForQuery(syncPoint, query) {\r\n const params = query._queryParams;\r\n if (params.loadsAllData()) {\r\n return syncPointGetCompleteView(syncPoint);\r\n }\r\n else {\r\n const queryId = query._queryIdentifier;\r\n return syncPoint.views.get(queryId);\r\n }\r\n}\r\nfunction syncPointViewExistsForQuery(syncPoint, query) {\r\n return syncPointViewForQuery(syncPoint, query) != null;\r\n}\r\nfunction syncPointHasCompleteView(syncPoint) {\r\n return syncPointGetCompleteView(syncPoint) != null;\r\n}\r\nfunction syncPointGetCompleteView(syncPoint) {\r\n for (const view of syncPoint.views.values()) {\r\n if (view.query._queryParams.loadsAllData()) {\r\n return view;\r\n }\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor;\r\nfunction syncTreeSetReferenceConstructor(val) {\r\n assert(!referenceConstructor, '__referenceConstructor has already been defined');\r\n referenceConstructor = val;\r\n}\r\nfunction syncTreeGetReferenceConstructor() {\r\n assert(referenceConstructor, 'Reference.ts has not been loaded');\r\n return referenceConstructor;\r\n}\r\n/**\r\n * Static tracker for next query tag.\r\n */\r\nlet syncTreeNextQueryTag_ = 1;\r\n/**\r\n * SyncTree is the central class for managing event callback registration, data caching, views\r\n * (query processing), and event generation. There are typically two SyncTree instances for\r\n * each Repo, one for the normal Firebase data, and one for the .info data.\r\n *\r\n * It has a number of responsibilities, including:\r\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\r\n * - Applying and caching data changes for user set(), transaction(), and update() calls\r\n * (applyUserOverwrite(), applyUserMerge()).\r\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\r\n * applyServerMerge()).\r\n * - Generating user-facing events for server and user changes (all of the apply* methods\r\n * return the set of events that need to be raised as a result).\r\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\r\n * to the correct set of paths and queries to satisfy the current set of user event\r\n * callbacks (listens are started/stopped using the provided listenProvider).\r\n *\r\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\r\n * events are returned to the caller rather than raised synchronously.\r\n *\r\n */\r\nclass SyncTree {\r\n /**\r\n * @param listenProvider_ - Used by SyncTree to start / stop listening\r\n * to server data.\r\n */\r\n constructor(listenProvider_) {\r\n this.listenProvider_ = listenProvider_;\r\n /**\r\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\r\n */\r\n this.syncPointTree_ = new ImmutableTree(null);\r\n /**\r\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\r\n */\r\n this.pendingWriteTree_ = newWriteTree();\r\n this.tagToQueryMap = new Map();\r\n this.queryToTagMap = new Map();\r\n }\r\n}\r\n/**\r\n * Apply the data changes for a user-generated set() or transaction() call.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {\r\n // Record pending write.\r\n writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);\r\n if (!visible) {\r\n return [];\r\n }\r\n else {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));\r\n }\r\n}\r\n/**\r\n * Apply the data from a user-generated update() call\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {\r\n // Record pending merge.\r\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));\r\n}\r\n/**\r\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\r\n *\r\n * @param revert - True if the given write failed and needs to be reverted\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAckUserWrite(syncTree, writeId, revert = false) {\r\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\r\n const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);\r\n if (!needToReevaluate) {\r\n return [];\r\n }\r\n else {\r\n let affectedTree = new ImmutableTree(null);\r\n if (write.snap != null) {\r\n // overwrite\r\n affectedTree = affectedTree.set(newEmptyPath(), true);\r\n }\r\n else {\r\n each(write.children, (pathString) => {\r\n affectedTree = affectedTree.set(new Path(pathString), true);\r\n });\r\n }\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));\r\n }\r\n}\r\n/**\r\n * Apply new server data for the specified path..\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerOverwrite(syncTree, path, newData) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\r\n}\r\n/**\r\n * Apply new server data to be merged in at the specified path.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerMerge(syncTree, path, changedChildren) {\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));\r\n}\r\n/**\r\n * Apply a listen complete for a query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyListenComplete(syncTree, path) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));\r\n}\r\n/**\r\n * Apply a listen complete for a tagged query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedListenComplete(syncTree, path, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Remove event callback(s).\r\n *\r\n * If query is the default query, we'll check all queries for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\r\n *\r\n * @param eventRegistration - If null, all callbacks are removed.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError) {\r\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\r\n const path = query._path;\r\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\r\n let cancelEvents = [];\r\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\r\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\r\n // not loadsAllData().\r\n if (maybeSyncPoint &&\r\n (query._queryIdentifier === 'default' ||\r\n syncPointViewExistsForQuery(maybeSyncPoint, query))) {\r\n const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);\r\n if (syncPointIsEmpty(maybeSyncPoint)) {\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\r\n }\r\n const removed = removedAndEvents.removed;\r\n cancelEvents = removedAndEvents.events;\r\n // We may have just removed one of many listeners and can short-circuit this whole process\r\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\r\n // properly set up.\r\n //\r\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\r\n // queryId === 'default'\r\n const removingDefault = -1 !==\r\n removed.findIndex(query => {\r\n return query._queryParams.loadsAllData();\r\n });\r\n const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));\r\n if (removingDefault && !covered) {\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\r\n // removal\r\n if (!subtree.isEmpty()) {\r\n // We need to fold over our subtree and collect the listeners to send\r\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\r\n // Ok, we've collected all the listens we need. Set them up.\r\n for (let i = 0; i < newViews.length; ++i) {\r\n const view = newViews[i], newQuery = view.query;\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery_(syncTree, newQuery), listener.hashFn, listener.onComplete);\r\n }\r\n }\r\n }\r\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\r\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\r\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\r\n if (!covered && removed.length > 0 && !cancelError) {\r\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\r\n // default. Otherwise, we need to iterate through and cancel each individual query\r\n if (removingDefault) {\r\n // We don't tag default listeners\r\n const defaultTag = null;\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);\r\n }\r\n else {\r\n removed.forEach((queryToRemove) => {\r\n const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);\r\n });\r\n }\r\n }\r\n // Now, clear all of the tags we're tracking for the removed listens\r\n syncTreeRemoveTags_(syncTree, removed);\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Apply new server data for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey != null) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // Query must have been removed already\r\n return [];\r\n }\r\n}\r\n/**\r\n * Apply server data to be merged in for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAddEventRegistration(syncTree, query, eventRegistration) {\r\n const path = query._path;\r\n let serverCache = null;\r\n let foundAncestorDefaultView = false;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let serverCacheComplete;\r\n if (serverCache != null) {\r\n serverCacheComplete = true;\r\n }\r\n else {\r\n serverCacheComplete = false;\r\n serverCache = ChildrenNode.EMPTY_NODE;\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n subtree.foreachChild((childName, childSyncPoint) => {\r\n const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());\r\n if (completeCache) {\r\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\r\n }\r\n });\r\n }\r\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\r\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\r\n // We need to track a tag for this query\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');\r\n const tag = syncTreeGetNextQueryTag_();\r\n syncTree.queryToTagMap.set(queryKey, tag);\r\n syncTree.tagToQueryMap.set(tag, queryKey);\r\n }\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\r\n let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);\r\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\r\n const view = syncPointViewForQuery(syncPoint, query);\r\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\r\n }\r\n return events;\r\n}\r\n/**\r\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\r\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\r\n * have a listener above, and atomic operations would correctly show a jitter of ->\r\n * as the write is applied locally and then acknowledged at the server.\r\n *\r\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\r\n *\r\n * @param path - The path to the data we want\r\n * @param writeIdsToExclude - A specific set to be excluded\r\n */\r\nfunction syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {\r\n const includeHiddenSets = true;\r\n const writeTree = syncTree.pendingWriteTree_;\r\n const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {\r\n const relativePath = newRelativePath(pathSoFar, path);\r\n const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);\r\n if (serverCache) {\r\n return serverCache;\r\n }\r\n });\r\n return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);\r\n}\r\nfunction syncTreeGetServerValue(syncTree, query) {\r\n const path = query._path;\r\n let serverCache = null;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n const serverCacheComplete = serverCache != null;\r\n const serverCacheNode = serverCacheComplete\r\n ? new CacheNode(serverCache, true, false)\r\n : null;\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);\r\n return viewGetCompleteNode(view);\r\n}\r\n/**\r\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\r\n *\r\n * NOTES:\r\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\r\n *\r\n * - We call applyOperation() on each SyncPoint passing three things:\r\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\r\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\r\n * 3. A snapshot Node with cached server data, if we have it.\r\n *\r\n * - We concatenate all of the events returned by each SyncPoint and return the result.\r\n */\r\nfunction syncTreeApplyOperationToSyncPoints_(syncTree, operation) {\r\n return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, \r\n /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n if (pathIsEmpty(operation.path)) {\r\n return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\r\n }\r\n else {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n const childName = pathGetFront(operation.path);\r\n const childOperation = operation.operationForChild(childName);\r\n const childTree = syncPointTree.children.get(childName);\r\n if (childTree && childOperation) {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n syncPointTree.children.inorderTraversal((childName, childTree) => {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n const childOperation = operation.operationForChild(childName);\r\n if (childOperation) {\r\n events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n });\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n}\r\nfunction syncTreeCreateListenerForView_(syncTree, view) {\r\n const query = view.query;\r\n const tag = syncTreeTagForQuery_(syncTree, query);\r\n return {\r\n hashFn: () => {\r\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\r\n return cache.hash();\r\n },\r\n onComplete: (status) => {\r\n if (status === 'ok') {\r\n if (tag) {\r\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\r\n }\r\n else {\r\n return syncTreeApplyListenComplete(syncTree, query._path);\r\n }\r\n }\r\n else {\r\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\r\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\r\n const error = errorForServerCode(status, query);\r\n return syncTreeRemoveEventRegistration(syncTree, query, \r\n /*eventRegistration*/ null, error);\r\n }\r\n }\r\n };\r\n}\r\n/**\r\n * Return the tag associated with the given query.\r\n */\r\nfunction syncTreeTagForQuery_(syncTree, query) {\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n return syncTree.queryToTagMap.get(queryKey);\r\n}\r\n/**\r\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\r\n */\r\nfunction syncTreeMakeQueryKey_(query) {\r\n return query._path.toString() + '$' + query._queryIdentifier;\r\n}\r\n/**\r\n * Return the query associated with the given tag, if we have one\r\n */\r\nfunction syncTreeQueryKeyForTag_(syncTree, tag) {\r\n return syncTree.tagToQueryMap.get(tag);\r\n}\r\n/**\r\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\r\n */\r\nfunction syncTreeParseQueryKey_(queryKey) {\r\n const splitIndex = queryKey.indexOf('$');\r\n assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\r\n return {\r\n queryId: queryKey.substr(splitIndex + 1),\r\n path: new Path(queryKey.substr(0, splitIndex))\r\n };\r\n}\r\n/**\r\n * A helper method to apply tagged operations\r\n */\r\nfunction syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {\r\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\r\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);\r\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\r\n}\r\n/**\r\n * This collapses multiple unfiltered views into a single view, since we only need a single\r\n * listener for them.\r\n */\r\nfunction syncTreeCollectDistinctViewsForSubTree_(subtree) {\r\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\r\n return [completeView];\r\n }\r\n else {\r\n // No complete view here, flatten any deeper listens into an array\r\n let views = [];\r\n if (maybeChildSyncPoint) {\r\n views = syncPointGetQueryViews(maybeChildSyncPoint);\r\n }\r\n each(childMap, (_key, childViews) => {\r\n views = views.concat(childViews);\r\n });\r\n return views;\r\n }\r\n });\r\n}\r\n/**\r\n * Normalizes a query to a query we send the server for listening\r\n *\r\n * @returns The normalized query\r\n */\r\nfunction syncTreeQueryForListening_(query) {\r\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\r\n // We treat queries that load all data as default queries\r\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\r\n // from Query\r\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\r\n }\r\n else {\r\n return query;\r\n }\r\n}\r\nfunction syncTreeRemoveTags_(syncTree, queries) {\r\n for (let j = 0; j < queries.length; ++j) {\r\n const removedQuery = queries[j];\r\n if (!removedQuery._queryParams.loadsAllData()) {\r\n // We should have a tag for this\r\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\r\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\r\n syncTree.queryToTagMap.delete(removedQueryKey);\r\n syncTree.tagToQueryMap.delete(removedQueryTag);\r\n }\r\n }\r\n}\r\n/**\r\n * Static accessor for query tags.\r\n */\r\nfunction syncTreeGetNextQueryTag_() {\r\n return syncTreeNextQueryTag_++;\r\n}\r\n/**\r\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\r\n *\r\n * @returns This method can return events to support synchronous data sources\r\n */\r\nfunction syncTreeSetupListener_(syncTree, query, view) {\r\n const path = query._path;\r\n const tag = syncTreeTagForQuery_(syncTree, query);\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\r\n // may need to shadow other listens as well.\r\n if (tag) {\r\n assert(!syncPointHasCompleteView(subtree.value), \"If we're adding a query, it shouldn't be shadowed\");\r\n }\r\n else {\r\n // Shadow everything at or below this location, this is a default listener.\r\n const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (!pathIsEmpty(relativePath) &&\r\n maybeChildSyncPoint &&\r\n syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\r\n }\r\n else {\r\n // No default listener here, flatten any deeper queries into an array\r\n let queries = [];\r\n if (maybeChildSyncPoint) {\r\n queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));\r\n }\r\n each(childMap, (_key, childQueries) => {\r\n queries = queries.concat(childQueries);\r\n });\r\n return queries;\r\n }\r\n });\r\n for (let i = 0; i < queriesToStop.length; ++i) {\r\n const queryToStop = queriesToStop[i];\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery_(syncTree, queryToStop));\r\n }\r\n }\r\n return events;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ExistingValueProvider {\r\n constructor(node_) {\r\n this.node_ = node_;\r\n }\r\n getImmediateChild(childName) {\r\n const child = this.node_.getImmediateChild(childName);\r\n return new ExistingValueProvider(child);\r\n }\r\n node() {\r\n return this.node_;\r\n }\r\n}\r\nclass DeferredValueProvider {\r\n constructor(syncTree, path) {\r\n this.syncTree_ = syncTree;\r\n this.path_ = path;\r\n }\r\n getImmediateChild(childName) {\r\n const childPath = pathChild(this.path_, childName);\r\n return new DeferredValueProvider(this.syncTree_, childPath);\r\n }\r\n node() {\r\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\r\n }\r\n}\r\n/**\r\n * Generate placeholders for deferred values.\r\n */\r\nconst generateWithValues = function (values) {\r\n values = values || {};\r\n values['timestamp'] = values['timestamp'] || new Date().getTime();\r\n return values;\r\n};\r\n/**\r\n * Value to use when firing local events. When writing server values, fire\r\n * local events with an approximate value, otherwise return value as-is.\r\n */\r\nconst resolveDeferredLeafValue = function (value, existingVal, serverValues) {\r\n if (!value || typeof value !== 'object') {\r\n return value;\r\n }\r\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\r\n if (typeof value['.sv'] === 'string') {\r\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\r\n }\r\n else if (typeof value['.sv'] === 'object') {\r\n return resolveComplexDeferredValue(value['.sv'], existingVal);\r\n }\r\n else {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\r\n }\r\n};\r\nconst resolveScalarDeferredValue = function (op, existing, serverValues) {\r\n switch (op) {\r\n case 'timestamp':\r\n return serverValues['timestamp'];\r\n default:\r\n assert(false, 'Unexpected server value: ' + op);\r\n }\r\n};\r\nconst resolveComplexDeferredValue = function (op, existing, unused) {\r\n if (!op.hasOwnProperty('increment')) {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\r\n }\r\n const delta = op['increment'];\r\n if (typeof delta !== 'number') {\r\n assert(false, 'Unexpected increment value: ' + delta);\r\n }\r\n const existingNode = existing.node();\r\n assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');\r\n // Incrementing a non-number sets the value to the incremented amount\r\n if (!existingNode.isLeafNode()) {\r\n return delta;\r\n }\r\n const leaf = existingNode;\r\n const existingVal = leaf.getValue();\r\n if (typeof existingVal !== 'number') {\r\n return delta;\r\n }\r\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\r\n return existingVal + delta;\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the tree with the\r\n * specified generated replacement values.\r\n * @param path - path to which write is relative\r\n * @param node - new data written at path\r\n * @param syncTree - current data\r\n */\r\nconst resolveDeferredValueTree = function (path, node, syncTree, serverValues) {\r\n return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the node with the\r\n * specified generated replacement values. If there are no server values in the node,\r\n * it'll be returned as-is.\r\n */\r\nconst resolveDeferredValueSnapshot = function (node, existing, serverValues) {\r\n return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);\r\n};\r\nfunction resolveDeferredValue(node, existingVal, serverValues) {\r\n const rawPri = node.getPriority().val();\r\n const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);\r\n let newNode;\r\n if (node.isLeafNode()) {\r\n const leafNode = node;\r\n const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);\r\n if (value !== leafNode.getValue() ||\r\n priority !== leafNode.getPriority().val()) {\r\n return new LeafNode(value, nodeFromJSON(priority));\r\n }\r\n else {\r\n return node;\r\n }\r\n }\r\n else {\r\n const childrenNode = node;\r\n newNode = childrenNode;\r\n if (priority !== childrenNode.getPriority().val()) {\r\n newNode = newNode.updatePriority(new LeafNode(priority));\r\n }\r\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);\r\n if (newChildNode !== childNode) {\r\n newNode = newNode.updateImmediateChild(childName, newChildNode);\r\n }\r\n });\r\n return newNode;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A light-weight tree, traversable by path. Nodes can have both values and children.\r\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\r\n * children.\r\n */\r\nclass Tree {\r\n /**\r\n * @param name - Optional name of the node.\r\n * @param parent - Optional parent node.\r\n * @param node - Optional node to wrap.\r\n */\r\n constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {\r\n this.name = name;\r\n this.parent = parent;\r\n this.node = node;\r\n }\r\n}\r\n/**\r\n * Returns a sub-Tree for the given path.\r\n *\r\n * @param pathObj - Path to look up.\r\n * @returns Tree for path.\r\n */\r\nfunction treeSubTree(tree, pathObj) {\r\n // TODO: Require pathObj to be Path?\r\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\r\n let child = tree, next = pathGetFront(path);\r\n while (next !== null) {\r\n const childNode = safeGet(child.node.children, next) || {\r\n children: {},\r\n childCount: 0\r\n };\r\n child = new Tree(next, child, childNode);\r\n path = pathPopFront(path);\r\n next = pathGetFront(path);\r\n }\r\n return child;\r\n}\r\n/**\r\n * Returns the data associated with this tree node.\r\n *\r\n * @returns The data or null if no data exists.\r\n */\r\nfunction treeGetValue(tree) {\r\n return tree.node.value;\r\n}\r\n/**\r\n * Sets data to this tree node.\r\n *\r\n * @param value - Value to set.\r\n */\r\nfunction treeSetValue(tree, value) {\r\n tree.node.value = value;\r\n treeUpdateParents(tree);\r\n}\r\n/**\r\n * @returns Whether the tree has any children.\r\n */\r\nfunction treeHasChildren(tree) {\r\n return tree.node.childCount > 0;\r\n}\r\n/**\r\n * @returns Whethe rthe tree is empty (no value or children).\r\n */\r\nfunction treeIsEmpty(tree) {\r\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\r\n}\r\n/**\r\n * Calls action for each child of this tree node.\r\n *\r\n * @param action - Action to be called for each child.\r\n */\r\nfunction treeForEachChild(tree, action) {\r\n each(tree.node.children, (child, childTree) => {\r\n action(new Tree(child, tree, childTree));\r\n });\r\n}\r\n/**\r\n * Does a depth-first traversal of this node's descendants, calling action for each one.\r\n *\r\n * @param action - Action to be called for each child.\r\n * @param includeSelf - Whether to call action on this node as well. Defaults to\r\n * false.\r\n * @param childrenFirst - Whether to call action on children before calling it on\r\n * parent.\r\n */\r\nfunction treeForEachDescendant(tree, action, includeSelf, childrenFirst) {\r\n if (includeSelf && !childrenFirst) {\r\n action(tree);\r\n }\r\n treeForEachChild(tree, child => {\r\n treeForEachDescendant(child, action, true, childrenFirst);\r\n });\r\n if (includeSelf && childrenFirst) {\r\n action(tree);\r\n }\r\n}\r\n/**\r\n * Calls action on each ancestor node.\r\n *\r\n * @param action - Action to be called on each parent; return\r\n * true to abort.\r\n * @param includeSelf - Whether to call action on this node as well.\r\n * @returns true if the action callback returned true.\r\n */\r\nfunction treeForEachAncestor(tree, action, includeSelf) {\r\n let node = includeSelf ? tree : tree.parent;\r\n while (node !== null) {\r\n if (action(node)) {\r\n return true;\r\n }\r\n node = node.parent;\r\n }\r\n return false;\r\n}\r\n/**\r\n * @returns The path of this tree node, as a Path.\r\n */\r\nfunction treeGetPath(tree) {\r\n return new Path(tree.parent === null\r\n ? tree.name\r\n : treeGetPath(tree.parent) + '/' + tree.name);\r\n}\r\n/**\r\n * Adds or removes this child from its parent based on whether it's empty or not.\r\n */\r\nfunction treeUpdateParents(tree) {\r\n if (tree.parent !== null) {\r\n treeUpdateChild(tree.parent, tree.name, tree);\r\n }\r\n}\r\n/**\r\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\r\n *\r\n * @param childName - The name of the child to update.\r\n * @param child - The child to update.\r\n */\r\nfunction treeUpdateChild(tree, childName, child) {\r\n const childEmpty = treeIsEmpty(child);\r\n const childExists = contains(tree.node.children, childName);\r\n if (childEmpty && childExists) {\r\n delete tree.node.children[childName];\r\n tree.node.childCount--;\r\n treeUpdateParents(tree);\r\n }\r\n else if (!childEmpty && !childExists) {\r\n tree.node.children[childName] = child.node;\r\n tree.node.childCount++;\r\n treeUpdateParents(tree);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * True for invalid Firebase keys\r\n */\r\nconst INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * True for invalid Firebase paths.\r\n * Allows '/' in paths.\r\n */\r\nconst INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * Maximum number of characters to allow in leaf value\r\n */\r\nconst MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\r\nconst isValidKey = function (key) {\r\n return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\r\n};\r\nconst isValidPathString = function (pathString) {\r\n return (typeof pathString === 'string' &&\r\n pathString.length !== 0 &&\r\n !INVALID_PATH_REGEX_.test(pathString));\r\n};\r\nconst isValidRootPathString = function (pathString) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n return isValidPathString(pathString);\r\n};\r\nconst isValidPriority = function (priority) {\r\n return (priority === null ||\r\n typeof priority === 'string' ||\r\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\r\n (priority &&\r\n typeof priority === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n contains(priority, '.sv')));\r\n};\r\n/**\r\n * Pre-validate a datum passed as an argument to Firebase function.\r\n */\r\nconst validateFirebaseDataArg = function (fnName, value, path, optional) {\r\n if (optional && value === undefined) {\r\n return;\r\n }\r\n validateFirebaseData(errorPrefix(fnName, 'value'), value, path);\r\n};\r\n/**\r\n * Validate a data object client-side before sending to server.\r\n */\r\nconst validateFirebaseData = function (errorPrefix, data, path_) {\r\n const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\r\n if (data === undefined) {\r\n throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));\r\n }\r\n if (typeof data === 'function') {\r\n throw new Error(errorPrefix +\r\n 'contains a function ' +\r\n validationPathToErrorString(path) +\r\n ' with contents = ' +\r\n data.toString());\r\n }\r\n if (isInvalidJSONNumber(data)) {\r\n throw new Error(errorPrefix +\r\n 'contains ' +\r\n data.toString() +\r\n ' ' +\r\n validationPathToErrorString(path));\r\n }\r\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\r\n if (typeof data === 'string' &&\r\n data.length > MAX_LEAF_SIZE_ / 3 &&\r\n stringLength(data) > MAX_LEAF_SIZE_) {\r\n throw new Error(errorPrefix +\r\n 'contains a string greater than ' +\r\n MAX_LEAF_SIZE_ +\r\n ' utf8 bytes ' +\r\n validationPathToErrorString(path) +\r\n \" ('\" +\r\n data.substring(0, 50) +\r\n \"...')\");\r\n }\r\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\r\n // to save extra walking of large objects.\r\n if (data && typeof data === 'object') {\r\n let hasDotValue = false;\r\n let hasActualChild = false;\r\n each(data, (key, value) => {\r\n if (key === '.value') {\r\n hasDotValue = true;\r\n }\r\n else if (key !== '.priority' && key !== '.sv') {\r\n hasActualChild = true;\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix +\r\n ' contains an invalid key (' +\r\n key +\r\n ') ' +\r\n validationPathToErrorString(path) +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n validationPathPush(path, key);\r\n validateFirebaseData(errorPrefix, value, path);\r\n validationPathPop(path);\r\n });\r\n if (hasDotValue && hasActualChild) {\r\n throw new Error(errorPrefix +\r\n ' contains \".value\" child ' +\r\n validationPathToErrorString(path) +\r\n ' in addition to actual children.');\r\n }\r\n }\r\n};\r\n/**\r\n * Pre-validate paths passed in the firebase function.\r\n */\r\nconst validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\r\n let i, curPath;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n const keys = pathSlice(curPath);\r\n for (let j = 0; j < keys.length; j++) {\r\n if (keys[j] === '.priority' && j === keys.length - 1) ;\r\n else if (!isValidKey(keys[j])) {\r\n throw new Error(errorPrefix +\r\n 'contains an invalid key (' +\r\n keys[j] +\r\n ') in path ' +\r\n curPath.toString() +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n }\r\n // Check that update keys are not descendants of each other.\r\n // We rely on the property that sorting guarantees that ancestors come\r\n // right before descendants.\r\n mergePaths.sort(pathCompare);\r\n let prevPath = null;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n if (prevPath !== null && pathContains(prevPath, curPath)) {\r\n throw new Error(errorPrefix +\r\n 'contains a path ' +\r\n prevPath.toString() +\r\n ' that is ancestor of another path ' +\r\n curPath.toString());\r\n }\r\n prevPath = curPath;\r\n }\r\n};\r\n/**\r\n * pre-validate an object passed as an argument to firebase function (\r\n * must be an object - e.g. for firebase.update()).\r\n */\r\nconst validateFirebaseMergeDataArg = function (fnName, data, path, optional) {\r\n if (optional && data === undefined) {\r\n return;\r\n }\r\n const errorPrefix$1 = errorPrefix(fnName, 'values');\r\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\r\n throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');\r\n }\r\n const mergePaths = [];\r\n each(data, (key, value) => {\r\n const curPath = new Path(key);\r\n validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));\r\n if (pathGetBack(curPath) === '.priority') {\r\n if (!isValidPriority(value)) {\r\n throw new Error(errorPrefix$1 +\r\n \"contains an invalid value for '\" +\r\n curPath.toString() +\r\n \"', which must be a valid \" +\r\n 'Firebase priority (a string, finite number, server value, or null).');\r\n }\r\n }\r\n mergePaths.push(curPath);\r\n });\r\n validateFirebaseMergePaths(errorPrefix$1, mergePaths);\r\n};\r\nconst validatePriority = function (fnName, priority, optional) {\r\n if (optional && priority === undefined) {\r\n return;\r\n }\r\n if (isInvalidJSONNumber(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'is ' +\r\n priority.toString() +\r\n ', but must be a valid Firebase priority (a string, finite number, ' +\r\n 'server value, or null).');\r\n }\r\n // Special case to allow importing data with a .sv.\r\n if (!isValidPriority(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'must be a valid Firebase priority ' +\r\n '(a string, finite number, server value, or null).');\r\n }\r\n};\r\nconst validateKey = function (fnName, argumentName, key, optional) {\r\n if (optional && key === undefined) {\r\n return;\r\n }\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid key = \"' +\r\n key +\r\n '\". Firebase keys must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\r\n }\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validatePathString = function (fnName, argumentName, pathString, optional) {\r\n if (optional && pathString === undefined) {\r\n return;\r\n }\r\n if (!isValidPathString(pathString)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid path = \"' +\r\n pathString +\r\n '\". Paths must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\r\n }\r\n};\r\nconst validateRootPathString = function (fnName, argumentName, pathString, optional) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n validatePathString(fnName, argumentName, pathString, optional);\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validateWritablePath = function (fnName, path) {\r\n if (pathGetFront(path) === '.info') {\r\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\r\n }\r\n};\r\nconst validateUrl = function (fnName, parsedUrl) {\r\n // TODO = Validate server better.\r\n const pathString = parsedUrl.path.toString();\r\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\r\n parsedUrl.repoInfo.host.length === 0 ||\r\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\r\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\r\n (pathString.length !== 0 && !isValidRootPathString(pathString))) {\r\n throw new Error(errorPrefix(fnName, 'url') +\r\n 'must be a valid firebase URL and ' +\r\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\r\n }\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The event queue serves a few purposes:\r\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\r\n * events being queued.\r\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\r\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\r\n * left off, ensuring that the events are still raised synchronously and in order.\r\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\r\n * events are raised synchronously.\r\n *\r\n * NOTE: This can all go away if/when we move to async events.\r\n *\r\n */\r\nclass EventQueue {\r\n constructor() {\r\n this.eventLists_ = [];\r\n /**\r\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\r\n */\r\n this.recursionDepth_ = 0;\r\n }\r\n}\r\n/**\r\n * @param eventDataList - The new events to queue.\r\n */\r\nfunction eventQueueQueueEvents(eventQueue, eventDataList) {\r\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\r\n let currList = null;\r\n for (let i = 0; i < eventDataList.length; i++) {\r\n const data = eventDataList[i];\r\n const path = data.getPath();\r\n if (currList !== null && !pathEquals(path, currList.path)) {\r\n eventQueue.eventLists_.push(currList);\r\n currList = null;\r\n }\r\n if (currList === null) {\r\n currList = { events: [], path };\r\n }\r\n currList.events.push(data);\r\n }\r\n if (currList) {\r\n eventQueue.eventLists_.push(currList);\r\n }\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones)\r\n * for the specified path.\r\n *\r\n * It is assumed that the new events are all for the specified path.\r\n *\r\n * @param path - The path to raise events for.\r\n * @param eventDataList - The new events to raise.\r\n */\r\nfunction eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\r\n * locations related to the specified change path (i.e. all ancestors and descendants).\r\n *\r\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\r\n *\r\n * @param changedPath - The path to raise events for.\r\n * @param eventDataList - The events to raise\r\n */\r\nfunction eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||\r\n pathContains(changedPath, eventPath));\r\n}\r\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {\r\n eventQueue.recursionDepth_++;\r\n let sentAll = true;\r\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\r\n const eventList = eventQueue.eventLists_[i];\r\n if (eventList) {\r\n const eventPath = eventList.path;\r\n if (predicate(eventPath)) {\r\n eventListRaise(eventQueue.eventLists_[i]);\r\n eventQueue.eventLists_[i] = null;\r\n }\r\n else {\r\n sentAll = false;\r\n }\r\n }\r\n }\r\n if (sentAll) {\r\n eventQueue.eventLists_ = [];\r\n }\r\n eventQueue.recursionDepth_--;\r\n}\r\n/**\r\n * Iterates through the list and raises each event\r\n */\r\nfunction eventListRaise(eventList) {\r\n for (let i = 0; i < eventList.events.length; i++) {\r\n const eventData = eventList.events[i];\r\n if (eventData !== null) {\r\n eventList.events[i] = null;\r\n const eventFn = eventData.getEventRunner();\r\n if (logger) {\r\n log('event: ' + eventData.toString());\r\n }\r\n exceptionGuard(eventFn);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INTERRUPT_REASON = 'repo_interrupt';\r\n/**\r\n * If a transaction does not succeed after 25 retries, we abort it. Among other\r\n * things this ensure that if there's ever a bug causing a mismatch between\r\n * client / server hashes for some data, we won't retry indefinitely.\r\n */\r\nconst MAX_TRANSACTION_RETRIES = 25;\r\n/**\r\n * A connection to a single data repository.\r\n */\r\nclass Repo {\r\n constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {\r\n this.repoInfo_ = repoInfo_;\r\n this.forceRestClient_ = forceRestClient_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckProvider_ = appCheckProvider_;\r\n this.dataUpdateCount = 0;\r\n this.statsListener_ = null;\r\n this.eventQueue_ = new EventQueue();\r\n this.nextWriteId_ = 1;\r\n this.interceptServerDataCallback_ = null;\r\n /** A list of data pieces and paths to be set when this client disconnects. */\r\n this.onDisconnect_ = newSparseSnapshotTree();\r\n /** Stores queues of outstanding transactions for Firebase locations. */\r\n this.transactionQueueTree_ = new Tree();\r\n // TODO: This should be @private but it's used by test_access.js and internal.js\r\n this.persistentConnection_ = null;\r\n // This key is intentionally not updated if RepoInfo is later changed or replaced\r\n this.key = this.repoInfo_.toURLString();\r\n }\r\n /**\r\n * @returns The URL corresponding to the root of this Firebase.\r\n */\r\n toString() {\r\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\r\n }\r\n}\r\nfunction repoStart(repo, appId, authOverride) {\r\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\r\n if (repo.forceRestClient_ || beingCrawled()) {\r\n repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_);\r\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\r\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\r\n }\r\n else {\r\n // Validate authOverride\r\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\r\n if (typeof authOverride !== 'object') {\r\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\r\n }\r\n try {\r\n stringify(authOverride);\r\n }\r\n catch (e) {\r\n throw new Error('Invalid authOverride provided: ' + e);\r\n }\r\n }\r\n repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, (connectStatus) => {\r\n repoOnConnectStatus(repo, connectStatus);\r\n }, (updates) => {\r\n repoOnServerInfoUpdate(repo, updates);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);\r\n repo.server_ = repo.persistentConnection_;\r\n }\r\n repo.authTokenProvider_.addTokenChangeListener(token => {\r\n repo.server_.refreshAuthToken(token);\r\n });\r\n repo.appCheckProvider_.addTokenChangeListener(result => {\r\n repo.server_.refreshAppCheckToken(result.token);\r\n });\r\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\r\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\r\n repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));\r\n // Used for .info.\r\n repo.infoData_ = new SnapshotHolder();\r\n repo.infoSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n let infoEvents = [];\r\n const node = repo.infoData_.getNode(query._path);\r\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\r\n // on initial data...\r\n if (!node.isEmpty()) {\r\n infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);\r\n setTimeout(() => {\r\n onComplete('ok');\r\n }, 0);\r\n }\r\n return infoEvents;\r\n },\r\n stopListening: () => { }\r\n });\r\n repoUpdateInfo(repo, 'connected', false);\r\n repo.serverSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\r\n const events = onComplete(status, data);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n });\r\n // No synchronous events for network-backed sync trees\r\n return [];\r\n },\r\n stopListening: (query, tag) => {\r\n repo.server_.unlisten(query, tag);\r\n }\r\n });\r\n}\r\n/**\r\n * @returns The time in milliseconds, taking the server offset into account if we have one.\r\n */\r\nfunction repoServerTime(repo) {\r\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\r\n const offset = offsetNode.val() || 0;\r\n return new Date().getTime() + offset;\r\n}\r\n/**\r\n * Generate ServerValues using some variables from the repo object.\r\n */\r\nfunction repoGenerateServerValues(repo) {\r\n return generateWithValues({\r\n timestamp: repoServerTime(repo)\r\n });\r\n}\r\n/**\r\n * Called by realtime when we get new messages from the server.\r\n */\r\nfunction repoOnDataUpdate(repo, pathString, data, isMerge, tag) {\r\n // For testing.\r\n repo.dataUpdateCount++;\r\n const path = new Path(pathString);\r\n data = repo.interceptServerDataCallback_\r\n ? repo.interceptServerDataCallback_(pathString, data)\r\n : data;\r\n let events = [];\r\n if (tag) {\r\n if (isMerge) {\r\n const taggedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);\r\n }\r\n else {\r\n const taggedSnap = nodeFromJSON(data);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);\r\n }\r\n }\r\n else if (isMerge) {\r\n const changedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);\r\n }\r\n else {\r\n const snap = nodeFromJSON(data);\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\r\n }\r\n let affectedPath = path;\r\n if (events.length > 0) {\r\n // Since we have a listener outstanding for each transaction, receiving any events\r\n // is a proxy for some change having occurred.\r\n affectedPath = repoRerunTransactions(repo, path);\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\r\n}\r\nfunction repoOnConnectStatus(repo, connectStatus) {\r\n repoUpdateInfo(repo, 'connected', connectStatus);\r\n if (connectStatus === false) {\r\n repoRunOnDisconnectEvents(repo);\r\n }\r\n}\r\nfunction repoOnServerInfoUpdate(repo, updates) {\r\n each(updates, (key, value) => {\r\n repoUpdateInfo(repo, key, value);\r\n });\r\n}\r\nfunction repoUpdateInfo(repo, pathString, value) {\r\n const path = new Path('/.info/' + pathString);\r\n const newNode = nodeFromJSON(value);\r\n repo.infoData_.updateSnapshot(path, newNode);\r\n const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n}\r\nfunction repoGetNextWriteId(repo) {\r\n return repo.nextWriteId_++;\r\n}\r\n/**\r\n * The purpose of `getValue` is to return the latest known value\r\n * satisfying `query`.\r\n *\r\n * This method will first check for in-memory cached values\r\n * belonging to active listeners. If they are found, such values\r\n * are considered to be the most up-to-date.\r\n *\r\n * If the client is not connected, this method will try to\r\n * establish a connection and request the value for `query`. If\r\n * the client is not able to retrieve the query result, it reports\r\n * an error.\r\n *\r\n * @param query - The query to surface a value for.\r\n */\r\nfunction repoGetValue(repo, query) {\r\n // Only active queries are cached. There is no persisted cache.\r\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\r\n if (cached != null) {\r\n return Promise.resolve(cached);\r\n }\r\n return repo.server_.get(query).then(payload => {\r\n const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());\r\n const events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n return Promise.resolve(node);\r\n }, err => {\r\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\r\n return Promise.reject(new Error(err));\r\n });\r\n}\r\nfunction repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {\r\n repoLog(repo, 'set', {\r\n path: path.toString(),\r\n value: newVal,\r\n priority: newPriority\r\n });\r\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\r\n // (b) store unresolved paths on JSON parse\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\r\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('set at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\r\n}\r\nfunction repoUpdate(repo, path, childrenToMerge, onComplete) {\r\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\r\n // Start with our existing data and merge each child into it.\r\n let empty = true;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const changedChildren = {};\r\n each(childrenToMerge, (changedKey, changedValue) => {\r\n empty = false;\r\n changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);\r\n });\r\n if (!empty) {\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('update at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n each(childrenToMerge, (changedPath) => {\r\n const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\r\n }\r\n else {\r\n log(\"update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n }\r\n}\r\n/**\r\n * Applies all of the changes stored up in the onDisconnect_ tree.\r\n */\r\nfunction repoRunOnDisconnectEvents(repo) {\r\n repoLog(repo, 'onDisconnectEvents');\r\n const serverValues = repoGenerateServerValues(repo);\r\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\r\n sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {\r\n const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);\r\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\r\n });\r\n let events = [];\r\n sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {\r\n events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n repo.onDisconnect_ = newSparseSnapshotTree();\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\r\n}\r\nfunction repoOnDisconnectCancel(repo, path, onComplete) {\r\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSet(repo, path, value, onComplete) {\r\n const newNode = nodeFromJSON(value);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {\r\n const newNode = nodeFromJSON(value, priority);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {\r\n if (isEmpty(childrenToMerge)) {\r\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n return;\r\n }\r\n repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n if (status === 'ok') {\r\n each(childrenToMerge, (childName, childNode) => {\r\n const newChildNode = nodeFromJSON(childNode);\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);\r\n });\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoAddEventCallbackForQuery(repo, query, eventRegistration) {\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {\r\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\r\n // a little bit by handling the return values anyways.\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoInterrupt(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoResume(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.resume(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoLog(repo, ...varArgs) {\r\n let prefix = '';\r\n if (repo.persistentConnection_) {\r\n prefix = repo.persistentConnection_.id + ':';\r\n }\r\n log(prefix, ...varArgs);\r\n}\r\nfunction repoCallOnCompleteCallback(repo, callback, status, errorReason) {\r\n if (callback) {\r\n exceptionGuard(() => {\r\n if (status === 'ok') {\r\n callback(null);\r\n }\r\n else {\r\n const code = (status || 'error').toUpperCase();\r\n let message = code;\r\n if (errorReason) {\r\n message += ': ' + errorReason;\r\n }\r\n const error = new Error(message);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code;\r\n callback(error);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Creates a new transaction, adds it to the transactions we're tracking, and\r\n * sends it to the server if possible.\r\n *\r\n * @param path - Path at which to do transaction.\r\n * @param transactionUpdate - Update callback.\r\n * @param onComplete - Completion callback.\r\n * @param unwatcher - Function that will be called when the transaction no longer\r\n * need data updates for `path`.\r\n * @param applyLocally - Whether or not to make intermediate results visible\r\n */\r\nfunction repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {\r\n repoLog(repo, 'transaction on ' + path);\r\n // Initialize transaction.\r\n const transaction = {\r\n path,\r\n update: transactionUpdate,\r\n onComplete,\r\n // One of TransactionStatus enums.\r\n status: null,\r\n // Used when combining transactions at different locations to figure out\r\n // which one goes first.\r\n order: LUIDGenerator(),\r\n // Whether to raise local events for this transaction.\r\n applyLocally,\r\n // Count of how many times we've retried the transaction.\r\n retryCount: 0,\r\n // Function to call to clean up our .on() listener.\r\n unwatcher,\r\n // Stores why a transaction was aborted.\r\n abortReason: null,\r\n currentWriteId: null,\r\n currentInputSnapshot: null,\r\n currentOutputSnapshotRaw: null,\r\n currentOutputSnapshotResolved: null\r\n };\r\n // Run transaction initially.\r\n const currentState = repoGetLatestState(repo, path, undefined);\r\n transaction.currentInputSnapshot = currentState;\r\n const newVal = transaction.update(currentState.val());\r\n if (newVal === undefined) {\r\n // Abort transaction.\r\n transaction.unwatcher();\r\n transaction.currentOutputSnapshotRaw = null;\r\n transaction.currentOutputSnapshotResolved = null;\r\n if (transaction.onComplete) {\r\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\r\n }\r\n }\r\n else {\r\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\r\n // Mark as run and add to our queue.\r\n transaction.status = 0 /* RUN */;\r\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\r\n const nodeQueue = treeGetValue(queueNode) || [];\r\n nodeQueue.push(transaction);\r\n treeSetValue(queueNode, nodeQueue);\r\n // Update visibleData and raise events\r\n // Note: We intentionally raise events after updating all of our\r\n // transaction state, since the user could start new transactions from the\r\n // event callbacks.\r\n let priorityForNode;\r\n if (typeof newVal === 'object' &&\r\n newVal !== null &&\r\n contains(newVal, '.priority')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n priorityForNode = safeGet(newVal, '.priority');\r\n assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\r\n 'Priority must be a valid string, finite number, server value, or null.');\r\n }\r\n else {\r\n const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\r\n ChildrenNode.EMPTY_NODE;\r\n priorityForNode = currentNode.getPriority().val();\r\n }\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);\r\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\r\n transaction.currentOutputSnapshotResolved = newNode;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n }\r\n}\r\n/**\r\n * @param excludeSets - A specific set to exclude\r\n */\r\nfunction repoGetLatestState(repo, path, excludeSets) {\r\n return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\r\n ChildrenNode.EMPTY_NODE);\r\n}\r\n/**\r\n * Sends any already-run transactions that aren't waiting for outstanding\r\n * transactions to complete.\r\n *\r\n * Externally it's called with no arguments, but it calls itself recursively\r\n * with a particular transactionQueueTree node to recurse through the tree.\r\n *\r\n * @param node - transactionQueueTree node to start at.\r\n */\r\nfunction repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {\r\n // Before recursing, make sure any completed transactions are removed.\r\n if (!node) {\r\n repoPruneCompletedTransactionsBelowNode(repo, node);\r\n }\r\n if (treeGetValue(node)) {\r\n const queue = repoBuildTransactionQueue(repo, node);\r\n assert(queue.length > 0, 'Sending zero length transaction queue');\r\n const allRun = queue.every((transaction) => transaction.status === 0 /* RUN */);\r\n // If they're all run (and not sent), we can send them. Else, we must wait.\r\n if (allRun) {\r\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\r\n }\r\n }\r\n else if (treeHasChildren(node)) {\r\n treeForEachChild(node, childNode => {\r\n repoSendReadyTransactions(repo, childNode);\r\n });\r\n }\r\n}\r\n/**\r\n * Given a list of run transactions, send them to the server and then handle\r\n * the result (success or failure).\r\n *\r\n * @param path - The location of the queue.\r\n * @param queue - Queue of transactions under the specified location.\r\n */\r\nfunction repoSendTransactionQueue(repo, path, queue) {\r\n // Mark transactions as sent and increment retry count!\r\n const setsToIgnore = queue.map(txn => {\r\n return txn.currentWriteId;\r\n });\r\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\r\n let snapToSend = latestState;\r\n const latestHash = latestState.hash();\r\n for (let i = 0; i < queue.length; i++) {\r\n const txn = queue[i];\r\n assert(txn.status === 0 /* RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');\r\n txn.status = 1 /* SENT */;\r\n txn.retryCount++;\r\n const relativePath = newRelativePath(path, txn.path);\r\n // If we've gotten to this point, the output snapshot must be defined.\r\n snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);\r\n }\r\n const dataToSend = snapToSend.val(true);\r\n const pathToSend = path;\r\n // Send the put.\r\n repo.server_.put(pathToSend.toString(), dataToSend, (status) => {\r\n repoLog(repo, 'transaction put response', {\r\n path: pathToSend.toString(),\r\n status\r\n });\r\n let events = [];\r\n if (status === 'ok') {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more\r\n // transactions or sets.\r\n const callbacks = [];\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 2 /* COMPLETED */;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));\r\n if (queue[i].onComplete) {\r\n // We never unset the output snapshot, and given that this\r\n // transaction is complete, it should be set\r\n callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));\r\n }\r\n queue[i].unwatcher();\r\n }\r\n // Now remove the completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));\r\n // There may be pending transactions that we can now send.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n // Finally, trigger onComplete callbacks.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n else {\r\n // transactions are no longer sent. Update their status appropriately.\r\n if (status === 'datastale') {\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* SENT_NEEDS_ABORT */) {\r\n queue[i].status = 4 /* NEEDS_ABORT */;\r\n }\r\n else {\r\n queue[i].status = 0 /* RUN */;\r\n }\r\n }\r\n }\r\n else {\r\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 4 /* NEEDS_ABORT */;\r\n queue[i].abortReason = status;\r\n }\r\n }\r\n repoRerunTransactions(repo, path);\r\n }\r\n }, latestHash);\r\n}\r\n/**\r\n * Finds all transactions dependent on the data at changedPath and reruns them.\r\n *\r\n * Should be called any time cached data changes.\r\n *\r\n * Return the highest path that was affected by rerunning transactions. This\r\n * is the path at which events need to be raised for.\r\n *\r\n * @param changedPath - The path in mergedData that changed.\r\n * @returns The rootmost path that was affected by rerunning transactions.\r\n */\r\nfunction repoRerunTransactions(repo, changedPath) {\r\n const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);\r\n const path = treeGetPath(rootMostTransactionNode);\r\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\r\n repoRerunTransactionQueue(repo, queue, path);\r\n return path;\r\n}\r\n/**\r\n * Does all the work of rerunning transactions (as well as cleans up aborted\r\n * transactions and whatnot).\r\n *\r\n * @param queue - The queue of transactions to run.\r\n * @param path - The path the queue is for.\r\n */\r\nfunction repoRerunTransactionQueue(repo, queue, path) {\r\n if (queue.length === 0) {\r\n return; // Nothing to do!\r\n }\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions or\r\n // sets.\r\n const callbacks = [];\r\n let events = [];\r\n // Ignore all of the sets we're going to re-run.\r\n const txnsToRerun = queue.filter(q => {\r\n return q.status === 0 /* RUN */;\r\n });\r\n const setsToIgnore = txnsToRerun.map(q => {\r\n return q.currentWriteId;\r\n });\r\n for (let i = 0; i < queue.length; i++) {\r\n const transaction = queue[i];\r\n const relativePath = newRelativePath(path, transaction.path);\r\n let abortTransaction = false, abortReason;\r\n assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\r\n if (transaction.status === 4 /* NEEDS_ABORT */) {\r\n abortTransaction = true;\r\n abortReason = transaction.abortReason;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else if (transaction.status === 0 /* RUN */) {\r\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\r\n abortTransaction = true;\r\n abortReason = 'maxretry';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else {\r\n // This code reruns a transaction\r\n const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);\r\n transaction.currentInputSnapshot = currentNode;\r\n const newData = queue[i].update(currentNode.val());\r\n if (newData !== undefined) {\r\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\r\n let newDataNode = nodeFromJSON(newData);\r\n const hasExplicitPriority = typeof newData === 'object' &&\r\n newData != null &&\r\n contains(newData, '.priority');\r\n if (!hasExplicitPriority) {\r\n // Keep the old priority if there wasn't a priority explicitly specified.\r\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\r\n }\r\n const oldWriteId = transaction.currentWriteId;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);\r\n transaction.currentOutputSnapshotRaw = newDataNode;\r\n transaction.currentOutputSnapshotResolved = newNodeResolved;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n // Mutates setsToIgnore in place\r\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\r\n events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));\r\n }\r\n else {\r\n abortTransaction = true;\r\n abortReason = 'nodata';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n }\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n events = [];\r\n if (abortTransaction) {\r\n // Abort.\r\n queue[i].status = 2 /* COMPLETED */;\r\n // Removing a listener can trigger pruning which can muck with\r\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\r\n // until we're done.\r\n (function (unwatcher) {\r\n setTimeout(unwatcher, Math.floor(0));\r\n })(queue[i].unwatcher);\r\n if (queue[i].onComplete) {\r\n if (abortReason === 'nodata') {\r\n callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));\r\n }\r\n else {\r\n callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));\r\n }\r\n }\r\n }\r\n }\r\n // Clean up completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\r\n // Now fire callbacks, now that we're in a good, known state.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n // Try to send the transaction result to the server.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n}\r\n/**\r\n * Returns the rootmost ancestor node of the specified path that has a pending\r\n * transaction on it, or just returns the node for the given path if there are\r\n * no pending transactions on any ancestor.\r\n *\r\n * @param path - The location to start at.\r\n * @returns The rootmost node with a transaction.\r\n */\r\nfunction repoGetAncestorTransactionNode(repo, path) {\r\n let front;\r\n // Start at the root and walk deeper into the tree towards path until we\r\n // find a node with pending transactions.\r\n let transactionNode = repo.transactionQueueTree_;\r\n front = pathGetFront(path);\r\n while (front !== null && treeGetValue(transactionNode) === undefined) {\r\n transactionNode = treeSubTree(transactionNode, front);\r\n path = pathPopFront(path);\r\n front = pathGetFront(path);\r\n }\r\n return transactionNode;\r\n}\r\n/**\r\n * Builds the queue of all transactions at or below the specified\r\n * transactionNode.\r\n *\r\n * @param transactionNode\r\n * @returns The generated queue.\r\n */\r\nfunction repoBuildTransactionQueue(repo, transactionNode) {\r\n // Walk any child transaction queues and aggregate them into a single queue.\r\n const transactionQueue = [];\r\n repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);\r\n // Sort them by the order the transactions were created.\r\n transactionQueue.sort((a, b) => a.order - b.order);\r\n return transactionQueue;\r\n}\r\nfunction repoAggregateTransactionQueuesForNode(repo, node, queue) {\r\n const nodeQueue = treeGetValue(node);\r\n if (nodeQueue) {\r\n for (let i = 0; i < nodeQueue.length; i++) {\r\n queue.push(nodeQueue[i]);\r\n }\r\n }\r\n treeForEachChild(node, child => {\r\n repoAggregateTransactionQueuesForNode(repo, child, queue);\r\n });\r\n}\r\n/**\r\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\r\n */\r\nfunction repoPruneCompletedTransactionsBelowNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n let to = 0;\r\n for (let from = 0; from < queue.length; from++) {\r\n if (queue[from].status !== 2 /* COMPLETED */) {\r\n queue[to] = queue[from];\r\n to++;\r\n }\r\n }\r\n queue.length = to;\r\n treeSetValue(node, queue.length > 0 ? queue : undefined);\r\n }\r\n treeForEachChild(node, childNode => {\r\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\r\n });\r\n}\r\n/**\r\n * Aborts all transactions on ancestors or descendants of the specified path.\r\n * Called when doing a set() or update() since we consider them incompatible\r\n * with transactions.\r\n *\r\n * @param path - Path for which we want to abort related transactions.\r\n */\r\nfunction repoAbortTransactions(repo, path) {\r\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\r\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\r\n treeForEachAncestor(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n repoAbortTransactionsOnNode(repo, transactionNode);\r\n treeForEachDescendant(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n return affectedPath;\r\n}\r\n/**\r\n * Abort transactions stored in this transaction queue node.\r\n *\r\n * @param node - Node to abort transactions for.\r\n */\r\nfunction repoAbortTransactionsOnNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions\r\n // or sets.\r\n const callbacks = [];\r\n // Go through queue. Any already-sent transactions must be marked for\r\n // abort, while the unsent ones can be immediately aborted and removed.\r\n let events = [];\r\n let lastSent = -1;\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* SENT_NEEDS_ABORT */) ;\r\n else if (queue[i].status === 1 /* SENT */) {\r\n assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\r\n lastSent = i;\r\n // Mark transaction for abort when it comes back.\r\n queue[i].status = 3 /* SENT_NEEDS_ABORT */;\r\n queue[i].abortReason = 'set';\r\n }\r\n else {\r\n assert(queue[i].status === 0 /* RUN */, 'Unexpected transaction status in abort');\r\n // We can abort it immediately.\r\n queue[i].unwatcher();\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));\r\n if (queue[i].onComplete) {\r\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));\r\n }\r\n }\r\n }\r\n if (lastSent === -1) {\r\n // We're not waiting for any sent transactions. We can clear the queue.\r\n treeSetValue(node, undefined);\r\n }\r\n else {\r\n // Remove the transactions we aborted.\r\n queue.length = lastSent + 1;\r\n }\r\n // Now fire the callbacks.\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction decodePath(pathString) {\r\n let pathStringDecoded = '';\r\n const pieces = pathString.split('/');\r\n for (let i = 0; i < pieces.length; i++) {\r\n if (pieces[i].length > 0) {\r\n let piece = pieces[i];\r\n try {\r\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\r\n }\r\n catch (e) { }\r\n pathStringDecoded += '/' + piece;\r\n }\r\n }\r\n return pathStringDecoded;\r\n}\r\n/**\r\n * @returns key value hash\r\n */\r\nfunction decodeQuery(queryString) {\r\n const results = {};\r\n if (queryString.charAt(0) === '?') {\r\n queryString = queryString.substring(1);\r\n }\r\n for (const segment of queryString.split('&')) {\r\n if (segment.length === 0) {\r\n continue;\r\n }\r\n const kv = segment.split('=');\r\n if (kv.length === 2) {\r\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\r\n }\r\n else {\r\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\r\n }\r\n }\r\n return results;\r\n}\r\nconst parseRepoInfo = function (dataURL, nodeAdmin) {\r\n const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;\r\n if (parsedUrl.domain === 'firebase.com') {\r\n fatal(parsedUrl.host +\r\n ' is no longer supported. ' +\r\n 'Please use .firebaseio.com instead');\r\n }\r\n // Catch common error of uninitialized namespace value.\r\n if ((!namespace || namespace === 'undefined') &&\r\n parsedUrl.domain !== 'localhost') {\r\n fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\r\n }\r\n if (!parsedUrl.secure) {\r\n warnIfPageIsSecure();\r\n }\r\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\r\n return {\r\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, nodeAdmin, webSocketOnly, \r\n /*persistenceKey=*/ '', \r\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),\r\n path: new Path(parsedUrl.pathString)\r\n };\r\n};\r\nconst parseDatabaseURL = function (dataURL) {\r\n // Default to empty strings in the event of a malformed string.\r\n let host = '', domain = '', subdomain = '', pathString = '', namespace = '';\r\n // Always default to SSL, unless otherwise specified.\r\n let secure = true, scheme = 'https', port = 443;\r\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\r\n if (typeof dataURL === 'string') {\r\n // Parse scheme.\r\n let colonInd = dataURL.indexOf('//');\r\n if (colonInd >= 0) {\r\n scheme = dataURL.substring(0, colonInd - 1);\r\n dataURL = dataURL.substring(colonInd + 2);\r\n }\r\n // Parse host, path, and query string.\r\n let slashInd = dataURL.indexOf('/');\r\n if (slashInd === -1) {\r\n slashInd = dataURL.length;\r\n }\r\n let questionMarkInd = dataURL.indexOf('?');\r\n if (questionMarkInd === -1) {\r\n questionMarkInd = dataURL.length;\r\n }\r\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\r\n if (slashInd < questionMarkInd) {\r\n // For pathString, questionMarkInd will always come after slashInd\r\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\r\n }\r\n const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\r\n // If we have a port, use scheme for determining if it's secure.\r\n colonInd = host.indexOf(':');\r\n if (colonInd >= 0) {\r\n secure = scheme === 'https' || scheme === 'wss';\r\n port = parseInt(host.substring(colonInd + 1), 10);\r\n }\r\n else {\r\n colonInd = host.length;\r\n }\r\n const hostWithoutPort = host.slice(0, colonInd);\r\n if (hostWithoutPort.toLowerCase() === 'localhost') {\r\n domain = 'localhost';\r\n }\r\n else if (hostWithoutPort.split('.').length <= 2) {\r\n domain = hostWithoutPort;\r\n }\r\n else {\r\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\r\n const dotInd = host.indexOf('.');\r\n subdomain = host.substring(0, dotInd).toLowerCase();\r\n domain = host.substring(dotInd + 1);\r\n // Normalize namespaces to lowercase to share storage / connection.\r\n namespace = subdomain;\r\n }\r\n // Always treat the value of the `ns` as the namespace name if it is present.\r\n if ('ns' in queryParams) {\r\n namespace = queryParams['ns'];\r\n }\r\n }\r\n return {\r\n host,\r\n port,\r\n domain,\r\n subdomain,\r\n secure,\r\n scheme,\r\n pathString,\r\n namespace\r\n };\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Encapsulates the data needed to raise an event\r\n */\r\nclass DataEvent {\r\n /**\r\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\r\n * @param eventRegistration - The function to call to with the event data. User provided\r\n * @param snapshot - The data backing the event\r\n * @param prevName - Optional, the name of the previous child for child_* events.\r\n */\r\n constructor(eventType, eventRegistration, snapshot, prevName) {\r\n this.eventType = eventType;\r\n this.eventRegistration = eventRegistration;\r\n this.snapshot = snapshot;\r\n this.prevName = prevName;\r\n }\r\n getPath() {\r\n const ref = this.snapshot.ref;\r\n if (this.eventType === 'value') {\r\n return ref._path;\r\n }\r\n else {\r\n return ref.parent._path;\r\n }\r\n }\r\n getEventType() {\r\n return this.eventType;\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return (this.getPath().toString() +\r\n ':' +\r\n this.eventType +\r\n ':' +\r\n stringify(this.snapshot.exportVal()));\r\n }\r\n}\r\nclass CancelEvent {\r\n constructor(eventRegistration, error, path) {\r\n this.eventRegistration = eventRegistration;\r\n this.error = error;\r\n this.path = path;\r\n }\r\n getPath() {\r\n return this.path;\r\n }\r\n getEventType() {\r\n return 'cancel';\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return this.path.toString() + ':cancel';\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A wrapper class that converts events from the database@exp SDK to the legacy\r\n * Database SDK. Events are not converted directly as event registration relies\r\n * on reference comparison of the original user callback (see `matches()`) and\r\n * relies on equality of the legacy SDK's `context` object.\r\n */\r\nclass CallbackContext {\r\n constructor(snapshotCallback, cancelCallback) {\r\n this.snapshotCallback = snapshotCallback;\r\n this.cancelCallback = cancelCallback;\r\n }\r\n onValue(expDataSnapshot, previousChildName) {\r\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\r\n }\r\n onCancel(error) {\r\n assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\r\n return this.cancelCallback.call(null, error);\r\n }\r\n get hasCancelCallback() {\r\n return !!this.cancelCallback;\r\n }\r\n matches(other) {\r\n return (this.snapshotCallback === other.snapshotCallback ||\r\n (this.snapshotCallback.userCallback !== undefined &&\r\n this.snapshotCallback.userCallback ===\r\n other.snapshotCallback.userCallback &&\r\n this.snapshotCallback.context === other.snapshotCallback.context));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The `onDisconnect` class allows you to write or clear data when your client\r\n * disconnects from the Database server. These updates occur whether your\r\n * client disconnects cleanly or not, so you can rely on them to clean up data\r\n * even if a connection is dropped or a client crashes.\r\n *\r\n * The `onDisconnect` class is most commonly used to manage presence in\r\n * applications where it is useful to detect how many clients are connected and\r\n * when other clients disconnect. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * To avoid problems when a connection is dropped before the requests can be\r\n * transferred to the Database server, these functions should be called before\r\n * writing any data.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time you reconnect.\r\n */\r\nclass OnDisconnect {\r\n /** @hideconstructor */\r\n constructor(_repo, _path) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n }\r\n /**\r\n * Cancels all previously queued `onDisconnect()` set or update events for this\r\n * location and all children.\r\n *\r\n * If a write has been queued for this location via a `set()` or `update()` at a\r\n * parent location, the write at this location will be canceled, though writes\r\n * to sibling locations will still occur.\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n cancel() {\r\n const deferred = new Deferred();\r\n repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is deleted when the client is disconnected\r\n * (due to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n remove() {\r\n validateWritablePath('OnDisconnect.remove', this._path);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value when the\r\n * client is disconnected (due to closing the browser, navigating to a new page,\r\n * or network issues).\r\n *\r\n * `set()` is especially useful for implementing \"presence\" systems, where a\r\n * value should be changed or cleared when a user disconnects so that they\r\n * appear \"offline\" to other users. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time.\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n set(value) {\r\n validateWritablePath('OnDisconnect.set', this._path);\r\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value and priority\r\n * when the client is disconnected (due to closing the browser, navigating to a\r\n * new page, or network issues).\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n setWithPriority(value, priority) {\r\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\r\n validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\r\n validatePriority('OnDisconnect.setWithPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Writes multiple values at this location when the client is disconnected (due\r\n * to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\r\n * from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n update(values) {\r\n validateWritablePath('OnDisconnect.update', this._path);\r\n validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nclass QueryImpl {\r\n /**\r\n * @hideconstructor\r\n */\r\n constructor(_repo, _path, _queryParams, _orderByCalled) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n this._queryParams = _queryParams;\r\n this._orderByCalled = _orderByCalled;\r\n }\r\n get key() {\r\n if (pathIsEmpty(this._path)) {\r\n return null;\r\n }\r\n else {\r\n return pathGetBack(this._path);\r\n }\r\n }\r\n get ref() {\r\n return new ReferenceImpl(this._repo, this._path);\r\n }\r\n get _queryIdentifier() {\r\n const obj = queryParamsGetQueryObject(this._queryParams);\r\n const id = ObjectToUniqueKey(obj);\r\n return id === '{}' ? 'default' : id;\r\n }\r\n /**\r\n * An object representation of the query parameters used by this Query.\r\n */\r\n get _queryObject() {\r\n return queryParamsGetQueryObject(this._queryParams);\r\n }\r\n isEqual(other) {\r\n other = getModularInstance(other);\r\n if (!(other instanceof QueryImpl)) {\r\n return false;\r\n }\r\n const sameRepo = this._repo === other._repo;\r\n const samePath = pathEquals(this._path, other._path);\r\n const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\r\n return sameRepo && samePath && sameQueryIdentifier;\r\n }\r\n toJSON() {\r\n return this.toString();\r\n }\r\n toString() {\r\n return this._repo.toString() + pathToUrlEncodedString(this._path);\r\n }\r\n}\r\n/**\r\n * Validates that no other order by call has been made\r\n */\r\nfunction validateNoPreviousOrderByCall(query, fnName) {\r\n if (query._orderByCalled === true) {\r\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\r\n }\r\n}\r\n/**\r\n * Validates start/end values for queries.\r\n */\r\nfunction validateQueryEndpoints(params) {\r\n let startNode = null;\r\n let endNode = null;\r\n if (params.hasStart()) {\r\n startNode = params.getIndexStartValue();\r\n }\r\n if (params.hasEnd()) {\r\n endNode = params.getIndexEndValue();\r\n }\r\n if (params.getIndex() === KEY_INDEX) {\r\n const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\r\n 'startAt(), endAt(), or equalTo().';\r\n const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\r\n 'endAt(), endBefore(), or equalTo() must be a string.';\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n if (startName !== MIN_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof startNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n if (endName !== MAX_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof endNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n }\r\n else if (params.getIndex() === PRIORITY_INDEX) {\r\n if ((startNode != null && !isValidPriority(startNode)) ||\r\n (endNode != null && !isValidPriority(endNode))) {\r\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\r\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\r\n '(null, a number, or a string).');\r\n }\r\n }\r\n else {\r\n assert(params.getIndex() instanceof PathIndex ||\r\n params.getIndex() === VALUE_INDEX, 'unknown index type.');\r\n if ((startNode != null && typeof startNode === 'object') ||\r\n (endNode != null && typeof endNode === 'object')) {\r\n throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\r\n 'equalTo() cannot be an object.');\r\n }\r\n }\r\n}\r\n/**\r\n * Validates that limit* has been called with the correct combination of parameters\r\n */\r\nfunction validateLimit(params) {\r\n if (params.hasStart() &&\r\n params.hasEnd() &&\r\n params.hasLimit() &&\r\n !params.hasAnchoredLimit()) {\r\n throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\r\n 'limitToFirst() or limitToLast() instead.');\r\n }\r\n}\r\n/**\r\n * @internal\r\n */\r\nclass ReferenceImpl extends QueryImpl {\r\n /** @hideconstructor */\r\n constructor(repo, path) {\r\n super(repo, path, new QueryParams(), false);\r\n }\r\n get parent() {\r\n const parentPath = pathParent(this._path);\r\n return parentPath === null\r\n ? null\r\n : new ReferenceImpl(this._repo, parentPath);\r\n }\r\n get root() {\r\n let ref = this;\r\n while (ref.parent !== null) {\r\n ref = ref.parent;\r\n }\r\n return ref;\r\n }\r\n}\r\n/**\r\n * A `DataSnapshot` contains data from a Database location.\r\n *\r\n * Any time you read data from the Database, you receive the data as a\r\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\r\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\r\n * JavaScript object by calling the `val()` method. Alternatively, you can\r\n * traverse into the snapshot by calling `child()` to return child snapshots\r\n * (which you could then call `val()` on).\r\n *\r\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\r\n * a Database location. It cannot be modified and will never change (to modify\r\n * data, you always call the `set()` method on a `Reference` directly).\r\n */\r\nclass DataSnapshot {\r\n /**\r\n * @param _node - A SnapshotNode to wrap.\r\n * @param ref - The location this snapshot came from.\r\n * @param _index - The iteration order for this snapshot\r\n * @hideconstructor\r\n */\r\n constructor(_node, \r\n /**\r\n * The location of this DataSnapshot.\r\n */\r\n ref, _index) {\r\n this._node = _node;\r\n this.ref = ref;\r\n this._index = _index;\r\n }\r\n /**\r\n * Gets the priority value of the data in this `DataSnapshot`.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\r\n * ).\r\n */\r\n get priority() {\r\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\r\n return this._node.getPriority().val();\r\n }\r\n /**\r\n * The key (last part of the path) of the location of this `DataSnapshot`.\r\n *\r\n * The last token in a Database location is considered its key. For example,\r\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\r\n * `DataSnapshot` will return the key for the location that generated it.\r\n * However, accessing the key on the root URL of a Database will return\r\n * `null`.\r\n */\r\n get key() {\r\n return this.ref.key;\r\n }\r\n /** Returns the number of child properties of this `DataSnapshot`. */\r\n get size() {\r\n return this._node.numChildren();\r\n }\r\n /**\r\n * Gets another `DataSnapshot` for the location at the specified relative path.\r\n *\r\n * Passing a relative path to the `child()` method of a DataSnapshot returns\r\n * another `DataSnapshot` for the location at the specified relative path. The\r\n * relative path can either be a simple child name (for example, \"ada\") or a\r\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\r\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\r\n * whose value is `null`) is returned.\r\n *\r\n * @param path - A relative path to the location of child data.\r\n */\r\n child(path) {\r\n const childPath = new Path(path);\r\n const childRef = child(this.ref, path);\r\n return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\r\n }\r\n /**\r\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\r\n * efficient than using `snapshot.val() !== null`.\r\n */\r\n exists() {\r\n return !this._node.isEmpty();\r\n }\r\n /**\r\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\r\n *\r\n * The `exportVal()` method is similar to `val()`, except priority information\r\n * is included (if available), making it suitable for backing up your data.\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n exportVal() {\r\n return this._node.val(true);\r\n }\r\n /**\r\n * Enumerates the top-level children in the `DataSnapshot`.\r\n *\r\n * Because of the way JavaScript objects work, the ordering of data in the\r\n * JavaScript object returned by `val()` is not guaranteed to match the\r\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\r\n * where `forEach()` comes in handy. It guarantees the children of a\r\n * `DataSnapshot` will be iterated in their query order.\r\n *\r\n * If no explicit `orderBy*()` method is used, results are returned\r\n * ordered by key (unless priorities are used, in which case, results are\r\n * returned by priority).\r\n *\r\n * @param action - A function that will be called for each child DataSnapshot.\r\n * The callback can return true to cancel further enumeration.\r\n * @returns true if enumeration was canceled due to your callback returning\r\n * true.\r\n */\r\n forEach(action) {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n const childrenNode = this._node;\r\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\r\n return !!childrenNode.forEachChild(this._index, (key, node) => {\r\n return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\r\n });\r\n }\r\n /**\r\n * Returns true if the specified child path has (non-null) data.\r\n *\r\n * @param path - A relative path to the location of a potential child.\r\n * @returns `true` if data exists at the specified child path; else\r\n * `false`.\r\n */\r\n hasChild(path) {\r\n const childPath = new Path(path);\r\n return !this._node.getChild(childPath).isEmpty();\r\n }\r\n /**\r\n * Returns whether or not the `DataSnapshot` has any non-`null` child\r\n * properties.\r\n *\r\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\r\n * children. If it does, you can enumerate them using `forEach()`. If it\r\n * doesn't, then either this snapshot contains a primitive value (which can be\r\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\r\n * `null`).\r\n *\r\n * @returns true if this snapshot has any children; else false.\r\n */\r\n hasChildren() {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n return !this._node.isEmpty();\r\n }\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return this.exportVal();\r\n }\r\n /**\r\n * Extracts a JavaScript value from a `DataSnapshot`.\r\n *\r\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\r\n * scalar type (string, number, or boolean), an array, or an object. It may\r\n * also return null, indicating that the `DataSnapshot` is empty (contains no\r\n * data).\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n val() {\r\n return this._node.val();\r\n }\r\n}\r\n/**\r\n *\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided path. If no path is provided, the `Reference`\r\n * will point to the root of the Database.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param path - Optional path representing the location the returned\r\n * `Reference` will point. If not provided, the returned `Reference` will\r\n * point to the root of the Database.\r\n * @returns If a path is provided, a `Reference`\r\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\r\n * root of the Database.\r\n */\r\nfunction ref(db, path) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('ref');\r\n return path !== undefined ? child(db._root, path) : db._root;\r\n}\r\n/**\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided Firebase URL.\r\n *\r\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\r\n * has a different domain than the current `Database` instance.\r\n *\r\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\r\n * and are not applied to the returned `Reference`.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param url - The Firebase URL at which the returned `Reference` will\r\n * point.\r\n * @returns A `Reference` pointing to the provided\r\n * Firebase URL.\r\n */\r\nfunction refFromURL(db, url) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('refFromURL');\r\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\r\n validateUrl('refFromURL', parsedURL);\r\n const repoInfo = parsedURL.repoInfo;\r\n if (!db._repo.repoInfo_.isCustomHost() &&\r\n repoInfo.host !== db._repo.repoInfo_.host) {\r\n fatal('refFromURL' +\r\n ': Host name does not match the current database: ' +\r\n '(found ' +\r\n repoInfo.host +\r\n ' but expected ' +\r\n db._repo.repoInfo_.host +\r\n ')');\r\n }\r\n return ref(db, parsedURL.path.toString());\r\n}\r\n/**\r\n * Gets a `Reference` for the location at the specified relative path.\r\n *\r\n * The relative path can either be a simple child name (for example, \"ada\") or\r\n * a deeper slash-separated path (for example, \"ada/name/first\").\r\n *\r\n * @param parent - The parent location.\r\n * @param path - A relative path from this location to the desired child\r\n * location.\r\n * @returns The specified child location.\r\n */\r\nfunction child(parent, path) {\r\n parent = getModularInstance(parent);\r\n if (pathGetFront(parent._path) === null) {\r\n validateRootPathString('child', 'path', path, false);\r\n }\r\n else {\r\n validatePathString('child', 'path', path, false);\r\n }\r\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\r\n}\r\n/**\r\n * Returns an `OnDisconnect` object - see\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information on how to use it.\r\n *\r\n * @param ref - The reference to add OnDisconnect triggers for.\r\n */\r\nfunction onDisconnect(ref) {\r\n ref = getModularInstance(ref);\r\n return new OnDisconnect(ref._repo, ref._path);\r\n}\r\n/**\r\n * Generates a new child location using a unique key and returns its\r\n * `Reference`.\r\n *\r\n * This is the most common pattern for adding data to a collection of items.\r\n *\r\n * If you provide a value to `push()`, the value is written to the\r\n * generated location. If you don't pass a value, nothing is written to the\r\n * database and the child remains empty (but you can use the `Reference`\r\n * elsewhere).\r\n *\r\n * The unique keys generated by `push()` are ordered by the current time, so the\r\n * resulting list of items is chronologically sorted. The keys are also\r\n * designed to be unguessable (they contain 72 random bits of entropy).\r\n *\r\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}\r\n *
See {@link ttps://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}\r\n *\r\n * @param parent - The parent location.\r\n * @param value - Optional value to be written at the generated location.\r\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\r\n * but can be used immediately as the `Reference` to the child location.\r\n */\r\nfunction push(parent, value) {\r\n parent = getModularInstance(parent);\r\n validateWritablePath('push', parent._path);\r\n validateFirebaseDataArg('push', value, parent._path, true);\r\n const now = repoServerTime(parent._repo);\r\n const name = nextPushId(now);\r\n // push() returns a ThennableReference whose promise is fulfilled with a\r\n // regular Reference. We use child() to create handles to two different\r\n // references. The first is turned into a ThennableReference below by adding\r\n // then() and catch() methods and is used as the return value of push(). The\r\n // second remains a regular Reference and is used as the fulfilled value of\r\n // the first ThennableReference.\r\n const thennablePushRef = child(parent, name);\r\n const pushRef = child(parent, name);\r\n let promise;\r\n if (value != null) {\r\n promise = set(pushRef, value).then(() => pushRef);\r\n }\r\n else {\r\n promise = Promise.resolve(pushRef);\r\n }\r\n thennablePushRef.then = promise.then.bind(promise);\r\n thennablePushRef.catch = promise.then.bind(promise, undefined);\r\n return thennablePushRef;\r\n}\r\n/**\r\n * Removes the data at this Database location.\r\n *\r\n * Any data at child locations will also be deleted.\r\n *\r\n * The effect of the remove will be visible immediately and the corresponding\r\n * event 'value' will be triggered. Synchronization of the remove to the\r\n * Firebase servers will also be started, and the returned Promise will resolve\r\n * when complete. If provided, the onComplete callback will be called\r\n * asynchronously after synchronization has finished.\r\n *\r\n * @param ref - The location to remove.\r\n * @returns Resolves when remove on server is complete.\r\n */\r\nfunction remove(ref) {\r\n validateWritablePath('remove', ref._path);\r\n return set(ref, null);\r\n}\r\n/**\r\n * Writes data to this Database location.\r\n *\r\n * This will overwrite any data at this location and all child locations.\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\r\n * all data at this location and all child locations will be deleted.\r\n *\r\n * `set()` will remove any priority stored at this location, so if priority is\r\n * meant to be preserved, you need to use `setWithPriority()` instead.\r\n *\r\n * Note that modifying data with `set()` will cancel any pending transactions\r\n * at that location, so extreme care should be taken if mixing `set()` and\r\n * `transaction()` to modify the same data.\r\n *\r\n * A single `set()` will generate a single \"value\" event at the location where\r\n * the `set()` was performed.\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction set(ref, value) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('set', ref._path);\r\n validateFirebaseDataArg('set', value, ref._path, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, \r\n /*priority=*/ null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Sets a priority for the data at this Database location.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setPriority(ref, priority) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('setPriority', ref._path);\r\n validatePriority('setPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes data the Database location. Like `set()` but also specifies the\r\n * priority for that data.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setWithPriority(ref, value, priority) {\r\n validateWritablePath('setWithPriority', ref._path);\r\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\r\n validatePriority('setWithPriority', priority, false);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\r\n }\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes multiple values to the Database at once.\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example,\r\n * \"name/first\") from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * A single `update()` will generate a single \"value\" event at the location\r\n * where the `update()` was performed, regardless of how many children were\r\n * modified.\r\n *\r\n * Note that modifying data with `update()` will cancel any pending\r\n * transactions at that location, so extreme care should be taken if mixing\r\n * `update()` and `transaction()` to modify the same data.\r\n *\r\n * Passing `null` to `update()` will remove the data at this location.\r\n *\r\n * See\r\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\r\n *\r\n * @param ref - The location to write to.\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when update on server is complete.\r\n */\r\nfunction update(ref, values) {\r\n validateFirebaseMergeDataArg('update', values, ref._path, false);\r\n const deferred = new Deferred();\r\n repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Gets the most up-to-date result for this query.\r\n *\r\n * @param query - The query to run.\r\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\r\n * available, or rejects if the client is unable to return a value (e.g., if the\r\n * server is unreachable and there is nothing cached).\r\n */\r\nfunction get(query) {\r\n query = getModularInstance(query);\r\n return repoGetValue(query._repo, query).then(node => {\r\n return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\r\n });\r\n}\r\n/**\r\n * Represents registration for 'value' events.\r\n */\r\nclass ValueEventRegistration {\r\n constructor(callbackContext) {\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n return eventType === 'value';\r\n }\r\n createEvent(change, query) {\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, null);\r\n }\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n matches(other) {\r\n if (!(other instanceof ValueEventRegistration)) {\r\n return false;\r\n }\r\n else if (!other.callbackContext || !this.callbackContext) {\r\n // If no callback specified, we consider it to match any callback.\r\n return true;\r\n }\r\n else {\r\n return other.callbackContext.matches(this.callbackContext);\r\n }\r\n }\r\n hasAnyCallback() {\r\n return this.callbackContext !== null;\r\n }\r\n}\r\n/**\r\n * Represents the registration of a child_x event.\r\n */\r\nclass ChildEventRegistration {\r\n constructor(eventType, callbackContext) {\r\n this.eventType = eventType;\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\r\n eventToCheck =\r\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\r\n return this.eventType === eventToCheck;\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n createEvent(change, query) {\r\n assert(change.childName != null, 'Child events should have a childName.');\r\n const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\r\n }\r\n }\r\n matches(other) {\r\n if (other instanceof ChildEventRegistration) {\r\n return (this.eventType === other.eventType &&\r\n (!this.callbackContext ||\r\n !other.callbackContext ||\r\n this.callbackContext.matches(other.callbackContext)));\r\n }\r\n return false;\r\n }\r\n hasAnyCallback() {\r\n return !!this.callbackContext;\r\n }\r\n}\r\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\r\n let cancelCallback;\r\n if (typeof cancelCallbackOrListenOptions === 'object') {\r\n cancelCallback = undefined;\r\n options = cancelCallbackOrListenOptions;\r\n }\r\n if (typeof cancelCallbackOrListenOptions === 'function') {\r\n cancelCallback = cancelCallbackOrListenOptions;\r\n }\r\n if (options && options.onlyOnce) {\r\n const userCallback = callback;\r\n const onceCallback = (dataSnapshot, previousChildName) => {\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n userCallback(dataSnapshot, previousChildName);\r\n };\r\n onceCallback.userCallback = callback.userCallback;\r\n onceCallback.context = callback.context;\r\n callback = onceCallback;\r\n }\r\n const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\r\n const container = eventType === 'value'\r\n ? new ValueEventRegistration(callbackContext)\r\n : new ChildEventRegistration(eventType, callbackContext);\r\n repoAddEventCallbackForQuery(query._repo, query, container);\r\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\n/**\r\n * Detaches a callback previously attached with `on()`.\r\n *\r\n * Detach a callback previously attached with `on()`. Note that if `on()` was\r\n * called multiple times with the same eventType and callback, the callback\r\n * will be called multiple times for each event, and `off()` must be called\r\n * multiple times to remove the callback. Calling `off()` on a parent listener\r\n * will not automatically remove listeners registered on child nodes, `off()`\r\n * must also be called on any child listeners to remove the callback.\r\n *\r\n * If a callback is not specified, all callbacks for the specified eventType\r\n * will be removed. Similarly, if no eventType is specified, all callbacks\r\n * for the `Reference` will be removed.\r\n *\r\n * Individual listeners can also be removed by invoking their unsubscribe\r\n * callbacks.\r\n *\r\n * @param query - The query that the listener was registered with.\r\n * @param eventType - One of the following strings: \"value\", \"child_added\",\r\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\r\n * for the `Reference` will be removed.\r\n * @param callback - The callback function that was passed to `on()` or\r\n * `undefined` to remove all callbacks.\r\n */\r\nfunction off(query, eventType, callback) {\r\n let container = null;\r\n const expCallback = callback ? new CallbackContext(callback) : null;\r\n if (eventType === 'value') {\r\n container = new ValueEventRegistration(expCallback);\r\n }\r\n else if (eventType) {\r\n container = new ChildEventRegistration(eventType, expCallback);\r\n }\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\n/**\r\n * A `QueryConstraint` is used to narrow the set of documents returned by a\r\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\r\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\r\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\r\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\r\n * {@link orderByValue} or {@link equalTo} and\r\n * can then be passed to {@link query} to create a new query instance that\r\n * also contains this `QueryConstraint`.\r\n */\r\nclass QueryConstraint {\r\n}\r\nclass QueryEndAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endAt', this._value, query._path, true);\r\n const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endAt: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name less than or equal\r\n * to the specified key.\r\n *\r\n * You can read more about `endAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to end at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end at, among the children with the previously\r\n * specified priority. This argument is only allowed if ordering by child,\r\n * value, or priority.\r\n */\r\nfunction endAt(value, key) {\r\n validateKey('endAt', 'key', key, true);\r\n return new QueryEndAtConstraint(value, key);\r\n}\r\nclass QueryEndBeforeConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\r\n const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is exclusive. If only a value is provided, children\r\n * with a value less than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value lesss than or equal\r\n * to the specified value and a a key name less than the specified key.\r\n *\r\n * @param value - The value to end before. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end before, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction endBefore(value, key) {\r\n validateKey('endBefore', 'key', key, true);\r\n return new QueryEndBeforeConstraint(value, key);\r\n}\r\nclass QueryStartAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAt', this._value, query._path, true);\r\n const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAt: Starting point was already set (by another call to startAt, ' +\r\n 'startBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name greater than or\r\n * equal to the specified key.\r\n *\r\n * You can read more about `startAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to start at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAt(value = null, key) {\r\n validateKey('startAt', 'key', key, true);\r\n return new QueryStartAtConstraint(value, key);\r\n}\r\nclass QueryStartAfterConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\r\n const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +\r\n 'startAfter, or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is exclusive. If only a value is provided, children\r\n * with a value greater than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value greater than or equal\r\n * to the specified value and a a key name greater than the specified key.\r\n *\r\n * @param value - The value to start after. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start after. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAfter(value, key) {\r\n validateKey('startAfter', 'key', key, true);\r\n return new QueryStartAfterConstraint(value, key);\r\n}\r\nclass QueryLimitToFirstConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that if limited to the first specific number\r\n * of children.\r\n *\r\n * The `limitToFirst()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the first 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToFirst()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToFirst(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToFirst: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToFirstConstraint(limit);\r\n}\r\nclass QueryLimitToLastConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that is limited to return only the last\r\n * specified number of children.\r\n *\r\n * The `limitToLast()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the last 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToLast()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToLast(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToLast: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToLastConstraint(limit);\r\n}\r\nclass QueryOrderByChildConstraint extends QueryConstraint {\r\n constructor(_path) {\r\n super();\r\n this._path = _path;\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByChild');\r\n const parsedPath = new Path(this._path);\r\n if (pathIsEmpty(parsedPath)) {\r\n throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\r\n }\r\n const index = new PathIndex(parsedPath);\r\n const newParams = queryParamsOrderBy(query._queryParams, index);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the specified child key.\r\n *\r\n * Queries can only order by one key at a time. Calling `orderByChild()`\r\n * multiple times on the same query is an error.\r\n *\r\n * Firebase queries allow you to order your data by any child key on the fly.\r\n * However, if you know in advance what your indexes will be, you can define\r\n * them via the .indexOn rule in your Security Rules for better performance. See\r\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\r\n * rule for more information.\r\n *\r\n * You can read more about `orderByChild()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n *\r\n * @param path - The path to order by.\r\n */\r\nfunction orderByChild(path) {\r\n if (path === '$key') {\r\n throw new Error('orderByChild: \"$key\" is invalid. Use orderByKey() instead.');\r\n }\r\n else if (path === '$priority') {\r\n throw new Error('orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.');\r\n }\r\n else if (path === '$value') {\r\n throw new Error('orderByChild: \"$value\" is invalid. Use orderByValue() instead.');\r\n }\r\n validatePathString('orderByChild', 'path', path, false);\r\n return new QueryOrderByChildConstraint(path);\r\n}\r\nclass QueryOrderByKeyConstraint extends QueryConstraint {\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByKey');\r\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the key.\r\n *\r\n * Sorts the results of a query by their (ascending) key values.\r\n *\r\n * You can read more about `orderByKey()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByKey() {\r\n return new QueryOrderByKeyConstraint();\r\n}\r\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByPriority');\r\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by priority.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\r\n * for alternatives to priority.\r\n */\r\nfunction orderByPriority() {\r\n return new QueryOrderByPriorityConstraint();\r\n}\r\nclass QueryOrderByValueConstraint extends QueryConstraint {\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByValue');\r\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by value.\r\n *\r\n * If the children of a query are all scalar values (string, number, or\r\n * boolean), you can order the results by their (ascending) values.\r\n *\r\n * You can read more about `orderByValue()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByValue() {\r\n return new QueryOrderByValueConstraint();\r\n}\r\nclass QueryEqualToValueConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\r\n 'equalTo).');\r\n }\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\r\n 'equalTo).');\r\n }\r\n return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` that includes children that match the specified\r\n * value.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The optional key argument can be used to further limit the range of the\r\n * query. If it is specified, then children that have exactly the specified\r\n * value must also have exactly the specified key as their key name. This can be\r\n * used to filter result sets with many matches for the same value.\r\n *\r\n * You can read more about `equalTo()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to match for. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction equalTo(value, key) {\r\n validateKey('equalTo', 'key', key, true);\r\n return new QueryEqualToValueConstraint(value, key);\r\n}\r\n/**\r\n * Creates a new immutable instance of `Query` that is extended to also include\r\n * additional query constraints.\r\n *\r\n * @param query - The Query instance to use as a base for the new constraints.\r\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\r\n * @throws if any of the provided query constraints cannot be combined with the\r\n * existing or new constraints.\r\n */\r\nfunction query(query, ...queryConstraints) {\r\n let queryImpl = getModularInstance(query);\r\n for (const constraint of queryConstraints) {\r\n queryImpl = constraint._apply(queryImpl);\r\n }\r\n return queryImpl;\r\n}\r\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\r\nsyncPointSetReferenceConstructor(ReferenceImpl);\r\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This variable is also defined in the firebase Node.js Admin SDK. Before\r\n * modifying this definition, consult the definition in:\r\n *\r\n * https://github.com/firebase/firebase-admin-node\r\n *\r\n * and make sure the two are consistent.\r\n */\r\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\r\n/**\r\n * Creates and caches `Repo` instances.\r\n */\r\nconst repos = {};\r\n/**\r\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\r\n */\r\nlet useRestClient = false;\r\n/**\r\n * Update an existing `Repo` in place to point to a new host/port.\r\n */\r\nfunction repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {\r\n repo.repoInfo_ = new RepoInfo(`${host}:${port}`, \r\n /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);\r\n if (tokenProvider) {\r\n repo.authTokenProvider_ = tokenProvider;\r\n }\r\n}\r\n/**\r\n * This function should only ever be called to CREATE a new database instance.\r\n * @internal\r\n */\r\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\r\n let dbUrl = url || app.options.databaseURL;\r\n if (dbUrl === undefined) {\r\n if (!app.options.projectId) {\r\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\r\n ' a Project ID when calling firebase.initializeApp().');\r\n }\r\n log('Using default host for project ', app.options.projectId);\r\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\r\n }\r\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n let repoInfo = parsedUrl.repoInfo;\r\n let isEmulator;\r\n let dbEmulatorHost = undefined;\r\n if (typeof process !== 'undefined') {\r\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\r\n }\r\n if (dbEmulatorHost) {\r\n isEmulator = true;\r\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\r\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n repoInfo = parsedUrl.repoInfo;\r\n }\r\n else {\r\n isEmulator = !parsedUrl.repoInfo.secure;\r\n }\r\n const authTokenProvider = nodeAdmin && isEmulator\r\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\r\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\r\n validateUrl('Invalid Firebase Database URL', parsedUrl);\r\n if (!pathIsEmpty(parsedUrl.path)) {\r\n fatal('Database URL must point to the root of a Firebase Database ' +\r\n '(not including a child path).');\r\n }\r\n const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));\r\n return new Database(repo, app);\r\n}\r\n/**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n */\r\nfunction repoManagerDeleteRepo(repo, appName) {\r\n const appRepos = repos[appName];\r\n // This should never happen...\r\n if (!appRepos || appRepos[repo.key] !== repo) {\r\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\r\n }\r\n repoInterrupt(repo);\r\n delete appRepos[repo.key];\r\n}\r\n/**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param repoInfo - The metadata about the Repo\r\n * @returns The Repo object for the specified server / repoName.\r\n */\r\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\r\n let appRepos = repos[app.name];\r\n if (!appRepos) {\r\n appRepos = {};\r\n repos[app.name] = appRepos;\r\n }\r\n let repo = appRepos[repoInfo.toURLString()];\r\n if (repo) {\r\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\r\n }\r\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\r\n appRepos[repoInfo.toURLString()] = repo;\r\n return repo;\r\n}\r\n/**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n */\r\nfunction repoManagerForceRestClient(forceRestClient) {\r\n useRestClient = forceRestClient;\r\n}\r\n/**\r\n * Class representing a Firebase Realtime Database.\r\n */\r\nclass Database {\r\n /** @hideconstructor */\r\n constructor(_repoInternal, \r\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\r\n app) {\r\n this._repoInternal = _repoInternal;\r\n this.app = app;\r\n /** Represents a `Database` instance. */\r\n this['type'] = 'database';\r\n /** Track if the instance has been used (root or repo accessed) */\r\n this._instanceStarted = false;\r\n }\r\n get _repo() {\r\n if (!this._instanceStarted) {\r\n repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\r\n this._instanceStarted = true;\r\n }\r\n return this._repoInternal;\r\n }\r\n get _root() {\r\n if (!this._rootInternal) {\r\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\r\n }\r\n return this._rootInternal;\r\n }\r\n _delete() {\r\n if (this._rootInternal !== null) {\r\n repoManagerDeleteRepo(this._repo, this.app.name);\r\n this._repoInternal = null;\r\n this._rootInternal = null;\r\n }\r\n return Promise.resolve();\r\n }\r\n _checkNotDeleted(apiName) {\r\n if (this._rootInternal === null) {\r\n fatal('Cannot call ' + apiName + ' on a deleted database.');\r\n }\r\n }\r\n}\r\n/**\r\n * Returns the instance of the Realtime Database SDK that is associated\r\n * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with\r\n * with default settings if no instance exists or if the existing instance uses\r\n * a custom database URL.\r\n *\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\r\n * Database instance is associated with.\r\n * @param url - The URL of the Realtime Database instance to connect to. If not\r\n * provided, the SDK connects to the default instance of the Firebase App.\r\n * @returns The `Database` instance of the provided app.\r\n */\r\nfunction getDatabase(app = getApp(), url) {\r\n return _getProvider(app, 'database').getImmediate({\r\n identifier: url\r\n });\r\n}\r\n/**\r\n * Modify the provided instance to communicate with the Realtime Database\r\n * emulator.\r\n *\r\n *

Note: This method must be called before performing any other operation.\r\n *\r\n * @param db - The instance to modify.\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 8080)\r\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\r\n */\r\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('useEmulator');\r\n if (db._instanceStarted) {\r\n fatal('Cannot call useEmulator() after instance has already been initialized.');\r\n }\r\n const repo = db._repoInternal;\r\n let tokenProvider = undefined;\r\n if (repo.repoInfo_.nodeAdmin) {\r\n if (options.mockUserToken) {\r\n fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".');\r\n }\r\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\r\n }\r\n else if (options.mockUserToken) {\r\n const token = typeof options.mockUserToken === 'string'\r\n ? options.mockUserToken\r\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\r\n tokenProvider = new EmulatorTokenProvider(token);\r\n }\r\n // Modify the repo to apply emulator settings\r\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\r\n}\r\n/**\r\n * Disconnects from the server (all Database operations will be completed\r\n * offline).\r\n *\r\n * The client automatically maintains a persistent connection to the Database\r\n * server, which will remain active indefinitely and reconnect when\r\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\r\n * to control the client connection in cases where a persistent connection is\r\n * undesirable.\r\n *\r\n * While offline, the client will no longer receive data updates from the\r\n * Database. However, all Database operations performed locally will continue to\r\n * immediately fire events, allowing your application to continue behaving\r\n * normally. Additionally, each operation performed locally will automatically\r\n * be queued and retried upon reconnection to the Database server.\r\n *\r\n * To reconnect to the Database and begin receiving remote events, see\r\n * `goOnline()`.\r\n *\r\n * @param db - The instance to disconnect.\r\n */\r\nfunction goOffline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOffline');\r\n repoInterrupt(db._repo);\r\n}\r\n/**\r\n * Reconnects to the server and synchronizes the offline Database state\r\n * with the server state.\r\n *\r\n * This method should be used after disabling the active connection with\r\n * `goOffline()`. Once reconnected, the client will transmit the proper data\r\n * and fire the appropriate events so that your client \"catches up\"\r\n * automatically.\r\n *\r\n * @param db - The instance to reconnect.\r\n */\r\nfunction goOnline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOnline');\r\n repoResume(db._repo);\r\n}\r\nfunction enableLogging(logger, persistent) {\r\n enableLogging$1(logger, persistent);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerDatabase(variant) {\r\n setSDKVersion(SDK_VERSION$1);\r\n _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const authProvider = container.getProvider('auth-internal');\r\n const appCheckProvider = container.getProvider('app-check-internal');\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);\r\n }, \"PUBLIC\" /* PUBLIC */).setMultipleInstances(true));\r\n registerVersion(name, version, variant);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SERVER_TIMESTAMP = {\r\n '.sv': 'timestamp'\r\n};\r\n/**\r\n * Returns a placeholder value for auto-populating the current timestamp (time\r\n * since the Unix epoch, in milliseconds) as determined by the Firebase\r\n * servers.\r\n */\r\nfunction serverTimestamp() {\r\n return SERVER_TIMESTAMP;\r\n}\r\n/**\r\n * Returns a placeholder value that can be used to atomically increment the\r\n * current database value by the provided delta.\r\n *\r\n * @param delta - the amount to modify the current value atomically.\r\n * @returns A placeholder value for modifying data atomically server-side.\r\n */\r\nfunction increment(delta) {\r\n return {\r\n '.sv': {\r\n 'increment': delta\r\n }\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A type for the resolve value of {@link runTransaction}.\r\n */\r\nclass TransactionResult {\r\n /** @hideconstructor */\r\n constructor(\r\n /** Whether the transaction was successfully committed. */\r\n committed, \r\n /** The resulting data snapshot. */\r\n snapshot) {\r\n this.committed = committed;\r\n this.snapshot = snapshot;\r\n }\r\n /** Returns a JSON-serializable representation of this object. */\r\n toJSON() {\r\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\r\n }\r\n}\r\n/**\r\n * Atomically modifies the data at this location.\r\n *\r\n * Atomically modify the data at this location. Unlike a normal `set()`, which\r\n * just overwrites the data regardless of its previous value, `runTransaction()` is\r\n * used to modify the existing value to a new value, ensuring there are no\r\n * conflicts with other clients writing to the same location at the same time.\r\n *\r\n * To accomplish this, you pass `runTransaction()` an update function which is\r\n * used to transform the current value into a new value. If another client\r\n * writes to the location before your new value is successfully written, your\r\n * update function will be called again with the new current value, and the\r\n * write will be retried. This will happen repeatedly until your write succeeds\r\n * without conflict or you abort the transaction by not returning a value from\r\n * your update function.\r\n *\r\n * Note: Modifying data with `set()` will cancel any pending transactions at\r\n * that location, so extreme care should be taken if mixing `set()` and\r\n * `runTransaction()` to update the same data.\r\n *\r\n * Note: When using transactions with Security and Firebase Rules in place, be\r\n * aware that a client needs `.read` access in addition to `.write` access in\r\n * order to perform a transaction. This is because the client-side nature of\r\n * transactions requires the client to read the data in order to transactionally\r\n * update it.\r\n *\r\n * @param ref - The location to atomically modify.\r\n * @param transactionUpdate - A developer-supplied function which will be passed\r\n * the current data stored at this location (as a JavaScript object). The\r\n * function should return the new value it would like written (as a JavaScript\r\n * object). If `undefined` is returned (i.e. you return with no arguments) the\r\n * transaction will be aborted and the data at this location will not be\r\n * modified.\r\n * @param options - An options object to configure transactions.\r\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\r\n * callback to handle success and failure.\r\n */\r\nfunction runTransaction(ref, \r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\ntransactionUpdate, options) {\r\n var _a;\r\n ref = getModularInstance(ref);\r\n validateWritablePath('Reference.transaction', ref._path);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');\r\n }\r\n const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;\r\n const deferred = new Deferred();\r\n const promiseComplete = (error, committed, node) => {\r\n let dataSnapshot = null;\r\n if (error) {\r\n deferred.reject(error);\r\n }\r\n else {\r\n dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\r\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\r\n }\r\n };\r\n // Add a watch to make sure we get server updates.\r\n const unwatcher = onValue(ref, () => { });\r\n repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\r\n return deferred.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\r\n this.sendRequest('q', { p: pathString }, onComplete);\r\n};\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.echo = function (data, onEcho) {\r\n this.sendRequest('echo', { d: data }, onEcho);\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst hijackHash = function (newHash) {\r\n const oldPut = PersistentConnection.prototype.put;\r\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\r\n if (hash !== undefined) {\r\n hash = newHash();\r\n }\r\n oldPut.call(this, pathString, data, onComplete, hash);\r\n };\r\n return function () {\r\n PersistentConnection.prototype.put = oldPut;\r\n };\r\n};\r\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n * @internal\r\n */\r\nconst forceRestClient = function (forceRestClient) {\r\n repoManagerForceRestClient(forceRestClient);\r\n};\n\n/**\r\n * Firebase Realtime Database\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterDatabase();\n\nexport { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };\n//# sourceMappingURL=firebase-database.js.map\n"}}},{"rowIdx":42,"cells":{"target":{"kind":"string","value":"src/svg-icons/toggle/star-half.js"},"feat_repo_name":{"kind":"string","value":"pradel/material-ui"},"text":{"kind":"string","value":"import React from 'react';\nimport pure from 'recompose/pure';\nimport SvgIcon from '../../SvgIcon';\n\nlet ToggleStarHalf = (props) => (\n \n \n \n);\nToggleStarHalf = pure(ToggleStarHalf);\nToggleStarHalf.displayName = 'ToggleStarHalf';\n\nexport default ToggleStarHalf;\n"}}},{"rowIdx":43,"cells":{"target":{"kind":"string","value":"packages/icons/src/md/av/HighQuality.js"},"feat_repo_name":{"kind":"string","value":"suitejs/suitejs"},"text":{"kind":"string","value":"import React from 'react';\nimport IconBase from '@suitejs/icon-base';\n\nfunction MdHighQuality(props) {\n return (\n \n \n \n );\n}\n\nexport default MdHighQuality;\n"}}},{"rowIdx":44,"cells":{"target":{"kind":"string","value":"src-rx/src/components/Instances/LinksDialog.js"},"feat_repo_name":{"kind":"string","value":"ioBroker/ioBroker.admin"},"text":{"kind":"string","value":"import React, { Component } from 'react';\nimport PropTypes from 'prop-types';\nimport { withStyles } from '@material-ui/core/styles';\n\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport DialogTitle from '@material-ui/core/DialogTitle';\nimport Dialog from '@material-ui/core/Dialog';\nimport ListItemAvatar from '@material-ui/core/ListItemAvatar';\nimport Avatar from '@material-ui/core/Avatar';\n\nimport Utils from '../Utils';\n\nconst styles = theme => ({\n img: {\n width: '100%',\n height: '100%',\n }\n});\n\nclass LinksDialog extends Component {\n render() {\n if (!this.props.links || !this.props.links.length) {\n return null;\n }\n const firstPort = this.props.links[0].port;\n const showPort = this.props.links.find(item => item.port !== firstPort);\n\n return

this.props.onClose()} open={true}>\n {this.props.t('Links')}\n \n {this.props.links.map(link => {\n e.stopPropagation();\n // replace IPv6 Address with [ipv6]:port\n let url = link.link;\n url = url.replace(/\\/\\/([0-9a-f]*:[0-9a-f]*:[0-9a-f]*:[0-9a-f]*:[0-9a-f]*:[0-9a-f]*)(:\\d+)?\\//i, '//[$1]$2/');\n window.open(url, this.props.instanceId);\n this.props.onClose();\n }}\n key={link.name}\n >\n \n \n {this.props.instanceId}/\n \n \n \n )}\n \n ;\n }\n}\n\nLinksDialog.propTypes = {\n links: PropTypes.array.isRequired,\n onClose: PropTypes.func.isRequired,\n t: PropTypes.func.isRequired,\n instanceId: PropTypes.string.isRequired,\n image: PropTypes.string,\n themeType: PropTypes.string,\n};\n\nexport default withStyles(styles)(LinksDialog);"}}},{"rowIdx":45,"cells":{"target":{"kind":"string","value":"ajax/libs/clappr/0.0.86/clappr.js"},"feat_repo_name":{"kind":"string","value":"jimmybyrum/cdnjs"},"text":{"kind":"string","value":"require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o 0) {\n var fn = queue.shift();\n fn();\n }\n }\n }, true);\n\n return function nextTick(fn) {\n queue.push(fn);\n window.postMessage('process-tick', '*');\n };\n }\n\n return function nextTick(fn) {\n setTimeout(fn, 0);\n };\n})();\n\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\n// TODO(shtylman)\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\n\n},{}],3:[function(require,module,exports){\n(function (process,global){\n(function(global) {\n 'use strict';\n if (global.$traceurRuntime) {\n return;\n }\n var $Object = Object;\n var $TypeError = TypeError;\n var $create = $Object.create;\n var $defineProperties = $Object.defineProperties;\n var $defineProperty = $Object.defineProperty;\n var $freeze = $Object.freeze;\n var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;\n var $getOwnPropertyNames = $Object.getOwnPropertyNames;\n var $keys = $Object.keys;\n var $hasOwnProperty = $Object.prototype.hasOwnProperty;\n var $toString = $Object.prototype.toString;\n var $preventExtensions = Object.preventExtensions;\n var $seal = Object.seal;\n var $isExtensible = Object.isExtensible;\n function nonEnum(value) {\n return {\n configurable: true,\n enumerable: false,\n value: value,\n writable: true\n };\n }\n var types = {\n void: function voidType() {},\n any: function any() {},\n string: function string() {},\n number: function number() {},\n boolean: function boolean() {}\n };\n var method = nonEnum;\n var counter = 0;\n function newUniqueString() {\n return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';\n }\n var symbolInternalProperty = newUniqueString();\n var symbolDescriptionProperty = newUniqueString();\n var symbolDataProperty = newUniqueString();\n var symbolValues = $create(null);\n var privateNames = $create(null);\n function createPrivateName() {\n var s = newUniqueString();\n privateNames[s] = true;\n return s;\n }\n function isSymbol(symbol) {\n return typeof symbol === 'object' && symbol instanceof SymbolValue;\n }\n function typeOf(v) {\n if (isSymbol(v))\n return 'symbol';\n return typeof v;\n }\n function Symbol(description) {\n var value = new SymbolValue(description);\n if (!(this instanceof Symbol))\n return value;\n throw new TypeError('Symbol cannot be new\\'ed');\n }\n $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));\n $defineProperty(Symbol.prototype, 'toString', method(function() {\n var symbolValue = this[symbolDataProperty];\n if (!getOption('symbols'))\n return symbolValue[symbolInternalProperty];\n if (!symbolValue)\n throw TypeError('Conversion from symbol to string');\n var desc = symbolValue[symbolDescriptionProperty];\n if (desc === undefined)\n desc = '';\n return 'Symbol(' + desc + ')';\n }));\n $defineProperty(Symbol.prototype, 'valueOf', method(function() {\n var symbolValue = this[symbolDataProperty];\n if (!symbolValue)\n throw TypeError('Conversion from symbol to string');\n if (!getOption('symbols'))\n return symbolValue[symbolInternalProperty];\n return symbolValue;\n }));\n function SymbolValue(description) {\n var key = newUniqueString();\n $defineProperty(this, symbolDataProperty, {value: this});\n $defineProperty(this, symbolInternalProperty, {value: key});\n $defineProperty(this, symbolDescriptionProperty, {value: description});\n freeze(this);\n symbolValues[key] = this;\n }\n $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));\n $defineProperty(SymbolValue.prototype, 'toString', {\n value: Symbol.prototype.toString,\n enumerable: false\n });\n $defineProperty(SymbolValue.prototype, 'valueOf', {\n value: Symbol.prototype.valueOf,\n enumerable: false\n });\n var hashProperty = createPrivateName();\n var hashPropertyDescriptor = {value: undefined};\n var hashObjectProperties = {\n hash: {value: undefined},\n self: {value: undefined}\n };\n var hashCounter = 0;\n function getOwnHashObject(object) {\n var hashObject = object[hashProperty];\n if (hashObject && hashObject.self === object)\n return hashObject;\n if ($isExtensible(object)) {\n hashObjectProperties.hash.value = hashCounter++;\n hashObjectProperties.self.value = object;\n hashPropertyDescriptor.value = $create(null, hashObjectProperties);\n $defineProperty(object, hashProperty, hashPropertyDescriptor);\n return hashPropertyDescriptor.value;\n }\n return undefined;\n }\n function freeze(object) {\n getOwnHashObject(object);\n return $freeze.apply(this, arguments);\n }\n function preventExtensions(object) {\n getOwnHashObject(object);\n return $preventExtensions.apply(this, arguments);\n }\n function seal(object) {\n getOwnHashObject(object);\n return $seal.apply(this, arguments);\n }\n Symbol.iterator = Symbol();\n freeze(SymbolValue.prototype);\n function toProperty(name) {\n if (isSymbol(name))\n return name[symbolInternalProperty];\n return name;\n }\n function getOwnPropertyNames(object) {\n var rv = [];\n var names = $getOwnPropertyNames(object);\n for (var i = 0; i < names.length; i++) {\n var name = names[i];\n if (!symbolValues[name] && !privateNames[name])\n rv.push(name);\n }\n return rv;\n }\n function getOwnPropertyDescriptor(object, name) {\n return $getOwnPropertyDescriptor(object, toProperty(name));\n }\n function getOwnPropertySymbols(object) {\n var rv = [];\n var names = $getOwnPropertyNames(object);\n for (var i = 0; i < names.length; i++) {\n var symbol = symbolValues[names[i]];\n if (symbol)\n rv.push(symbol);\n }\n return rv;\n }\n function hasOwnProperty(name) {\n return $hasOwnProperty.call(this, toProperty(name));\n }\n function getOption(name) {\n return global.traceur && global.traceur.options[name];\n }\n function setProperty(object, name, value) {\n var sym,\n desc;\n if (isSymbol(name)) {\n sym = name;\n name = name[symbolInternalProperty];\n }\n object[name] = value;\n if (sym && (desc = $getOwnPropertyDescriptor(object, name)))\n $defineProperty(object, name, {enumerable: false});\n return value;\n }\n function defineProperty(object, name, descriptor) {\n if (isSymbol(name)) {\n if (descriptor.enumerable) {\n descriptor = $create(descriptor, {enumerable: {value: false}});\n }\n name = name[symbolInternalProperty];\n }\n $defineProperty(object, name, descriptor);\n return object;\n }\n function polyfillObject(Object) {\n $defineProperty(Object, 'defineProperty', {value: defineProperty});\n $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});\n $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});\n $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});\n $defineProperty(Object, 'freeze', {value: freeze});\n $defineProperty(Object, 'preventExtensions', {value: preventExtensions});\n $defineProperty(Object, 'seal', {value: seal});\n Object.getOwnPropertySymbols = getOwnPropertySymbols;\n }\n function exportStar(object) {\n for (var i = 1; i < arguments.length; i++) {\n var names = $getOwnPropertyNames(arguments[i]);\n for (var j = 0; j < names.length; j++) {\n var name = names[j];\n if (privateNames[name])\n continue;\n (function(mod, name) {\n $defineProperty(object, name, {\n get: function() {\n return mod[name];\n },\n enumerable: true\n });\n })(arguments[i], names[j]);\n }\n }\n return object;\n }\n function isObject(x) {\n return x != null && (typeof x === 'object' || typeof x === 'function');\n }\n function toObject(x) {\n if (x == null)\n throw $TypeError();\n return $Object(x);\n }\n function checkObjectCoercible(argument) {\n if (argument == null) {\n throw new TypeError('Value cannot be converted to an Object');\n }\n return argument;\n }\n function setupGlobals(global) {\n global.Symbol = Symbol;\n global.Reflect = global.Reflect || {};\n global.Reflect.global = global.Reflect.global || global;\n polyfillObject(global.Object);\n }\n setupGlobals(global);\n global.$traceurRuntime = {\n createPrivateName: createPrivateName,\n exportStar: exportStar,\n getOwnHashObject: getOwnHashObject,\n privateNames: privateNames,\n setProperty: setProperty,\n setupGlobals: setupGlobals,\n toObject: toObject,\n isObject: isObject,\n toProperty: toProperty,\n type: types,\n typeof: typeOf,\n checkObjectCoercible: checkObjectCoercible,\n hasOwnProperty: function(o, p) {\n return hasOwnProperty.call(o, p);\n },\n defineProperties: $defineProperties,\n defineProperty: $defineProperty,\n getOwnPropertyDescriptor: $getOwnPropertyDescriptor,\n getOwnPropertyNames: $getOwnPropertyNames,\n keys: $keys\n };\n})(typeof global !== 'undefined' ? global : this);\n(function() {\n 'use strict';\n function spread() {\n var rv = [],\n j = 0,\n iterResult;\n for (var i = 0; i < arguments.length; i++) {\n var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]);\n if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') {\n throw new TypeError('Cannot spread non-iterable object.');\n }\n var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)]();\n while (!(iterResult = iter.next()).done) {\n rv[j++] = iterResult.value;\n }\n }\n return rv;\n }\n $traceurRuntime.spread = spread;\n})();\n(function() {\n 'use strict';\n var $Object = Object;\n var $TypeError = TypeError;\n var $create = $Object.create;\n var $defineProperties = $traceurRuntime.defineProperties;\n var $defineProperty = $traceurRuntime.defineProperty;\n var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;\n var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;\n var $getPrototypeOf = Object.getPrototypeOf;\n function superDescriptor(homeObject, name) {\n var proto = $getPrototypeOf(homeObject);\n do {\n var result = $getOwnPropertyDescriptor(proto, name);\n if (result)\n return result;\n proto = $getPrototypeOf(proto);\n } while (proto);\n return undefined;\n }\n function superCall(self, homeObject, name, args) {\n return superGet(self, homeObject, name).apply(self, args);\n }\n function superGet(self, homeObject, name) {\n var descriptor = superDescriptor(homeObject, name);\n if (descriptor) {\n if (!descriptor.get)\n return descriptor.value;\n return descriptor.get.call(self);\n }\n return undefined;\n }\n function superSet(self, homeObject, name, value) {\n var descriptor = superDescriptor(homeObject, name);\n if (descriptor && descriptor.set) {\n descriptor.set.call(self, value);\n return value;\n }\n throw $TypeError(\"super has no setter '\" + name + \"'.\");\n }\n function getDescriptors(object) {\n var descriptors = {},\n name,\n names = $getOwnPropertyNames(object);\n for (var i = 0; i < names.length; i++) {\n var name = names[i];\n descriptors[name] = $getOwnPropertyDescriptor(object, name);\n }\n return descriptors;\n }\n function createClass(ctor, object, staticObject, superClass) {\n $defineProperty(object, 'constructor', {\n value: ctor,\n configurable: true,\n enumerable: false,\n writable: true\n });\n if (arguments.length > 3) {\n if (typeof superClass === 'function')\n ctor.__proto__ = superClass;\n ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));\n } else {\n ctor.prototype = object;\n }\n $defineProperty(ctor, 'prototype', {\n configurable: false,\n writable: false\n });\n return $defineProperties(ctor, getDescriptors(staticObject));\n }\n function getProtoParent(superClass) {\n if (typeof superClass === 'function') {\n var prototype = superClass.prototype;\n if ($Object(prototype) === prototype || prototype === null)\n return superClass.prototype;\n throw new $TypeError('super prototype must be an Object or null');\n }\n if (superClass === null)\n return null;\n throw new $TypeError((\"Super expression must either be null or a function, not \" + typeof superClass + \".\"));\n }\n function defaultSuperCall(self, homeObject, args) {\n if ($getPrototypeOf(homeObject) !== null)\n superCall(self, homeObject, 'constructor', args);\n }\n $traceurRuntime.createClass = createClass;\n $traceurRuntime.defaultSuperCall = defaultSuperCall;\n $traceurRuntime.superCall = superCall;\n $traceurRuntime.superGet = superGet;\n $traceurRuntime.superSet = superSet;\n})();\n(function() {\n 'use strict';\n var createPrivateName = $traceurRuntime.createPrivateName;\n var $defineProperties = $traceurRuntime.defineProperties;\n var $defineProperty = $traceurRuntime.defineProperty;\n var $create = Object.create;\n var $TypeError = TypeError;\n function nonEnum(value) {\n return {\n configurable: true,\n enumerable: false,\n value: value,\n writable: true\n };\n }\n var ST_NEWBORN = 0;\n var ST_EXECUTING = 1;\n var ST_SUSPENDED = 2;\n var ST_CLOSED = 3;\n var END_STATE = -2;\n var RETHROW_STATE = -3;\n function getInternalError(state) {\n return new Error('Traceur compiler bug: invalid state in state machine: ' + state);\n }\n function GeneratorContext() {\n this.state = 0;\n this.GState = ST_NEWBORN;\n this.storedException = undefined;\n this.finallyFallThrough = undefined;\n this.sent_ = undefined;\n this.returnValue = undefined;\n this.tryStack_ = [];\n }\n GeneratorContext.prototype = {\n pushTry: function(catchState, finallyState) {\n if (finallyState !== null) {\n var finallyFallThrough = null;\n for (var i = this.tryStack_.length - 1; i >= 0; i--) {\n if (this.tryStack_[i].catch !== undefined) {\n finallyFallThrough = this.tryStack_[i].catch;\n break;\n }\n }\n if (finallyFallThrough === null)\n finallyFallThrough = RETHROW_STATE;\n this.tryStack_.push({\n finally: finallyState,\n finallyFallThrough: finallyFallThrough\n });\n }\n if (catchState !== null) {\n this.tryStack_.push({catch: catchState});\n }\n },\n popTry: function() {\n this.tryStack_.pop();\n },\n get sent() {\n this.maybeThrow();\n return this.sent_;\n },\n set sent(v) {\n this.sent_ = v;\n },\n get sentIgnoreThrow() {\n return this.sent_;\n },\n maybeThrow: function() {\n if (this.action === 'throw') {\n this.action = 'next';\n throw this.sent_;\n }\n },\n end: function() {\n switch (this.state) {\n case END_STATE:\n return this;\n case RETHROW_STATE:\n throw this.storedException;\n default:\n throw getInternalError(this.state);\n }\n },\n handleException: function(ex) {\n this.GState = ST_CLOSED;\n this.state = END_STATE;\n throw ex;\n }\n };\n function nextOrThrow(ctx, moveNext, action, x) {\n switch (ctx.GState) {\n case ST_EXECUTING:\n throw new Error((\"\\\"\" + action + \"\\\" on executing generator\"));\n case ST_CLOSED:\n if (action == 'next') {\n return {\n value: undefined,\n done: true\n };\n }\n throw x;\n case ST_NEWBORN:\n if (action === 'throw') {\n ctx.GState = ST_CLOSED;\n throw x;\n }\n if (x !== undefined)\n throw $TypeError('Sent value to newborn generator');\n case ST_SUSPENDED:\n ctx.GState = ST_EXECUTING;\n ctx.action = action;\n ctx.sent = x;\n var value = moveNext(ctx);\n var done = value === ctx;\n if (done)\n value = ctx.returnValue;\n ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;\n return {\n value: value,\n done: done\n };\n }\n }\n var ctxName = createPrivateName();\n var moveNextName = createPrivateName();\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n $defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));\n GeneratorFunctionPrototype.prototype = {\n constructor: GeneratorFunctionPrototype,\n next: function(v) {\n return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);\n },\n throw: function(v) {\n return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);\n }\n };\n $defineProperties(GeneratorFunctionPrototype.prototype, {\n constructor: {enumerable: false},\n next: {enumerable: false},\n throw: {enumerable: false}\n });\n Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {\n return this;\n }));\n function createGeneratorInstance(innerFunction, functionObject, self) {\n var moveNext = getMoveNext(innerFunction, self);\n var ctx = new GeneratorContext();\n var object = $create(functionObject.prototype);\n object[ctxName] = ctx;\n object[moveNextName] = moveNext;\n return object;\n }\n function initGeneratorFunction(functionObject) {\n functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);\n functionObject.__proto__ = GeneratorFunctionPrototype;\n return functionObject;\n }\n function AsyncFunctionContext() {\n GeneratorContext.call(this);\n this.err = undefined;\n var ctx = this;\n ctx.result = new Promise(function(resolve, reject) {\n ctx.resolve = resolve;\n ctx.reject = reject;\n });\n }\n AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);\n AsyncFunctionContext.prototype.end = function() {\n switch (this.state) {\n case END_STATE:\n this.resolve(this.returnValue);\n break;\n case RETHROW_STATE:\n this.reject(this.storedException);\n break;\n default:\n this.reject(getInternalError(this.state));\n }\n };\n AsyncFunctionContext.prototype.handleException = function() {\n this.state = RETHROW_STATE;\n };\n function asyncWrap(innerFunction, self) {\n var moveNext = getMoveNext(innerFunction, self);\n var ctx = new AsyncFunctionContext();\n ctx.createCallback = function(newState) {\n return function(value) {\n ctx.state = newState;\n ctx.value = value;\n moveNext(ctx);\n };\n };\n ctx.errback = function(err) {\n handleCatch(ctx, err);\n moveNext(ctx);\n };\n moveNext(ctx);\n return ctx.result;\n }\n function getMoveNext(innerFunction, self) {\n return function(ctx) {\n while (true) {\n try {\n return innerFunction.call(self, ctx);\n } catch (ex) {\n handleCatch(ctx, ex);\n }\n }\n };\n }\n function handleCatch(ctx, ex) {\n ctx.storedException = ex;\n var last = ctx.tryStack_[ctx.tryStack_.length - 1];\n if (!last) {\n ctx.handleException(ex);\n return;\n }\n ctx.state = last.catch !== undefined ? last.catch : last.finally;\n if (last.finallyFallThrough !== undefined)\n ctx.finallyFallThrough = last.finallyFallThrough;\n }\n $traceurRuntime.asyncWrap = asyncWrap;\n $traceurRuntime.initGeneratorFunction = initGeneratorFunction;\n $traceurRuntime.createGeneratorInstance = createGeneratorInstance;\n})();\n(function() {\n function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {\n var out = [];\n if (opt_scheme) {\n out.push(opt_scheme, ':');\n }\n if (opt_domain) {\n out.push('//');\n if (opt_userInfo) {\n out.push(opt_userInfo, '@');\n }\n out.push(opt_domain);\n if (opt_port) {\n out.push(':', opt_port);\n }\n }\n if (opt_path) {\n out.push(opt_path);\n }\n if (opt_queryData) {\n out.push('?', opt_queryData);\n }\n if (opt_fragment) {\n out.push('#', opt_fragment);\n }\n return out.join('');\n }\n ;\n var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\\\w\\\\d\\\\-\\\\u0100-\\\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\\\?([^#]*))?' + '(?:#(.*))?' + '$');\n var ComponentIndex = {\n SCHEME: 1,\n USER_INFO: 2,\n DOMAIN: 3,\n PORT: 4,\n PATH: 5,\n QUERY_DATA: 6,\n FRAGMENT: 7\n };\n function split(uri) {\n return (uri.match(splitRe));\n }\n function removeDotSegments(path) {\n if (path === '/')\n return '/';\n var leadingSlash = path[0] === '/' ? '/' : '';\n var trailingSlash = path.slice(-1) === '/' ? '/' : '';\n var segments = path.split('/');\n var out = [];\n var up = 0;\n for (var pos = 0; pos < segments.length; pos++) {\n var segment = segments[pos];\n switch (segment) {\n case '':\n case '.':\n break;\n case '..':\n if (out.length)\n out.pop();\n else\n up++;\n break;\n default:\n out.push(segment);\n }\n }\n if (!leadingSlash) {\n while (up-- > 0) {\n out.unshift('..');\n }\n if (out.length === 0)\n out.push('.');\n }\n return leadingSlash + out.join('/') + trailingSlash;\n }\n function joinAndCanonicalizePath(parts) {\n var path = parts[ComponentIndex.PATH] || '';\n path = removeDotSegments(path);\n parts[ComponentIndex.PATH] = path;\n return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);\n }\n function canonicalizeUrl(url) {\n var parts = split(url);\n return joinAndCanonicalizePath(parts);\n }\n function resolveUrl(base, url) {\n var parts = split(url);\n var baseParts = split(base);\n if (parts[ComponentIndex.SCHEME]) {\n return joinAndCanonicalizePath(parts);\n } else {\n parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];\n }\n for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {\n if (!parts[i]) {\n parts[i] = baseParts[i];\n }\n }\n if (parts[ComponentIndex.PATH][0] == '/') {\n return joinAndCanonicalizePath(parts);\n }\n var path = baseParts[ComponentIndex.PATH];\n var index = path.lastIndexOf('/');\n path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];\n parts[ComponentIndex.PATH] = path;\n return joinAndCanonicalizePath(parts);\n }\n function isAbsolute(name) {\n if (!name)\n return false;\n if (name[0] === '/')\n return true;\n var parts = split(name);\n if (parts[ComponentIndex.SCHEME])\n return true;\n return false;\n }\n $traceurRuntime.canonicalizeUrl = canonicalizeUrl;\n $traceurRuntime.isAbsolute = isAbsolute;\n $traceurRuntime.removeDotSegments = removeDotSegments;\n $traceurRuntime.resolveUrl = resolveUrl;\n})();\n(function(global) {\n 'use strict';\n var $__2 = $traceurRuntime,\n canonicalizeUrl = $__2.canonicalizeUrl,\n resolveUrl = $__2.resolveUrl,\n isAbsolute = $__2.isAbsolute;\n var moduleInstantiators = Object.create(null);\n var baseURL;\n if (global.location && global.location.href)\n baseURL = resolveUrl(global.location.href, './');\n else\n baseURL = '';\n var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) {\n this.url = url;\n this.value_ = uncoatedModule;\n };\n ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {});\n var ModuleEvaluationError = function ModuleEvaluationError(erroneousModuleName, cause) {\n this.message = this.constructor.name + ': ' + this.stripCause(cause) + ' in ' + erroneousModuleName;\n if (!(cause instanceof $ModuleEvaluationError) && cause.stack)\n this.stack = this.stripStack(cause.stack);\n else\n this.stack = '';\n };\n var $ModuleEvaluationError = ModuleEvaluationError;\n ($traceurRuntime.createClass)(ModuleEvaluationError, {\n stripError: function(message) {\n return message.replace(/.*Error:/, this.constructor.name + ':');\n },\n stripCause: function(cause) {\n if (!cause)\n return '';\n if (!cause.message)\n return cause + '';\n return this.stripError(cause.message);\n },\n loadedBy: function(moduleName) {\n this.stack += '\\n loaded by ' + moduleName;\n },\n stripStack: function(causeStack) {\n var stack = [];\n causeStack.split('\\n').some((function(frame) {\n if (/UncoatedModuleInstantiator/.test(frame))\n return true;\n stack.push(frame);\n }));\n stack[0] = this.stripError(stack[0]);\n return stack.join('\\n');\n }\n }, {}, Error);\n var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) {\n $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, \"constructor\", [url, null]);\n this.func = func;\n };\n var $UncoatedModuleInstantiator = UncoatedModuleInstantiator;\n ($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() {\n if (this.value_)\n return this.value_;\n try {\n return this.value_ = this.func.call(global);\n } catch (ex) {\n if (ex instanceof ModuleEvaluationError) {\n ex.loadedBy(this.url);\n throw ex;\n }\n throw new ModuleEvaluationError(this.url, ex);\n }\n }}, {}, UncoatedModuleEntry);\n function getUncoatedModuleInstantiator(name) {\n if (!name)\n return;\n var url = ModuleStore.normalize(name);\n return moduleInstantiators[url];\n }\n ;\n var moduleInstances = Object.create(null);\n var liveModuleSentinel = {};\n function Module(uncoatedModule) {\n var isLive = arguments[1];\n var coatedModule = Object.create(null);\n Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {\n var getter,\n value;\n if (isLive === liveModuleSentinel) {\n var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);\n if (descr.get)\n getter = descr.get;\n }\n if (!getter) {\n value = uncoatedModule[name];\n getter = function() {\n return value;\n };\n }\n Object.defineProperty(coatedModule, name, {\n get: getter,\n enumerable: true\n });\n }));\n Object.preventExtensions(coatedModule);\n return coatedModule;\n }\n var ModuleStore = {\n normalize: function(name, refererName, refererAddress) {\n if (typeof name !== \"string\")\n throw new TypeError(\"module name must be a string, not \" + typeof name);\n if (isAbsolute(name))\n return canonicalizeUrl(name);\n if (/[^\\.]\\/\\.\\.\\//.test(name)) {\n throw new Error('module name embeds /../: ' + name);\n }\n if (name[0] === '.' && refererName)\n return resolveUrl(refererName, name);\n return canonicalizeUrl(name);\n },\n get: function(normalizedName) {\n var m = getUncoatedModuleInstantiator(normalizedName);\n if (!m)\n return undefined;\n var moduleInstance = moduleInstances[m.url];\n if (moduleInstance)\n return moduleInstance;\n moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);\n return moduleInstances[m.url] = moduleInstance;\n },\n set: function(normalizedName, module) {\n normalizedName = String(normalizedName);\n moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {\n return module;\n }));\n moduleInstances[normalizedName] = module;\n },\n get baseURL() {\n return baseURL;\n },\n set baseURL(v) {\n baseURL = String(v);\n },\n registerModule: function(name, func) {\n var normalizedName = ModuleStore.normalize(name);\n if (moduleInstantiators[normalizedName])\n throw new Error('duplicate module named ' + normalizedName);\n moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);\n },\n bundleStore: Object.create(null),\n register: function(name, deps, func) {\n if (!deps || !deps.length && !func.length) {\n this.registerModule(name, func);\n } else {\n this.bundleStore[name] = {\n deps: deps,\n execute: function() {\n var $__0 = arguments;\n var depMap = {};\n deps.forEach((function(dep, index) {\n return depMap[dep] = $__0[index];\n }));\n var registryEntry = func.call(this, depMap);\n registryEntry.execute.call(this);\n return registryEntry.exports;\n }\n };\n }\n },\n getAnonymousModule: function(func) {\n return new Module(func.call(global), liveModuleSentinel);\n },\n getForTesting: function(name) {\n var $__0 = this;\n if (!this.testingPrefix_) {\n Object.keys(moduleInstances).some((function(key) {\n var m = /(traceur@[^\\/]*\\/)/.exec(key);\n if (m) {\n $__0.testingPrefix_ = m[1];\n return true;\n }\n }));\n }\n return this.get(this.testingPrefix_ + name);\n }\n };\n ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore}));\n var setupGlobals = $traceurRuntime.setupGlobals;\n $traceurRuntime.setupGlobals = function(global) {\n setupGlobals(global);\n };\n $traceurRuntime.ModuleStore = ModuleStore;\n global.System = {\n register: ModuleStore.register.bind(ModuleStore),\n get: ModuleStore.get,\n set: ModuleStore.set,\n normalize: ModuleStore.normalize\n };\n $traceurRuntime.getModuleImpl = function(name) {\n var instantiator = getUncoatedModuleInstantiator(name);\n return instantiator && instantiator.getUncoatedModule();\n };\n})(typeof global !== 'undefined' ? global : this);\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/utils\";\n var $ceil = Math.ceil;\n var $floor = Math.floor;\n var $isFinite = isFinite;\n var $isNaN = isNaN;\n var $pow = Math.pow;\n var $min = Math.min;\n var toObject = $traceurRuntime.toObject;\n function toUint32(x) {\n return x >>> 0;\n }\n function isObject(x) {\n return x && (typeof x === 'object' || typeof x === 'function');\n }\n function isCallable(x) {\n return typeof x === 'function';\n }\n function isNumber(x) {\n return typeof x === 'number';\n }\n function toInteger(x) {\n x = +x;\n if ($isNaN(x))\n return 0;\n if (x === 0 || !$isFinite(x))\n return x;\n return x > 0 ? $floor(x) : $ceil(x);\n }\n var MAX_SAFE_LENGTH = $pow(2, 53) - 1;\n function toLength(x) {\n var len = toInteger(x);\n return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH);\n }\n function checkIterable(x) {\n return !isObject(x) ? undefined : x[Symbol.iterator];\n }\n function isConstructor(x) {\n return isCallable(x);\n }\n function createIteratorResultObject(value, done) {\n return {\n value: value,\n done: done\n };\n }\n function maybeDefine(object, name, descr) {\n if (!(name in object)) {\n Object.defineProperty(object, name, descr);\n }\n }\n function maybeDefineMethod(object, name, value) {\n maybeDefine(object, name, {\n value: value,\n configurable: true,\n enumerable: false,\n writable: true\n });\n }\n function maybeDefineConst(object, name, value) {\n maybeDefine(object, name, {\n value: value,\n configurable: false,\n enumerable: false,\n writable: false\n });\n }\n function maybeAddFunctions(object, functions) {\n for (var i = 0; i < functions.length; i += 2) {\n var name = functions[i];\n var value = functions[i + 1];\n maybeDefineMethod(object, name, value);\n }\n }\n function maybeAddConsts(object, consts) {\n for (var i = 0; i < consts.length; i += 2) {\n var name = consts[i];\n var value = consts[i + 1];\n maybeDefineConst(object, name, value);\n }\n }\n function maybeAddIterator(object, func, Symbol) {\n if (!Symbol || !Symbol.iterator || object[Symbol.iterator])\n return;\n if (object['@@iterator'])\n func = object['@@iterator'];\n Object.defineProperty(object, Symbol.iterator, {\n value: func,\n configurable: true,\n enumerable: false,\n writable: true\n });\n }\n var polyfills = [];\n function registerPolyfill(func) {\n polyfills.push(func);\n }\n function polyfillAll(global) {\n polyfills.forEach((function(f) {\n return f(global);\n }));\n }\n return {\n get toObject() {\n return toObject;\n },\n get toUint32() {\n return toUint32;\n },\n get isObject() {\n return isObject;\n },\n get isCallable() {\n return isCallable;\n },\n get isNumber() {\n return isNumber;\n },\n get toInteger() {\n return toInteger;\n },\n get toLength() {\n return toLength;\n },\n get checkIterable() {\n return checkIterable;\n },\n get isConstructor() {\n return isConstructor;\n },\n get createIteratorResultObject() {\n return createIteratorResultObject;\n },\n get maybeDefine() {\n return maybeDefine;\n },\n get maybeDefineMethod() {\n return maybeDefineMethod;\n },\n get maybeDefineConst() {\n return maybeDefineConst;\n },\n get maybeAddFunctions() {\n return maybeAddFunctions;\n },\n get maybeAddConsts() {\n return maybeAddConsts;\n },\n get maybeAddIterator() {\n return maybeAddIterator;\n },\n get registerPolyfill() {\n return registerPolyfill;\n },\n get polyfillAll() {\n return polyfillAll;\n }\n };\n});\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/Map\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/Map\";\n var $__3 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n isObject = $__3.isObject,\n maybeAddIterator = $__3.maybeAddIterator,\n registerPolyfill = $__3.registerPolyfill;\n var getOwnHashObject = $traceurRuntime.getOwnHashObject;\n var $hasOwnProperty = Object.prototype.hasOwnProperty;\n var deletedSentinel = {};\n function lookupIndex(map, key) {\n if (isObject(key)) {\n var hashObject = getOwnHashObject(key);\n return hashObject && map.objectIndex_[hashObject.hash];\n }\n if (typeof key === 'string')\n return map.stringIndex_[key];\n return map.primitiveIndex_[key];\n }\n function initMap(map) {\n map.entries_ = [];\n map.objectIndex_ = Object.create(null);\n map.stringIndex_ = Object.create(null);\n map.primitiveIndex_ = Object.create(null);\n map.deletedCount_ = 0;\n }\n var Map = function Map() {\n var iterable = arguments[0];\n if (!isObject(this))\n throw new TypeError('Map called on incompatible type');\n if ($hasOwnProperty.call(this, 'entries_')) {\n throw new TypeError('Map can not be reentrantly initialised');\n }\n initMap(this);\n if (iterable !== null && iterable !== undefined) {\n for (var $__5 = iterable[Symbol.iterator](),\n $__6; !($__6 = $__5.next()).done; ) {\n var $__7 = $__6.value,\n key = $__7[0],\n value = $__7[1];\n {\n this.set(key, value);\n }\n }\n }\n };\n ($traceurRuntime.createClass)(Map, {\n get size() {\n return this.entries_.length / 2 - this.deletedCount_;\n },\n get: function(key) {\n var index = lookupIndex(this, key);\n if (index !== undefined)\n return this.entries_[index + 1];\n },\n set: function(key, value) {\n var objectMode = isObject(key);\n var stringMode = typeof key === 'string';\n var index = lookupIndex(this, key);\n if (index !== undefined) {\n this.entries_[index + 1] = value;\n } else {\n index = this.entries_.length;\n this.entries_[index] = key;\n this.entries_[index + 1] = value;\n if (objectMode) {\n var hashObject = getOwnHashObject(key);\n var hash = hashObject.hash;\n this.objectIndex_[hash] = index;\n } else if (stringMode) {\n this.stringIndex_[key] = index;\n } else {\n this.primitiveIndex_[key] = index;\n }\n }\n return this;\n },\n has: function(key) {\n return lookupIndex(this, key) !== undefined;\n },\n delete: function(key) {\n var objectMode = isObject(key);\n var stringMode = typeof key === 'string';\n var index;\n var hash;\n if (objectMode) {\n var hashObject = getOwnHashObject(key);\n if (hashObject) {\n index = this.objectIndex_[hash = hashObject.hash];\n delete this.objectIndex_[hash];\n }\n } else if (stringMode) {\n index = this.stringIndex_[key];\n delete this.stringIndex_[key];\n } else {\n index = this.primitiveIndex_[key];\n delete this.primitiveIndex_[key];\n }\n if (index !== undefined) {\n this.entries_[index] = deletedSentinel;\n this.entries_[index + 1] = undefined;\n this.deletedCount_++;\n return true;\n }\n return false;\n },\n clear: function() {\n initMap(this);\n },\n forEach: function(callbackFn) {\n var thisArg = arguments[1];\n for (var i = 0; i < this.entries_.length; i += 2) {\n var key = this.entries_[i];\n var value = this.entries_[i + 1];\n if (key === deletedSentinel)\n continue;\n callbackFn.call(thisArg, value, key, this);\n }\n },\n entries: $traceurRuntime.initGeneratorFunction(function $__8() {\n var i,\n key,\n value;\n return $traceurRuntime.createGeneratorInstance(function($ctx) {\n while (true)\n switch ($ctx.state) {\n case 0:\n i = 0;\n $ctx.state = 12;\n break;\n case 12:\n $ctx.state = (i < this.entries_.length) ? 8 : -2;\n break;\n case 4:\n i += 2;\n $ctx.state = 12;\n break;\n case 8:\n key = this.entries_[i];\n value = this.entries_[i + 1];\n $ctx.state = 9;\n break;\n case 9:\n $ctx.state = (key === deletedSentinel) ? 4 : 6;\n break;\n case 6:\n $ctx.state = 2;\n return [key, value];\n case 2:\n $ctx.maybeThrow();\n $ctx.state = 4;\n break;\n default:\n return $ctx.end();\n }\n }, $__8, this);\n }),\n keys: $traceurRuntime.initGeneratorFunction(function $__9() {\n var i,\n key,\n value;\n return $traceurRuntime.createGeneratorInstance(function($ctx) {\n while (true)\n switch ($ctx.state) {\n case 0:\n i = 0;\n $ctx.state = 12;\n break;\n case 12:\n $ctx.state = (i < this.entries_.length) ? 8 : -2;\n break;\n case 4:\n i += 2;\n $ctx.state = 12;\n break;\n case 8:\n key = this.entries_[i];\n value = this.entries_[i + 1];\n $ctx.state = 9;\n break;\n case 9:\n $ctx.state = (key === deletedSentinel) ? 4 : 6;\n break;\n case 6:\n $ctx.state = 2;\n return key;\n case 2:\n $ctx.maybeThrow();\n $ctx.state = 4;\n break;\n default:\n return $ctx.end();\n }\n }, $__9, this);\n }),\n values: $traceurRuntime.initGeneratorFunction(function $__10() {\n var i,\n key,\n value;\n return $traceurRuntime.createGeneratorInstance(function($ctx) {\n while (true)\n switch ($ctx.state) {\n case 0:\n i = 0;\n $ctx.state = 12;\n break;\n case 12:\n $ctx.state = (i < this.entries_.length) ? 8 : -2;\n break;\n case 4:\n i += 2;\n $ctx.state = 12;\n break;\n case 8:\n key = this.entries_[i];\n value = this.entries_[i + 1];\n $ctx.state = 9;\n break;\n case 9:\n $ctx.state = (key === deletedSentinel) ? 4 : 6;\n break;\n case 6:\n $ctx.state = 2;\n return value;\n case 2:\n $ctx.maybeThrow();\n $ctx.state = 4;\n break;\n default:\n return $ctx.end();\n }\n }, $__10, this);\n })\n }, {});\n Object.defineProperty(Map.prototype, Symbol.iterator, {\n configurable: true,\n writable: true,\n value: Map.prototype.entries\n });\n function polyfillMap(global) {\n var $__7 = global,\n Object = $__7.Object,\n Symbol = $__7.Symbol;\n if (!global.Map)\n global.Map = Map;\n var mapPrototype = global.Map.prototype;\n if (mapPrototype.entries) {\n maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol);\n maybeAddIterator(Object.getPrototypeOf(new global.Map().entries()), function() {\n return this;\n }, Symbol);\n }\n }\n registerPolyfill(polyfillMap);\n return {\n get Map() {\n return Map;\n },\n get polyfillMap() {\n return polyfillMap;\n }\n };\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/Map\" + '');\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/Set\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/Set\";\n var $__11 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n isObject = $__11.isObject,\n maybeAddIterator = $__11.maybeAddIterator,\n registerPolyfill = $__11.registerPolyfill;\n var Map = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/Map\").Map;\n var getOwnHashObject = $traceurRuntime.getOwnHashObject;\n var $hasOwnProperty = Object.prototype.hasOwnProperty;\n function initSet(set) {\n set.map_ = new Map();\n }\n var Set = function Set() {\n var iterable = arguments[0];\n if (!isObject(this))\n throw new TypeError('Set called on incompatible type');\n if ($hasOwnProperty.call(this, 'map_')) {\n throw new TypeError('Set can not be reentrantly initialised');\n }\n initSet(this);\n if (iterable !== null && iterable !== undefined) {\n for (var $__15 = iterable[Symbol.iterator](),\n $__16; !($__16 = $__15.next()).done; ) {\n var item = $__16.value;\n {\n this.add(item);\n }\n }\n }\n };\n ($traceurRuntime.createClass)(Set, {\n get size() {\n return this.map_.size;\n },\n has: function(key) {\n return this.map_.has(key);\n },\n add: function(key) {\n this.map_.set(key, key);\n return this;\n },\n delete: function(key) {\n return this.map_.delete(key);\n },\n clear: function() {\n return this.map_.clear();\n },\n forEach: function(callbackFn) {\n var thisArg = arguments[1];\n var $__13 = this;\n return this.map_.forEach((function(value, key) {\n callbackFn.call(thisArg, key, key, $__13);\n }));\n },\n values: $traceurRuntime.initGeneratorFunction(function $__18() {\n var $__19,\n $__20;\n return $traceurRuntime.createGeneratorInstance(function($ctx) {\n while (true)\n switch ($ctx.state) {\n case 0:\n $__19 = this.map_.keys()[Symbol.iterator]();\n $ctx.sent = void 0;\n $ctx.action = 'next';\n $ctx.state = 12;\n break;\n case 12:\n $__20 = $__19[$ctx.action]($ctx.sentIgnoreThrow);\n $ctx.state = 9;\n break;\n case 9:\n $ctx.state = ($__20.done) ? 3 : 2;\n break;\n case 3:\n $ctx.sent = $__20.value;\n $ctx.state = -2;\n break;\n case 2:\n $ctx.state = 12;\n return $__20.value;\n default:\n return $ctx.end();\n }\n }, $__18, this);\n }),\n entries: $traceurRuntime.initGeneratorFunction(function $__21() {\n var $__22,\n $__23;\n return $traceurRuntime.createGeneratorInstance(function($ctx) {\n while (true)\n switch ($ctx.state) {\n case 0:\n $__22 = this.map_.entries()[Symbol.iterator]();\n $ctx.sent = void 0;\n $ctx.action = 'next';\n $ctx.state = 12;\n break;\n case 12:\n $__23 = $__22[$ctx.action]($ctx.sentIgnoreThrow);\n $ctx.state = 9;\n break;\n case 9:\n $ctx.state = ($__23.done) ? 3 : 2;\n break;\n case 3:\n $ctx.sent = $__23.value;\n $ctx.state = -2;\n break;\n case 2:\n $ctx.state = 12;\n return $__23.value;\n default:\n return $ctx.end();\n }\n }, $__21, this);\n })\n }, {});\n Object.defineProperty(Set.prototype, Symbol.iterator, {\n configurable: true,\n writable: true,\n value: Set.prototype.values\n });\n Object.defineProperty(Set.prototype, 'keys', {\n configurable: true,\n writable: true,\n value: Set.prototype.values\n });\n function polyfillSet(global) {\n var $__17 = global,\n Object = $__17.Object,\n Symbol = $__17.Symbol;\n if (!global.Set)\n global.Set = Set;\n var setPrototype = global.Set.prototype;\n if (setPrototype.values) {\n maybeAddIterator(setPrototype, setPrototype.values, Symbol);\n maybeAddIterator(Object.getPrototypeOf(new global.Set().values()), function() {\n return this;\n }, Symbol);\n }\n }\n registerPolyfill(polyfillSet);\n return {\n get Set() {\n return Set;\n },\n get polyfillSet() {\n return polyfillSet;\n }\n };\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/Set\" + '');\nSystem.register(\"traceur-runtime@0.0.62/node_modules/rsvp/lib/rsvp/asap\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/node_modules/rsvp/lib/rsvp/asap\";\n var len = 0;\n function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n scheduleFlush();\n }\n }\n var $__default = asap;\n var browserGlobal = (typeof window !== 'undefined') ? window : {};\n var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\n var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n function useNextTick() {\n return function() {\n process.nextTick(flush);\n };\n }\n function useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, {characterData: true});\n return function() {\n node.data = (iterations = ++iterations % 2);\n };\n }\n function useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function() {\n channel.port2.postMessage(0);\n };\n }\n function useSetTimeout() {\n return function() {\n setTimeout(flush, 1);\n };\n }\n var queue = new Array(1000);\n function flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n callback(arg);\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n len = 0;\n }\n var scheduleFlush;\n if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {\n scheduleFlush = useNextTick();\n } else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n } else if (isWorker) {\n scheduleFlush = useMessageChannel();\n } else {\n scheduleFlush = useSetTimeout();\n }\n return {get default() {\n return $__default;\n }};\n});\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/Promise\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/Promise\";\n var async = System.get(\"traceur-runtime@0.0.62/node_modules/rsvp/lib/rsvp/asap\").default;\n var registerPolyfill = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\").registerPolyfill;\n var promiseRaw = {};\n function isPromise(x) {\n return x && typeof x === 'object' && x.status_ !== undefined;\n }\n function idResolveHandler(x) {\n return x;\n }\n function idRejectHandler(x) {\n throw x;\n }\n function chain(promise) {\n var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;\n var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;\n var deferred = getDeferred(promise.constructor);\n switch (promise.status_) {\n case undefined:\n throw TypeError;\n case 0:\n promise.onResolve_.push(onResolve, deferred);\n promise.onReject_.push(onReject, deferred);\n break;\n case +1:\n promiseEnqueue(promise.value_, [onResolve, deferred]);\n break;\n case -1:\n promiseEnqueue(promise.value_, [onReject, deferred]);\n break;\n }\n return deferred.promise;\n }\n function getDeferred(C) {\n if (this === $Promise) {\n var promise = promiseInit(new $Promise(promiseRaw));\n return {\n promise: promise,\n resolve: (function(x) {\n promiseResolve(promise, x);\n }),\n reject: (function(r) {\n promiseReject(promise, r);\n })\n };\n } else {\n var result = {};\n result.promise = new C((function(resolve, reject) {\n result.resolve = resolve;\n result.reject = reject;\n }));\n return result;\n }\n }\n function promiseSet(promise, status, value, onResolve, onReject) {\n promise.status_ = status;\n promise.value_ = value;\n promise.onResolve_ = onResolve;\n promise.onReject_ = onReject;\n return promise;\n }\n function promiseInit(promise) {\n return promiseSet(promise, 0, undefined, [], []);\n }\n var Promise = function Promise(resolver) {\n if (resolver === promiseRaw)\n return;\n if (typeof resolver !== 'function')\n throw new TypeError;\n var promise = promiseInit(this);\n try {\n resolver((function(x) {\n promiseResolve(promise, x);\n }), (function(r) {\n promiseReject(promise, r);\n }));\n } catch (e) {\n promiseReject(promise, e);\n }\n };\n ($traceurRuntime.createClass)(Promise, {\n catch: function(onReject) {\n return this.then(undefined, onReject);\n },\n then: function(onResolve, onReject) {\n if (typeof onResolve !== 'function')\n onResolve = idResolveHandler;\n if (typeof onReject !== 'function')\n onReject = idRejectHandler;\n var that = this;\n var constructor = this.constructor;\n return chain(this, function(x) {\n x = promiseCoerce(constructor, x);\n return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);\n }, onReject);\n }\n }, {\n resolve: function(x) {\n if (this === $Promise) {\n if (isPromise(x)) {\n return x;\n }\n return promiseSet(new $Promise(promiseRaw), +1, x);\n } else {\n return new this(function(resolve, reject) {\n resolve(x);\n });\n }\n },\n reject: function(r) {\n if (this === $Promise) {\n return promiseSet(new $Promise(promiseRaw), -1, r);\n } else {\n return new this((function(resolve, reject) {\n reject(r);\n }));\n }\n },\n all: function(values) {\n var deferred = getDeferred(this);\n var resolutions = [];\n try {\n var count = values.length;\n if (count === 0) {\n deferred.resolve(resolutions);\n } else {\n for (var i = 0; i < values.length; i++) {\n this.resolve(values[i]).then(function(i, x) {\n resolutions[i] = x;\n if (--count === 0)\n deferred.resolve(resolutions);\n }.bind(undefined, i), (function(r) {\n deferred.reject(r);\n }));\n }\n }\n } catch (e) {\n deferred.reject(e);\n }\n return deferred.promise;\n },\n race: function(values) {\n var deferred = getDeferred(this);\n try {\n for (var i = 0; i < values.length; i++) {\n this.resolve(values[i]).then((function(x) {\n deferred.resolve(x);\n }), (function(r) {\n deferred.reject(r);\n }));\n }\n } catch (e) {\n deferred.reject(e);\n }\n return deferred.promise;\n }\n });\n var $Promise = Promise;\n var $PromiseReject = $Promise.reject;\n function promiseResolve(promise, x) {\n promiseDone(promise, +1, x, promise.onResolve_);\n }\n function promiseReject(promise, r) {\n promiseDone(promise, -1, r, promise.onReject_);\n }\n function promiseDone(promise, status, value, reactions) {\n if (promise.status_ !== 0)\n return;\n promiseEnqueue(value, reactions);\n promiseSet(promise, status, value);\n }\n function promiseEnqueue(value, tasks) {\n async((function() {\n for (var i = 0; i < tasks.length; i += 2) {\n promiseHandle(value, tasks[i], tasks[i + 1]);\n }\n }));\n }\n function promiseHandle(value, handler, deferred) {\n try {\n var result = handler(value);\n if (result === deferred.promise)\n throw new TypeError;\n else if (isPromise(result))\n chain(result, deferred.resolve, deferred.reject);\n else\n deferred.resolve(result);\n } catch (e) {\n try {\n deferred.reject(e);\n } catch (e) {}\n }\n }\n var thenableSymbol = '@@thenable';\n function isObject(x) {\n return x && (typeof x === 'object' || typeof x === 'function');\n }\n function promiseCoerce(constructor, x) {\n if (!isPromise(x) && isObject(x)) {\n var then;\n try {\n then = x.then;\n } catch (r) {\n var promise = $PromiseReject.call(constructor, r);\n x[thenableSymbol] = promise;\n return promise;\n }\n if (typeof then === 'function') {\n var p = x[thenableSymbol];\n if (p) {\n return p;\n } else {\n var deferred = getDeferred(constructor);\n x[thenableSymbol] = deferred.promise;\n try {\n then.call(x, deferred.resolve, deferred.reject);\n } catch (r) {\n deferred.reject(r);\n }\n return deferred.promise;\n }\n }\n }\n return x;\n }\n function polyfillPromise(global) {\n if (!global.Promise)\n global.Promise = Promise;\n }\n registerPolyfill(polyfillPromise);\n return {\n get Promise() {\n return Promise;\n },\n get polyfillPromise() {\n return polyfillPromise;\n }\n };\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/Promise\" + '');\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/StringIterator\", [], function() {\n \"use strict\";\n var $__29;\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/StringIterator\";\n var $__27 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n createIteratorResultObject = $__27.createIteratorResultObject,\n isObject = $__27.isObject;\n var $__30 = $traceurRuntime,\n hasOwnProperty = $__30.hasOwnProperty,\n toProperty = $__30.toProperty;\n var iteratedString = Symbol('iteratedString');\n var stringIteratorNextIndex = Symbol('stringIteratorNextIndex');\n var StringIterator = function StringIterator() {};\n ($traceurRuntime.createClass)(StringIterator, ($__29 = {}, Object.defineProperty($__29, \"next\", {\n value: function() {\n var o = this;\n if (!isObject(o) || !hasOwnProperty(o, iteratedString)) {\n throw new TypeError('this must be a StringIterator object');\n }\n var s = o[toProperty(iteratedString)];\n if (s === undefined) {\n return createIteratorResultObject(undefined, true);\n }\n var position = o[toProperty(stringIteratorNextIndex)];\n var len = s.length;\n if (position >= len) {\n o[toProperty(iteratedString)] = undefined;\n return createIteratorResultObject(undefined, true);\n }\n var first = s.charCodeAt(position);\n var resultString;\n if (first < 0xD800 || first > 0xDBFF || position + 1 === len) {\n resultString = String.fromCharCode(first);\n } else {\n var second = s.charCodeAt(position + 1);\n if (second < 0xDC00 || second > 0xDFFF) {\n resultString = String.fromCharCode(first);\n } else {\n resultString = String.fromCharCode(first) + String.fromCharCode(second);\n }\n }\n o[toProperty(stringIteratorNextIndex)] = position + resultString.length;\n return createIteratorResultObject(resultString, false);\n },\n configurable: true,\n enumerable: true,\n writable: true\n }), Object.defineProperty($__29, Symbol.iterator, {\n value: function() {\n return this;\n },\n configurable: true,\n enumerable: true,\n writable: true\n }), $__29), {});\n function createStringIterator(string) {\n var s = String(string);\n var iterator = Object.create(StringIterator.prototype);\n iterator[toProperty(iteratedString)] = s;\n iterator[toProperty(stringIteratorNextIndex)] = 0;\n return iterator;\n }\n return {get createStringIterator() {\n return createStringIterator;\n }};\n});\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/String\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/String\";\n var createStringIterator = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/StringIterator\").createStringIterator;\n var $__32 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n maybeAddFunctions = $__32.maybeAddFunctions,\n maybeAddIterator = $__32.maybeAddIterator,\n registerPolyfill = $__32.registerPolyfill;\n var $toString = Object.prototype.toString;\n var $indexOf = String.prototype.indexOf;\n var $lastIndexOf = String.prototype.lastIndexOf;\n function startsWith(search) {\n var string = String(this);\n if (this == null || $toString.call(search) == '[object RegExp]') {\n throw TypeError();\n }\n var stringLength = string.length;\n var searchString = String(search);\n var searchLength = searchString.length;\n var position = arguments.length > 1 ? arguments[1] : undefined;\n var pos = position ? Number(position) : 0;\n if (isNaN(pos)) {\n pos = 0;\n }\n var start = Math.min(Math.max(pos, 0), stringLength);\n return $indexOf.call(string, searchString, pos) == start;\n }\n function endsWith(search) {\n var string = String(this);\n if (this == null || $toString.call(search) == '[object RegExp]') {\n throw TypeError();\n }\n var stringLength = string.length;\n var searchString = String(search);\n var searchLength = searchString.length;\n var pos = stringLength;\n if (arguments.length > 1) {\n var position = arguments[1];\n if (position !== undefined) {\n pos = position ? Number(position) : 0;\n if (isNaN(pos)) {\n pos = 0;\n }\n }\n }\n var end = Math.min(Math.max(pos, 0), stringLength);\n var start = end - searchLength;\n if (start < 0) {\n return false;\n }\n return $lastIndexOf.call(string, searchString, start) == start;\n }\n function contains(search) {\n if (this == null) {\n throw TypeError();\n }\n var string = String(this);\n var stringLength = string.length;\n var searchString = String(search);\n var searchLength = searchString.length;\n var position = arguments.length > 1 ? arguments[1] : undefined;\n var pos = position ? Number(position) : 0;\n if (isNaN(pos)) {\n pos = 0;\n }\n var start = Math.min(Math.max(pos, 0), stringLength);\n return $indexOf.call(string, searchString, pos) != -1;\n }\n function repeat(count) {\n if (this == null) {\n throw TypeError();\n }\n var string = String(this);\n var n = count ? Number(count) : 0;\n if (isNaN(n)) {\n n = 0;\n }\n if (n < 0 || n == Infinity) {\n throw RangeError();\n }\n if (n == 0) {\n return '';\n }\n var result = '';\n while (n--) {\n result += string;\n }\n return result;\n }\n function codePointAt(position) {\n if (this == null) {\n throw TypeError();\n }\n var string = String(this);\n var size = string.length;\n var index = position ? Number(position) : 0;\n if (isNaN(index)) {\n index = 0;\n }\n if (index < 0 || index >= size) {\n return undefined;\n }\n var first = string.charCodeAt(index);\n var second;\n if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {\n second = string.charCodeAt(index + 1);\n if (second >= 0xDC00 && second <= 0xDFFF) {\n return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n }\n }\n return first;\n }\n function raw(callsite) {\n var raw = callsite.raw;\n var len = raw.length >>> 0;\n if (len === 0)\n return '';\n var s = '';\n var i = 0;\n while (true) {\n s += raw[i];\n if (i + 1 === len)\n return s;\n s += arguments[++i];\n }\n }\n function fromCodePoint() {\n var codeUnits = [];\n var floor = Math.floor;\n var highSurrogate;\n var lowSurrogate;\n var index = -1;\n var length = arguments.length;\n if (!length) {\n return '';\n }\n while (++index < length) {\n var codePoint = Number(arguments[index]);\n if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {\n throw RangeError('Invalid code point: ' + codePoint);\n }\n if (codePoint <= 0xFFFF) {\n codeUnits.push(codePoint);\n } else {\n codePoint -= 0x10000;\n highSurrogate = (codePoint >> 10) + 0xD800;\n lowSurrogate = (codePoint % 0x400) + 0xDC00;\n codeUnits.push(highSurrogate, lowSurrogate);\n }\n }\n return String.fromCharCode.apply(null, codeUnits);\n }\n function stringPrototypeIterator() {\n var o = $traceurRuntime.checkObjectCoercible(this);\n var s = String(o);\n return createStringIterator(s);\n }\n function polyfillString(global) {\n var String = global.String;\n maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]);\n maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);\n maybeAddIterator(String.prototype, stringPrototypeIterator, Symbol);\n }\n registerPolyfill(polyfillString);\n return {\n get startsWith() {\n return startsWith;\n },\n get endsWith() {\n return endsWith;\n },\n get contains() {\n return contains;\n },\n get repeat() {\n return repeat;\n },\n get codePointAt() {\n return codePointAt;\n },\n get raw() {\n return raw;\n },\n get fromCodePoint() {\n return fromCodePoint;\n },\n get stringPrototypeIterator() {\n return stringPrototypeIterator;\n },\n get polyfillString() {\n return polyfillString;\n }\n };\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/String\" + '');\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/ArrayIterator\", [], function() {\n \"use strict\";\n var $__36;\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/ArrayIterator\";\n var $__34 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n toObject = $__34.toObject,\n toUint32 = $__34.toUint32,\n createIteratorResultObject = $__34.createIteratorResultObject;\n var ARRAY_ITERATOR_KIND_KEYS = 1;\n var ARRAY_ITERATOR_KIND_VALUES = 2;\n var ARRAY_ITERATOR_KIND_ENTRIES = 3;\n var ArrayIterator = function ArrayIterator() {};\n ($traceurRuntime.createClass)(ArrayIterator, ($__36 = {}, Object.defineProperty($__36, \"next\", {\n value: function() {\n var iterator = toObject(this);\n var array = iterator.iteratorObject_;\n if (!array) {\n throw new TypeError('Object is not an ArrayIterator');\n }\n var index = iterator.arrayIteratorNextIndex_;\n var itemKind = iterator.arrayIterationKind_;\n var length = toUint32(array.length);\n if (index >= length) {\n iterator.arrayIteratorNextIndex_ = Infinity;\n return createIteratorResultObject(undefined, true);\n }\n iterator.arrayIteratorNextIndex_ = index + 1;\n if (itemKind == ARRAY_ITERATOR_KIND_VALUES)\n return createIteratorResultObject(array[index], false);\n if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)\n return createIteratorResultObject([index, array[index]], false);\n return createIteratorResultObject(index, false);\n },\n configurable: true,\n enumerable: true,\n writable: true\n }), Object.defineProperty($__36, Symbol.iterator, {\n value: function() {\n return this;\n },\n configurable: true,\n enumerable: true,\n writable: true\n }), $__36), {});\n function createArrayIterator(array, kind) {\n var object = toObject(array);\n var iterator = new ArrayIterator;\n iterator.iteratorObject_ = object;\n iterator.arrayIteratorNextIndex_ = 0;\n iterator.arrayIterationKind_ = kind;\n return iterator;\n }\n function entries() {\n return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);\n }\n function keys() {\n return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);\n }\n function values() {\n return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);\n }\n return {\n get entries() {\n return entries;\n },\n get keys() {\n return keys;\n },\n get values() {\n return values;\n }\n };\n});\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/Array\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/Array\";\n var $__37 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/ArrayIterator\"),\n entries = $__37.entries,\n keys = $__37.keys,\n values = $__37.values;\n var $__38 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n checkIterable = $__38.checkIterable,\n isCallable = $__38.isCallable,\n isConstructor = $__38.isConstructor,\n maybeAddFunctions = $__38.maybeAddFunctions,\n maybeAddIterator = $__38.maybeAddIterator,\n registerPolyfill = $__38.registerPolyfill,\n toInteger = $__38.toInteger,\n toLength = $__38.toLength,\n toObject = $__38.toObject;\n function from(arrLike) {\n var mapFn = arguments[1];\n var thisArg = arguments[2];\n var C = this;\n var items = toObject(arrLike);\n var mapping = mapFn !== undefined;\n var k = 0;\n var arr,\n len;\n if (mapping && !isCallable(mapFn)) {\n throw TypeError();\n }\n if (checkIterable(items)) {\n arr = isConstructor(C) ? new C() : [];\n for (var $__39 = items[Symbol.iterator](),\n $__40; !($__40 = $__39.next()).done; ) {\n var item = $__40.value;\n {\n if (mapping) {\n arr[k] = mapFn.call(thisArg, item, k);\n } else {\n arr[k] = item;\n }\n k++;\n }\n }\n arr.length = k;\n return arr;\n }\n len = toLength(items.length);\n arr = isConstructor(C) ? new C(len) : new Array(len);\n for (; k < len; k++) {\n if (mapping) {\n arr[k] = typeof thisArg === 'undefined' ? mapFn(items[k], k) : mapFn.call(thisArg, items[k], k);\n } else {\n arr[k] = items[k];\n }\n }\n arr.length = len;\n return arr;\n }\n function of() {\n for (var items = [],\n $__41 = 0; $__41 < arguments.length; $__41++)\n items[$__41] = arguments[$__41];\n var C = this;\n var len = items.length;\n var arr = isConstructor(C) ? new C(len) : new Array(len);\n for (var k = 0; k < len; k++) {\n arr[k] = items[k];\n }\n arr.length = len;\n return arr;\n }\n function fill(value) {\n var start = arguments[1] !== (void 0) ? arguments[1] : 0;\n var end = arguments[2];\n var object = toObject(this);\n var len = toLength(object.length);\n var fillStart = toInteger(start);\n var fillEnd = end !== undefined ? toInteger(end) : len;\n fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);\n fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);\n while (fillStart < fillEnd) {\n object[fillStart] = value;\n fillStart++;\n }\n return object;\n }\n function find(predicate) {\n var thisArg = arguments[1];\n return findHelper(this, predicate, thisArg);\n }\n function findIndex(predicate) {\n var thisArg = arguments[1];\n return findHelper(this, predicate, thisArg, true);\n }\n function findHelper(self, predicate) {\n var thisArg = arguments[2];\n var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;\n var object = toObject(self);\n var len = toLength(object.length);\n if (!isCallable(predicate)) {\n throw TypeError();\n }\n for (var i = 0; i < len; i++) {\n if (i in object) {\n var value = object[i];\n if (predicate.call(thisArg, value, i, object)) {\n return returnIndex ? i : value;\n }\n }\n }\n return returnIndex ? -1 : undefined;\n }\n function polyfillArray(global) {\n var $__42 = global,\n Array = $__42.Array,\n Object = $__42.Object,\n Symbol = $__42.Symbol;\n maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);\n maybeAddFunctions(Array, ['from', from, 'of', of]);\n maybeAddIterator(Array.prototype, values, Symbol);\n maybeAddIterator(Object.getPrototypeOf([].values()), function() {\n return this;\n }, Symbol);\n }\n registerPolyfill(polyfillArray);\n return {\n get from() {\n return from;\n },\n get of() {\n return of;\n },\n get fill() {\n return fill;\n },\n get find() {\n return find;\n },\n get findIndex() {\n return findIndex;\n },\n get polyfillArray() {\n return polyfillArray;\n }\n };\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/Array\" + '');\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/Object\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/Object\";\n var $__43 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n maybeAddFunctions = $__43.maybeAddFunctions,\n registerPolyfill = $__43.registerPolyfill;\n var $__44 = $traceurRuntime,\n defineProperty = $__44.defineProperty,\n getOwnPropertyDescriptor = $__44.getOwnPropertyDescriptor,\n getOwnPropertyNames = $__44.getOwnPropertyNames,\n keys = $__44.keys,\n privateNames = $__44.privateNames;\n function is(left, right) {\n if (left === right)\n return left !== 0 || 1 / left === 1 / right;\n return left !== left && right !== right;\n }\n function assign(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n var props = keys(source);\n var p,\n length = props.length;\n for (p = 0; p < length; p++) {\n var name = props[p];\n if (privateNames[name])\n continue;\n target[name] = source[name];\n }\n }\n return target;\n }\n function mixin(target, source) {\n var props = getOwnPropertyNames(source);\n var p,\n descriptor,\n length = props.length;\n for (p = 0; p < length; p++) {\n var name = props[p];\n if (privateNames[name])\n continue;\n descriptor = getOwnPropertyDescriptor(source, props[p]);\n defineProperty(target, props[p], descriptor);\n }\n return target;\n }\n function polyfillObject(global) {\n var Object = global.Object;\n maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);\n }\n registerPolyfill(polyfillObject);\n return {\n get is() {\n return is;\n },\n get assign() {\n return assign;\n },\n get mixin() {\n return mixin;\n },\n get polyfillObject() {\n return polyfillObject;\n }\n };\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/Object\" + '');\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/Number\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/Number\";\n var $__46 = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\"),\n isNumber = $__46.isNumber,\n maybeAddConsts = $__46.maybeAddConsts,\n maybeAddFunctions = $__46.maybeAddFunctions,\n registerPolyfill = $__46.registerPolyfill,\n toInteger = $__46.toInteger;\n var $abs = Math.abs;\n var $isFinite = isFinite;\n var $isNaN = isNaN;\n var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;\n var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1;\n var EPSILON = Math.pow(2, -52);\n function NumberIsFinite(number) {\n return isNumber(number) && $isFinite(number);\n }\n ;\n function isInteger(number) {\n return NumberIsFinite(number) && toInteger(number) === number;\n }\n function NumberIsNaN(number) {\n return isNumber(number) && $isNaN(number);\n }\n ;\n function isSafeInteger(number) {\n if (NumberIsFinite(number)) {\n var integral = toInteger(number);\n if (integral === number)\n return $abs(integral) <= MAX_SAFE_INTEGER;\n }\n return false;\n }\n function polyfillNumber(global) {\n var Number = global.Number;\n maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]);\n maybeAddFunctions(Number, ['isFinite', NumberIsFinite, 'isInteger', isInteger, 'isNaN', NumberIsNaN, 'isSafeInteger', isSafeInteger]);\n }\n registerPolyfill(polyfillNumber);\n return {\n get MAX_SAFE_INTEGER() {\n return MAX_SAFE_INTEGER;\n },\n get MIN_SAFE_INTEGER() {\n return MIN_SAFE_INTEGER;\n },\n get EPSILON() {\n return EPSILON;\n },\n get isFinite() {\n return NumberIsFinite;\n },\n get isInteger() {\n return isInteger;\n },\n get isNaN() {\n return NumberIsNaN;\n },\n get isSafeInteger() {\n return isSafeInteger;\n },\n get polyfillNumber() {\n return polyfillNumber;\n }\n };\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/Number\" + '');\nSystem.register(\"traceur-runtime@0.0.62/src/runtime/polyfills/polyfills\", [], function() {\n \"use strict\";\n var __moduleName = \"traceur-runtime@0.0.62/src/runtime/polyfills/polyfills\";\n var polyfillAll = System.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/utils\").polyfillAll;\n polyfillAll(this);\n var setupGlobals = $traceurRuntime.setupGlobals;\n $traceurRuntime.setupGlobals = function(global) {\n setupGlobals(global);\n polyfillAll(global);\n };\n return {};\n});\nSystem.get(\"traceur-runtime@0.0.62/src/runtime/polyfills/polyfills\" + '');\n\n}).call(this,require('_process'),typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n\n},{\"_process\":2}],4:[function(require,module,exports){\n/*global define:false */\n/**\n * Copyright 2013 Craig Campbell\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Mousetrap is a simple keyboard shortcut library for Javascript with\n * no external dependencies\n *\n * @version 1.4.6\n * @url craig.is/killing/mice\n */\n(function(window, document, undefined) {\n\n /**\n * mapping of special keycodes to their corresponding keys\n *\n * everything in this dictionary cannot use keypress events\n * so it has to be here to map to the correct keycodes for\n * keyup/keydown events\n *\n * @type {Object}\n */\n var _MAP = {\n 8: 'backspace',\n 9: 'tab',\n 13: 'enter',\n 16: 'shift',\n 17: 'ctrl',\n 18: 'alt',\n 20: 'capslock',\n 27: 'esc',\n 32: 'space',\n 33: 'pageup',\n 34: 'pagedown',\n 35: 'end',\n 36: 'home',\n 37: 'left',\n 38: 'up',\n 39: 'right',\n 40: 'down',\n 45: 'ins',\n 46: 'del',\n 91: 'meta',\n 93: 'meta',\n 224: 'meta'\n },\n\n /**\n * mapping for special characters so they can support\n *\n * this dictionary is only used incase you want to bind a\n * keyup or keydown event to one of these keys\n *\n * @type {Object}\n */\n _KEYCODE_MAP = {\n 106: '*',\n 107: '+',\n 109: '-',\n 110: '.',\n 111 : '/',\n 186: ';',\n 187: '=',\n 188: ',',\n 189: '-',\n 190: '.',\n 191: '/',\n 192: '`',\n 219: '[',\n 220: '\\\\',\n 221: ']',\n 222: '\\''\n },\n\n /**\n * this is a mapping of keys that require shift on a US keypad\n * back to the non shift equivelents\n *\n * this is so you can use keyup events with these keys\n *\n * note that this will only work reliably on US keyboards\n *\n * @type {Object}\n */\n _SHIFT_MAP = {\n '~': '`',\n '!': '1',\n '@': '2',\n '#': '3',\n '$': '4',\n '%': '5',\n '^': '6',\n '&': '7',\n '*': '8',\n '(': '9',\n ')': '0',\n '_': '-',\n '+': '=',\n ':': ';',\n '\\\"': '\\'',\n '<': ',',\n '>': '.',\n '?': '/',\n '|': '\\\\'\n },\n\n /**\n * this is a list of special strings you can use to map\n * to modifier keys when you specify your keyboard shortcuts\n *\n * @type {Object}\n */\n _SPECIAL_ALIASES = {\n 'option': 'alt',\n 'command': 'meta',\n 'return': 'enter',\n 'escape': 'esc',\n 'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'\n },\n\n /**\n * variable to store the flipped version of _MAP from above\n * needed to check if we should use keypress or not when no action\n * is specified\n *\n * @type {Object|undefined}\n */\n _REVERSE_MAP,\n\n /**\n * a list of all the callbacks setup via Mousetrap.bind()\n *\n * @type {Object}\n */\n _callbacks = {},\n\n /**\n * direct map of string combinations to callbacks used for trigger()\n *\n * @type {Object}\n */\n _directMap = {},\n\n /**\n * keeps track of what level each sequence is at since multiple\n * sequences can start out with the same sequence\n *\n * @type {Object}\n */\n _sequenceLevels = {},\n\n /**\n * variable to store the setTimeout call\n *\n * @type {null|number}\n */\n _resetTimer,\n\n /**\n * temporary state where we will ignore the next keyup\n *\n * @type {boolean|string}\n */\n _ignoreNextKeyup = false,\n\n /**\n * temporary state where we will ignore the next keypress\n *\n * @type {boolean}\n */\n _ignoreNextKeypress = false,\n\n /**\n * are we currently inside of a sequence?\n * type of action (\"keyup\" or \"keydown\" or \"keypress\") or false\n *\n * @type {boolean|string}\n */\n _nextExpectedAction = false;\n\n /**\n * loop through the f keys, f1 to f19 and add them to the map\n * programatically\n */\n for (var i = 1; i < 20; ++i) {\n _MAP[111 + i] = 'f' + i;\n }\n\n /**\n * loop through to map numbers on the numeric keypad\n */\n for (i = 0; i <= 9; ++i) {\n _MAP[i + 96] = i;\n }\n\n /**\n * cross browser add event method\n *\n * @param {Element|HTMLDocument} object\n * @param {string} type\n * @param {Function} callback\n * @returns void\n */\n function _addEvent(object, type, callback) {\n if (object.addEventListener) {\n object.addEventListener(type, callback, false);\n return;\n }\n\n object.attachEvent('on' + type, callback);\n }\n\n /**\n * takes the event and returns the key character\n *\n * @param {Event} e\n * @return {string}\n */\n function _characterFromEvent(e) {\n\n // for keypress events we should return the character as is\n if (e.type == 'keypress') {\n var character = String.fromCharCode(e.which);\n\n // if the shift key is not pressed then it is safe to assume\n // that we want the character to be lowercase. this means if\n // you accidentally have caps lock on then your key bindings\n // will continue to work\n //\n // the only side effect that might not be desired is if you\n // bind something like 'A' cause you want to trigger an\n // event when capital A is pressed caps lock will no longer\n // trigger the event. shift+a will though.\n if (!e.shiftKey) {\n character = character.toLowerCase();\n }\n\n return character;\n }\n\n // for non keypress events the special maps are needed\n if (_MAP[e.which]) {\n return _MAP[e.which];\n }\n\n if (_KEYCODE_MAP[e.which]) {\n return _KEYCODE_MAP[e.which];\n }\n\n // if it is not in the special map\n\n // with keydown and keyup events the character seems to always\n // come in as an uppercase character whether you are pressing shift\n // or not. we should make sure it is always lowercase for comparisons\n return String.fromCharCode(e.which).toLowerCase();\n }\n\n /**\n * checks if two arrays are equal\n *\n * @param {Array} modifiers1\n * @param {Array} modifiers2\n * @returns {boolean}\n */\n function _modifiersMatch(modifiers1, modifiers2) {\n return modifiers1.sort().join(',') === modifiers2.sort().join(',');\n }\n\n /**\n * resets all sequence counters except for the ones passed in\n *\n * @param {Object} doNotReset\n * @returns void\n */\n function _resetSequences(doNotReset) {\n doNotReset = doNotReset || {};\n\n var activeSequences = false,\n key;\n\n for (key in _sequenceLevels) {\n if (doNotReset[key]) {\n activeSequences = true;\n continue;\n }\n _sequenceLevels[key] = 0;\n }\n\n if (!activeSequences) {\n _nextExpectedAction = false;\n }\n }\n\n /**\n * finds all callbacks that match based on the keycode, modifiers,\n * and action\n *\n * @param {string} character\n * @param {Array} modifiers\n * @param {Event|Object} e\n * @param {string=} sequenceName - name of the sequence we are looking for\n * @param {string=} combination\n * @param {number=} level\n * @returns {Array}\n */\n function _getMatches(character, modifiers, e, sequenceName, combination, level) {\n var i,\n callback,\n matches = [],\n action = e.type;\n\n // if there are no events related to this keycode\n if (!_callbacks[character]) {\n return [];\n }\n\n // if a modifier key is coming up on its own we should allow it\n if (action == 'keyup' && _isModifier(character)) {\n modifiers = [character];\n }\n\n // loop through all callbacks for the key that was pressed\n // and see if any of them match\n for (i = 0; i < _callbacks[character].length; ++i) {\n callback = _callbacks[character][i];\n\n // if a sequence name is not specified, but this is a sequence at\n // the wrong level then move onto the next match\n if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {\n continue;\n }\n\n // if the action we are looking for doesn't match the action we got\n // then we should keep going\n if (action != callback.action) {\n continue;\n }\n\n // if this is a keypress event and the meta key and control key\n // are not pressed that means that we need to only look at the\n // character, otherwise check the modifiers as well\n //\n // chrome will not fire a keypress if meta or control is down\n // safari will fire a keypress if meta or meta+shift is down\n // firefox will fire a keypress if meta or control is down\n if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {\n\n // when you bind a combination or sequence a second time it\n // should overwrite the first one. if a sequenceName or\n // combination is specified in this call it does just that\n //\n // @todo make deleting its own method?\n var deleteCombo = !sequenceName && callback.combo == combination;\n var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;\n if (deleteCombo || deleteSequence) {\n _callbacks[character].splice(i, 1);\n }\n\n matches.push(callback);\n }\n }\n\n return matches;\n }\n\n /**\n * takes a key event and figures out what the modifiers are\n *\n * @param {Event} e\n * @returns {Array}\n */\n function _eventModifiers(e) {\n var modifiers = [];\n\n if (e.shiftKey) {\n modifiers.push('shift');\n }\n\n if (e.altKey) {\n modifiers.push('alt');\n }\n\n if (e.ctrlKey) {\n modifiers.push('ctrl');\n }\n\n if (e.metaKey) {\n modifiers.push('meta');\n }\n\n return modifiers;\n }\n\n /**\n * prevents default for this event\n *\n * @param {Event} e\n * @returns void\n */\n function _preventDefault(e) {\n if (e.preventDefault) {\n e.preventDefault();\n return;\n }\n\n e.returnValue = false;\n }\n\n /**\n * stops propogation for this event\n *\n * @param {Event} e\n * @returns void\n */\n function _stopPropagation(e) {\n if (e.stopPropagation) {\n e.stopPropagation();\n return;\n }\n\n e.cancelBubble = true;\n }\n\n /**\n * actually calls the callback function\n *\n * if your callback function returns false this will use the jquery\n * convention - prevent default and stop propogation on the event\n *\n * @param {Function} callback\n * @param {Event} e\n * @returns void\n */\n function _fireCallback(callback, e, combo, sequence) {\n\n // if this event should not happen stop here\n if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo, sequence)) {\n return;\n }\n\n if (callback(e, combo) === false) {\n _preventDefault(e);\n _stopPropagation(e);\n }\n }\n\n /**\n * handles a character key event\n *\n * @param {string} character\n * @param {Array} modifiers\n * @param {Event} e\n * @returns void\n */\n function _handleKey(character, modifiers, e) {\n var callbacks = _getMatches(character, modifiers, e),\n i,\n doNotReset = {},\n maxLevel = 0,\n processedSequenceCallback = false;\n\n // Calculate the maxLevel for sequences so we can only execute the longest callback sequence\n for (i = 0; i < callbacks.length; ++i) {\n if (callbacks[i].seq) {\n maxLevel = Math.max(maxLevel, callbacks[i].level);\n }\n }\n\n // loop through matching callbacks for this key event\n for (i = 0; i < callbacks.length; ++i) {\n\n // fire for all sequence callbacks\n // this is because if for example you have multiple sequences\n // bound such as \"g i\" and \"g t\" they both need to fire the\n // callback for matching g cause otherwise you can only ever\n // match the first one\n if (callbacks[i].seq) {\n\n // only fire callbacks for the maxLevel to prevent\n // subsequences from also firing\n //\n // for example 'a option b' should not cause 'option b' to fire\n // even though 'option b' is part of the other sequence\n //\n // any sequences that do not match here will be discarded\n // below by the _resetSequences call\n if (callbacks[i].level != maxLevel) {\n continue;\n }\n\n processedSequenceCallback = true;\n\n // keep a list of which sequences were matches for later\n doNotReset[callbacks[i].seq] = 1;\n _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);\n continue;\n }\n\n // if there were no sequence matches but we are still here\n // that means this is a regular match so we should fire that\n if (!processedSequenceCallback) {\n _fireCallback(callbacks[i].callback, e, callbacks[i].combo);\n }\n }\n\n // if the key you pressed matches the type of sequence without\n // being a modifier (ie \"keyup\" or \"keypress\") then we should\n // reset all sequences that were not matched by this event\n //\n // this is so, for example, if you have the sequence \"h a t\" and you\n // type \"h e a r t\" it does not match. in this case the \"e\" will\n // cause the sequence to reset\n //\n // modifier keys are ignored because you can have a sequence\n // that contains modifiers such as \"enter ctrl+space\" and in most\n // cases the modifier key will be pressed before the next key\n //\n // also if you have a sequence such as \"ctrl+b a\" then pressing the\n // \"b\" key will trigger a \"keypress\" and a \"keydown\"\n //\n // the \"keydown\" is expected when there is a modifier, but the\n // \"keypress\" ends up matching the _nextExpectedAction since it occurs\n // after and that causes the sequence to reset\n //\n // we ignore keypresses in a sequence that directly follow a keydown\n // for the same character\n var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;\n if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {\n _resetSequences(doNotReset);\n }\n\n _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';\n }\n\n /**\n * handles a keydown event\n *\n * @param {Event} e\n * @returns void\n */\n function _handleKeyEvent(e) {\n\n // normalize e.which for key events\n // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion\n if (typeof e.which !== 'number') {\n e.which = e.keyCode;\n }\n\n var character = _characterFromEvent(e);\n\n // no character found then stop\n if (!character) {\n return;\n }\n\n // need to use === for the character check because the character can be 0\n if (e.type == 'keyup' && _ignoreNextKeyup === character) {\n _ignoreNextKeyup = false;\n return;\n }\n\n Mousetrap.handleKey(character, _eventModifiers(e), e);\n }\n\n /**\n * determines if the keycode specified is a modifier key or not\n *\n * @param {string} key\n * @returns {boolean}\n */\n function _isModifier(key) {\n return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';\n }\n\n /**\n * called to set a 1 second timeout on the specified sequence\n *\n * this is so after each key press in the sequence you have 1 second\n * to press the next key before you have to start over\n *\n * @returns void\n */\n function _resetSequenceTimer() {\n clearTimeout(_resetTimer);\n _resetTimer = setTimeout(_resetSequences, 1000);\n }\n\n /**\n * reverses the map lookup so that we can look for specific keys\n * to see what can and can't use keypress\n *\n * @return {Object}\n */\n function _getReverseMap() {\n if (!_REVERSE_MAP) {\n _REVERSE_MAP = {};\n for (var key in _MAP) {\n\n // pull out the numeric keypad from here cause keypress should\n // be able to detect the keys from the character\n if (key > 95 && key < 112) {\n continue;\n }\n\n if (_MAP.hasOwnProperty(key)) {\n _REVERSE_MAP[_MAP[key]] = key;\n }\n }\n }\n return _REVERSE_MAP;\n }\n\n /**\n * picks the best action based on the key combination\n *\n * @param {string} key - character for key\n * @param {Array} modifiers\n * @param {string=} action passed in\n */\n function _pickBestAction(key, modifiers, action) {\n\n // if no action was picked in we should try to pick the one\n // that we think would work best for this key\n if (!action) {\n action = _getReverseMap()[key] ? 'keydown' : 'keypress';\n }\n\n // modifier keys don't work as expected with keypress,\n // switch to keydown\n if (action == 'keypress' && modifiers.length) {\n action = 'keydown';\n }\n\n return action;\n }\n\n /**\n * binds a key sequence to an event\n *\n * @param {string} combo - combo specified in bind call\n * @param {Array} keys\n * @param {Function} callback\n * @param {string=} action\n * @returns void\n */\n function _bindSequence(combo, keys, callback, action) {\n\n // start off by adding a sequence level record for this combination\n // and setting the level to 0\n _sequenceLevels[combo] = 0;\n\n /**\n * callback to increase the sequence level for this sequence and reset\n * all other sequences that were active\n *\n * @param {string} nextAction\n * @returns {Function}\n */\n function _increaseSequence(nextAction) {\n return function() {\n _nextExpectedAction = nextAction;\n ++_sequenceLevels[combo];\n _resetSequenceTimer();\n };\n }\n\n /**\n * wraps the specified callback inside of another function in order\n * to reset all sequence counters as soon as this sequence is done\n *\n * @param {Event} e\n * @returns void\n */\n function _callbackAndReset(e) {\n _fireCallback(callback, e, combo);\n\n // we should ignore the next key up if the action is key down\n // or keypress. this is so if you finish a sequence and\n // release the key the final key will not trigger a keyup\n if (action !== 'keyup') {\n _ignoreNextKeyup = _characterFromEvent(e);\n }\n\n // weird race condition if a sequence ends with the key\n // another sequence begins with\n setTimeout(_resetSequences, 10);\n }\n\n // loop through keys one at a time and bind the appropriate callback\n // function. for any key leading up to the final one it should\n // increase the sequence. after the final, it should reset all sequences\n //\n // if an action is specified in the original bind call then that will\n // be used throughout. otherwise we will pass the action that the\n // next key in the sequence should match. this allows a sequence\n // to mix and match keypress and keydown events depending on which\n // ones are better suited to the key provided\n for (var i = 0; i < keys.length; ++i) {\n var isFinal = i + 1 === keys.length;\n var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);\n _bindSingle(keys[i], wrappedCallback, action, combo, i);\n }\n }\n\n /**\n * Converts from a string key combination to an array\n *\n * @param {string} combination like \"command+shift+l\"\n * @return {Array}\n */\n function _keysFromString(combination) {\n if (combination === '+') {\n return ['+'];\n }\n\n return combination.split('+');\n }\n\n /**\n * Gets info for a specific key combination\n *\n * @param {string} combination key combination (\"command+s\" or \"a\" or \"*\")\n * @param {string=} action\n * @returns {Object}\n */\n function _getKeyInfo(combination, action) {\n var keys,\n key,\n i,\n modifiers = [];\n\n // take the keys from this pattern and figure out what the actual\n // pattern is all about\n keys = _keysFromString(combination);\n\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n\n // normalize key names\n if (_SPECIAL_ALIASES[key]) {\n key = _SPECIAL_ALIASES[key];\n }\n\n // if this is not a keypress event then we should\n // be smart about using shift keys\n // this will only work for US keyboards however\n if (action && action != 'keypress' && _SHIFT_MAP[key]) {\n key = _SHIFT_MAP[key];\n modifiers.push('shift');\n }\n\n // if this key is a modifier then add it to the list of modifiers\n if (_isModifier(key)) {\n modifiers.push(key);\n }\n }\n\n // depending on what the key combination is\n // we will try to pick the best event for it\n action = _pickBestAction(key, modifiers, action);\n\n return {\n key: key,\n modifiers: modifiers,\n action: action\n };\n }\n\n /**\n * binds a single keyboard combination\n *\n * @param {string} combination\n * @param {Function} callback\n * @param {string=} action\n * @param {string=} sequenceName - name of sequence if part of sequence\n * @param {number=} level - what part of the sequence the command is\n * @returns void\n */\n function _bindSingle(combination, callback, action, sequenceName, level) {\n\n // store a direct mapped reference for use with Mousetrap.trigger\n _directMap[combination + ':' + action] = callback;\n\n // make sure multiple spaces in a row become a single space\n combination = combination.replace(/\\s+/g, ' ');\n\n var sequence = combination.split(' '),\n info;\n\n // if this pattern is a sequence of keys then run through this method\n // to reprocess each pattern one key at a time\n if (sequence.length > 1) {\n _bindSequence(combination, sequence, callback, action);\n return;\n }\n\n info = _getKeyInfo(combination, action);\n\n // make sure to initialize array if this is the first time\n // a callback is added for this key\n _callbacks[info.key] = _callbacks[info.key] || [];\n\n // remove an existing match if there is one\n _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);\n\n // add this call back to the array\n // if it is a sequence put it at the beginning\n // if not put it at the end\n //\n // this is important because the way these are processed expects\n // the sequence ones to come first\n _callbacks[info.key][sequenceName ? 'unshift' : 'push']({\n callback: callback,\n modifiers: info.modifiers,\n action: info.action,\n seq: sequenceName,\n level: level,\n combo: combination\n });\n }\n\n /**\n * binds multiple combinations to the same callback\n *\n * @param {Array} combinations\n * @param {Function} callback\n * @param {string|undefined} action\n * @returns void\n */\n function _bindMultiple(combinations, callback, action) {\n for (var i = 0; i < combinations.length; ++i) {\n _bindSingle(combinations[i], callback, action);\n }\n }\n\n // start!\n _addEvent(document, 'keypress', _handleKeyEvent);\n _addEvent(document, 'keydown', _handleKeyEvent);\n _addEvent(document, 'keyup', _handleKeyEvent);\n\n var Mousetrap = {\n\n /**\n * binds an event to mousetrap\n *\n * can be a single key, a combination of keys separated with +,\n * an array of keys, or a sequence of keys separated by spaces\n *\n * be sure to list the modifier keys first to make sure that the\n * correct key ends up getting bound (the last key in the pattern)\n *\n * @param {string|Array} keys\n * @param {Function} callback\n * @param {string=} action - 'keypress', 'keydown', or 'keyup'\n * @returns void\n */\n bind: function(keys, callback, action) {\n keys = keys instanceof Array ? keys : [keys];\n _bindMultiple(keys, callback, action);\n return this;\n },\n\n /**\n * unbinds an event to mousetrap\n *\n * the unbinding sets the callback function of the specified key combo\n * to an empty function and deletes the corresponding key in the\n * _directMap dict.\n *\n * TODO: actually remove this from the _callbacks dictionary instead\n * of binding an empty function\n *\n * the keycombo+action has to be exactly the same as\n * it was defined in the bind method\n *\n * @param {string|Array} keys\n * @param {string} action\n * @returns void\n */\n unbind: function(keys, action) {\n return Mousetrap.bind(keys, function() {}, action);\n },\n\n /**\n * triggers an event that has already been bound\n *\n * @param {string} keys\n * @param {string=} action\n * @returns void\n */\n trigger: function(keys, action) {\n if (_directMap[keys + ':' + action]) {\n _directMap[keys + ':' + action]({}, keys);\n }\n return this;\n },\n\n /**\n * resets the library back to its initial state. this is useful\n * if you want to clear out the current keyboard shortcuts and bind\n * new ones - for example if you switch to another page\n *\n * @returns void\n */\n reset: function() {\n _callbacks = {};\n _directMap = {};\n return this;\n },\n\n /**\n * should we stop this event before firing off callbacks\n *\n * @param {Event} e\n * @param {Element} element\n * @return {boolean}\n */\n stopCallback: function(e, element) {\n\n // if the element has the class \"mousetrap\" then no need to stop\n if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {\n return false;\n }\n\n // stop for input, select, and textarea\n return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;\n },\n\n /**\n * exposes _handleKey publicly so it can be overwritten by extensions\n */\n handleKey: _handleKey\n };\n\n // expose mousetrap to the global object\n window.Mousetrap = Mousetrap;\n\n // expose mousetrap as an AMD module\n if (typeof define === 'function' && define.amd) {\n define(Mousetrap);\n }\n}) (window, document);\n\n},{}],5:[function(require,module,exports){\n(function( factory ) {\n\tif (typeof define !== 'undefined' && define.amd) {\n\t\tdefine([], factory);\n\t} else if (typeof module !== 'undefined' && module.exports) {\n\t\tmodule.exports = factory();\n\t} else {\n\t\twindow.scrollMonitor = factory();\n\t}\n})(function() {\n\n\tvar scrollTop = function() {\n\t\treturn window.pageYOffset ||\n\t\t\t(document.documentElement && document.documentElement.scrollTop) ||\n\t\t\tdocument.body.scrollTop;\n\t};\n\n\tvar exports = {};\n\n\tvar watchers = [];\n\n\tvar VISIBILITYCHANGE = 'visibilityChange';\n\tvar ENTERVIEWPORT = 'enterViewport';\n\tvar FULLYENTERVIEWPORT = 'fullyEnterViewport';\n\tvar EXITVIEWPORT = 'exitViewport';\n\tvar PARTIALLYEXITVIEWPORT = 'partiallyExitViewport';\n\tvar LOCATIONCHANGE = 'locationChange';\n\tvar STATECHANGE = 'stateChange';\n\n\tvar eventTypes = [\n\t\tVISIBILITYCHANGE,\n\t\tENTERVIEWPORT,\n\t\tFULLYENTERVIEWPORT,\n\t\tEXITVIEWPORT,\n\t\tPARTIALLYEXITVIEWPORT,\n\t\tLOCATIONCHANGE,\n\t\tSTATECHANGE\n\t];\n\n\tvar defaultOffsets = {top: 0, bottom: 0};\n\n\tvar getViewportHeight = function() {\n\t\treturn window.innerHeight || document.documentElement.clientHeight;\n\t};\n\n\tvar getDocumentHeight = function() {\n\t\t// jQuery approach\n\t\t// whichever is greatest\n\t\treturn Math.max(\n\t\t\tdocument.body.scrollHeight, document.documentElement.scrollHeight,\n\t\t\tdocument.body.offsetHeight, document.documentElement.offsetHeight,\n\t\t\tdocument.documentElement.clientHeight\n\t\t);\n\t};\n\n\texports.viewportTop = null;\n\texports.viewportBottom = null;\n\texports.documentHeight = null;\n\texports.viewportHeight = getViewportHeight();\n\n\tvar previousDocumentHeight;\n\tvar latestEvent;\n\n\tvar calculateViewportI;\n\tfunction calculateViewport() {\n\t\texports.viewportTop = scrollTop();\n\t\texports.viewportBottom = exports.viewportTop + exports.viewportHeight;\n\t\texports.documentHeight = getDocumentHeight();\n\t\tif (exports.documentHeight !== previousDocumentHeight) {\n\t\t\tcalculateViewportI = watchers.length;\n\t\t\twhile( calculateViewportI-- ) {\n\t\t\t\twatchers[calculateViewportI].recalculateLocation();\n\t\t\t}\n\t\t\tpreviousDocumentHeight = exports.documentHeight;\n\t\t}\n\t}\n\n\tfunction recalculateWatchLocationsAndTrigger() {\n\t\texports.viewportHeight = getViewportHeight();\n\t\tcalculateViewport();\n\t\tupdateAndTriggerWatchers();\n\t}\n\n\tvar recalculateAndTriggerTimer;\n\tfunction debouncedRecalcuateAndTrigger() {\n\t\tclearTimeout(recalculateAndTriggerTimer);\n\t\trecalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 );\n\t}\n\n\tvar updateAndTriggerWatchersI;\n\tfunction updateAndTriggerWatchers() {\n\t\t// update all watchers then trigger the events so one can rely on another being up to date.\n\t\tupdateAndTriggerWatchersI = watchers.length;\n\t\twhile( updateAndTriggerWatchersI-- ) {\n\t\t\twatchers[updateAndTriggerWatchersI].update();\n\t\t}\n\n\t\tupdateAndTriggerWatchersI = watchers.length;\n\t\twhile( updateAndTriggerWatchersI-- ) {\n\t\t\twatchers[updateAndTriggerWatchersI].triggerCallbacks();\n\t\t}\n\n\t}\n\n\tfunction ElementWatcher( watchItem, offsets ) {\n\t\tvar self = this;\n\n\t\tthis.watchItem = watchItem;\n\n\t\tif (!offsets) {\n\t\t\tthis.offsets = defaultOffsets;\n\t\t} else if (offsets === +offsets) {\n\t\t\tthis.offsets = {top: offsets, bottom: offsets};\n\t\t} else {\n\t\t\tthis.offsets = {\n\t\t\t\ttop: offsets.top || defaultOffsets.top,\n\t\t\t\tbottom: offsets.bottom || defaultOffsets.bottom\n\t\t\t};\n\t\t}\n\n\t\tthis.callbacks = {}; // {callback: function, isOne: true }\n\n\t\tfor (var i = 0, j = eventTypes.length; i < j; i++) {\n\t\t\tself.callbacks[eventTypes[i]] = [];\n\t\t}\n\n\t\tthis.locked = false;\n\n\t\tvar wasInViewport;\n\t\tvar wasFullyInViewport;\n\t\tvar wasAboveViewport;\n\t\tvar wasBelowViewport;\n\n\t\tvar listenerToTriggerListI;\n\t\tvar listener;\n\t\tfunction triggerCallbackArray( listeners ) {\n\t\t\tif (listeners.length === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlistenerToTriggerListI = listeners.length;\n\t\t\twhile( listenerToTriggerListI-- ) {\n\t\t\t\tlistener = listeners[listenerToTriggerListI];\n\t\t\t\tlistener.callback.call( self, latestEvent );\n\t\t\t\tif (listener.isOne) {\n\t\t\t\t\tlisteners.splice(listenerToTriggerListI, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.triggerCallbacks = function triggerCallbacks() {\n\n\t\t\tif (this.isInViewport && !wasInViewport) {\n\t\t\t\ttriggerCallbackArray( this.callbacks[ENTERVIEWPORT] );\n\t\t\t}\n\t\t\tif (this.isFullyInViewport && !wasFullyInViewport) {\n\t\t\t\ttriggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );\n\t\t\t}\n\n\n\t\t\tif (this.isAboveViewport !== wasAboveViewport &&\n\t\t\t\tthis.isBelowViewport !== wasBelowViewport) {\n\n\t\t\t\ttriggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );\n\n\t\t\t\t// if you skip completely past this element\n\t\t\t\tif (!wasFullyInViewport && !this.isFullyInViewport) {\n\t\t\t\t\ttriggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );\n\t\t\t\t\ttriggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );\n\t\t\t\t}\n\t\t\t\tif (!wasInViewport && !this.isInViewport) {\n\t\t\t\t\ttriggerCallbackArray( this.callbacks[ENTERVIEWPORT] );\n\t\t\t\t\ttriggerCallbackArray( this.callbacks[EXITVIEWPORT] );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!this.isFullyInViewport && wasFullyInViewport) {\n\t\t\t\ttriggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );\n\t\t\t}\n\t\t\tif (!this.isInViewport && wasInViewport) {\n\t\t\t\ttriggerCallbackArray( this.callbacks[EXITVIEWPORT] );\n\t\t\t}\n\t\t\tif (this.isInViewport !== wasInViewport) {\n\t\t\t\ttriggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );\n\t\t\t}\n\t\t\tswitch( true ) {\n\t\t\t\tcase wasInViewport !== this.isInViewport:\n\t\t\t\tcase wasFullyInViewport !== this.isFullyInViewport:\n\t\t\t\tcase wasAboveViewport !== this.isAboveViewport:\n\t\t\t\tcase wasBelowViewport !== this.isBelowViewport:\n\t\t\t\t\ttriggerCallbackArray( this.callbacks[STATECHANGE] );\n\t\t\t}\n\n\t\t\twasInViewport = this.isInViewport;\n\t\t\twasFullyInViewport = this.isFullyInViewport;\n\t\t\twasAboveViewport = this.isAboveViewport;\n\t\t\twasBelowViewport = this.isBelowViewport;\n\n\t\t};\n\n\t\tthis.recalculateLocation = function() {\n\t\t\tif (this.locked) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar previousTop = this.top;\n\t\t\tvar previousBottom = this.bottom;\n\t\t\tif (this.watchItem.nodeName) { // a dom element\n\t\t\t\tvar cachedDisplay = this.watchItem.style.display;\n\t\t\t\tif (cachedDisplay === 'none') {\n\t\t\t\t\tthis.watchItem.style.display = '';\n\t\t\t\t}\n\n\t\t\t\tvar boundingRect = this.watchItem.getBoundingClientRect();\n\t\t\t\tthis.top = boundingRect.top + exports.viewportTop;\n\t\t\t\tthis.bottom = boundingRect.bottom + exports.viewportTop;\n\n\t\t\t\tif (cachedDisplay === 'none') {\n\t\t\t\t\tthis.watchItem.style.display = cachedDisplay;\n\t\t\t\t}\n\n\t\t\t} else if (this.watchItem === +this.watchItem) { // number\n\t\t\t\tif (this.watchItem > 0) {\n\t\t\t\t\tthis.top = this.bottom = this.watchItem;\n\t\t\t\t} else {\n\t\t\t\t\tthis.top = this.bottom = exports.documentHeight - this.watchItem;\n\t\t\t\t}\n\n\t\t\t} else { // an object with a top and bottom property\n\t\t\t\tthis.top = this.watchItem.top;\n\t\t\t\tthis.bottom = this.watchItem.bottom;\n\t\t\t}\n\n\t\t\tthis.top -= this.offsets.top;\n\t\t\tthis.bottom += this.offsets.bottom;\n\t\t\tthis.height = this.bottom - this.top;\n\n\t\t\tif ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) {\n\t\t\t\ttriggerCallbackArray( this.callbacks[LOCATIONCHANGE] );\n\t\t\t}\n\t\t};\n\n\t\tthis.recalculateLocation();\n\t\tthis.update();\n\n\t\twasInViewport = this.isInViewport;\n\t\twasFullyInViewport = this.isFullyInViewport;\n\t\twasAboveViewport = this.isAboveViewport;\n\t\twasBelowViewport = this.isBelowViewport;\n\t}\n\n\tElementWatcher.prototype = {\n\t\ton: function( event, callback, isOne ) {\n\n\t\t\t// trigger the event if it applies to the element right now.\n\t\t\tswitch( true ) {\n\t\t\t\tcase event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport:\n\t\t\t\tcase event === ENTERVIEWPORT && this.isInViewport:\n\t\t\t\tcase event === FULLYENTERVIEWPORT && this.isFullyInViewport:\n\t\t\t\tcase event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport:\n\t\t\t\tcase event === PARTIALLYEXITVIEWPORT && this.isAboveViewport:\n\t\t\t\t\tcallback.call( this, latestEvent );\n\t\t\t\t\tif (isOne) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.callbacks[event]) {\n\t\t\t\tthis.callbacks[event].push({callback: callback, isOne: isOne||false});\n\t\t\t} else {\n\t\t\t\tthrow new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));\n\t\t\t}\n\t\t},\n\t\toff: function( event, callback ) {\n\t\t\tif (this.callbacks[event]) {\n\t\t\t\tfor (var i = 0, item; item = this.callbacks[event][i]; i++) {\n\t\t\t\t\tif (item.callback === callback) {\n\t\t\t\t\t\tthis.callbacks[event].splice(i, 1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));\n\t\t\t}\n\t\t},\n\t\tone: function( event, callback ) {\n\t\t\tthis.on( event, callback, true);\n\t\t},\n\t\trecalculateSize: function() {\n\t\t\tthis.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom;\n\t\t\tthis.bottom = this.top + this.height;\n\t\t},\n\t\tupdate: function() {\n\t\t\tthis.isAboveViewport = this.top < exports.viewportTop;\n\t\t\tthis.isBelowViewport = this.bottom > exports.viewportBottom;\n\n\t\t\tthis.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop);\n\t\t\tthis.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) ||\n\t\t\t\t\t\t\t\t (this.isAboveViewport && this.isBelowViewport);\n\n\t\t},\n\t\tdestroy: function() {\n\t\t\tvar index = watchers.indexOf(this),\n\t\t\t\tself = this;\n\t\t\twatchers.splice(index, 1);\n\t\t\tfor (var i = 0, j = eventTypes.length; i < j; i++) {\n\t\t\t\tself.callbacks[eventTypes[i]].length = 0;\n\t\t\t}\n\t\t},\n\t\t// prevent recalculating the element location\n\t\tlock: function() {\n\t\t\tthis.locked = true;\n\t\t},\n\t\tunlock: function() {\n\t\t\tthis.locked = false;\n\t\t}\n\t};\n\n\tvar eventHandlerFactory = function (type) {\n\t\treturn function( callback, isOne ) {\n\t\t\tthis.on.call(this, type, callback, isOne);\n\t\t};\n\t};\n\n\tfor (var i = 0, j = eventTypes.length; i < j; i++) {\n\t\tvar type = eventTypes[i];\n\t\tElementWatcher.prototype[type] = eventHandlerFactory(type);\n\t}\n\n\ttry {\n\t\tcalculateViewport();\n\t} catch (e) {\n\t\ttry {\n\t\t\twindow.$(calculateViewport);\n\t\t} catch (e) {\n\t\t\tthrow new Error('If you must put scrollMonitor in the , you must use jQuery.');\n\t\t}\n\t}\n\n\tfunction scrollMonitorListener(event) {\n\t\tlatestEvent = event;\n\t\tcalculateViewport();\n\t\tupdateAndTriggerWatchers();\n\t}\n\n\tif (window.addEventListener) {\n\t\twindow.addEventListener('scroll', scrollMonitorListener);\n\t\twindow.addEventListener('resize', debouncedRecalcuateAndTrigger);\n\t} else {\n\t\t// Old IE support\n\t\twindow.attachEvent('onscroll', scrollMonitorListener);\n\t\twindow.attachEvent('onresize', debouncedRecalcuateAndTrigger);\n\t}\n\n\texports.beget = exports.create = function( element, offsets ) {\n\t\tif (typeof element === 'string') {\n\t\t\telement = document.querySelector(element);\n\t\t} else if (element && element.length > 0) {\n\t\t\telement = element[0];\n\t\t}\n\n\t\tvar watcher = new ElementWatcher( element, offsets );\n\t\twatchers.push(watcher);\n\t\twatcher.update();\n\t\treturn watcher;\n\t};\n\n\texports.update = function() {\n\t\tlatestEvent = null;\n\t\tcalculateViewport();\n\t\tupdateAndTriggerWatchers();\n\t};\n\texports.recalculateLocations = function() {\n\t\texports.documentHeight = 0;\n\t\texports.update();\n\t};\n\n\treturn exports;\n});\n\n},{}],6:[function(require,module,exports){\nmodule.exports={\n \"name\": \"clappr\",\n \"version\": \"0.0.86\",\n \"description\": \"An extensible media player for the web\",\n \"main\": \"dist/clappr.min.js\",\n \"scripts\": {\n \"test\": \"./node_modules/.bin/gulp release && ./node_modules/.bin/karma start --single-run --browsers Firefox\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git@github.com:globocom/clappr.git\"\n },\n \"author\": \"Globo.com\",\n \"license\": \"BSD\",\n \"bugs\": {\n \"url\": \"https://github.com/globocom/clappr/issues\"\n },\n \"browser\": {\n \"zepto\": \"clappr-zepto\"\n },\n \"homepage\": \"https://github.com/globocom/clappr\",\n \"devDependencies\": {\n \"browserify\": \"^8.0.3\",\n \"chai\": \"1.10.0\",\n \"compass-mixins\": \"0.12.3\",\n \"dotenv\": \"^0.4.0\",\n \"es6ify\": \"~1.4.0\",\n \"exorcist\": \"^0.1.6\",\n \"express\": \"^4.6.1\",\n \"express-alias\": \"0.4.0\",\n \"glob\": \"^4.0.2\",\n \"gulp\": \"^3.8.1\",\n \"clappr-zepto\": \"0.0.3\",\n \"gulp-compressor\": \"^0.1.0\",\n \"gulp-jshint\": \"1.9.0\",\n \"gulp-livereload\": \"^2.1.0\",\n \"gulp-minify-css\": \"~0.3.5\",\n \"gulp-rename\": \"^1.2.0\",\n \"gulp-sass\": \"1.0.0\",\n \"gulp-streamify\": \"0.0.5\",\n \"gulp-uglify\": \"^1.0.1\",\n \"gulp-util\": \"3.0.1\",\n \"karma\": \"^0.12.17\",\n \"karma-browserify\": \"^1.0.0\",\n \"karma-chai\": \"^0.1.0\",\n \"karma-chrome-launcher\": \"^0.1.4\",\n \"karma-cli\": \"0.0.4\",\n \"karma-firefox-launcher\": \"^0.1.3\",\n \"karma-jasmine\": \"^0.2.2\",\n \"karma-jquery\": \"^0.1.0\",\n \"karma-mocha\": \"^0.1.4\",\n \"karma-safari-launcher\": \"^0.1.1\",\n \"karma-sinon\": \"^1.0.3\",\n \"karma-sinon-chai\": \"^0.2.0\",\n \"mkdirp\": \"^0.5.0\",\n \"s3\": \"^4.1.1\",\n \"scp\": \"0.0.3\",\n \"sinon\": \"^1.10.2\",\n \"traceur\": \"0.0.72\",\n \"vinyl-source-stream\": \"^1.0.0\",\n \"vinyl-transform\": \"0.0.1\",\n \"watchify\": \"^2.0.0\",\n \"yargs\": \"1.3.3\"\n },\n \"dependencies\": {\n \"underscore\": \"1.7.0\",\n \"mousetrap\": \"^1.4.6\",\n \"scrollmonitor\": \"^1.0.8\"\n }\n}\n\n},{}],7:[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nmodule.exports = {\n 'media_control': _.template('
<% var renderBar=function(name) { %>
>
>
>
>
>
>
>
<% }; %><% var renderSegmentedBar=function(name, segments) { segments=segments || 10; %>
><% for (var i = 0; i < segments; i++) { %>
>
<% } %>
<% }; %><% var renderDrawer=function(name, renderContent) { %>
>
>
>
>
<% renderContent(name); %>
<% }; %><% var renderIndicator=function(name) { %>
>
<% }; %><% var renderButton=function(name) { %><% }; %><% var templates={ bar: renderBar, segmentedBar: renderSegmentedBar, }; var render=function(settingsList) { _.each(settingsList, function(setting) { if(setting === \"seekbar\") { renderBar(setting); } else if (setting === \"volume\") { renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); }); } else if (setting === \"duration\" || setting=== \"position\") { renderIndicator(setting); } else { renderButton(setting); } }); }; %><% if (settings.default && settings.default.length) { %>
<% render(settings.default); %>
<% } %><% if (settings.left && settings.left.length) { %>
<% render(settings.left); %>
<% } %><% if (settings.right && settings.right.length) { %>
<% render(settings.right); %>
<% } %>
'),\n 'seek_time': _.template(''),\n 'flash': _.template('\">\" />\" src=\"<%= swfPath %>\">'),\n 'hls': _.template('?inline=1\">\" />\" src=\"<%= swfPath %>\" width=\"100%\" height=\"100%\">'),\n 'html5_video': _.template('\" type=\"<%=type%>\">'),\n 'no_op': _.template('

Something went wrong :(

'),\n 'background_button': _.template('
'),\n 'dvr_controls': _.template('
LIVE
'),\n 'poster': _.template('
'),\n 'spinner_three_bounce': _.template('
'),\n 'watermark': _.template('
>\">
'),\n CSS: {\n 'container': '.container[data-container]{position:absolute;background-color:#000;height:100%;width:100%}.container[data-container].pointer-enabled{cursor:pointer}',\n 'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;font-family:\"lucida grande\",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:\"\";content:none}[data-player] a img{border:none}[data-player] *{max-width:initial;box-sizing:inherit;float:initial}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}[data-player] .clappr-style{display:none!important}@media screen{[data-player]{opacity:.99}}',\n 'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format(\"embedded-opentype\"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format(\"truetype\"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format(\"svg\")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;width:100%;height:100%;z-index:9999;pointer-events:none}.media-control[data-media-control].dragging{pointer-events:auto;cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control].dragging *{cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:40%;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:opacity .6s;-webkit-transition-delay:ease-out;-moz-transition:opacity .6s ease-out;-o-transition:opacity .6s ease-out;transition:opacity .6s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.8) 0 0 5px}.media-control[data-media-control].media-control-hide .media-control-background[data-background]{opacity:0}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls]{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:absolute;bottom:7px;width:100%;height:32px;vertical-align:middle;pointer-events:auto;-webkit-transition:bottom .4s;-webkit-transition-delay:ease-out;-moz-transition:bottom .4s ease-out;-o-transition:bottom .4s ease-out;transition:bottom .4s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 6px;padding:0;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:\"\\\\e001\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:\"\\\\e002\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:\"\\\\e003\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:\"\\\\e006\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen].shrink:before{content:\"\\\\e007\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:\"\\\\e008\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover{opacity:1;text-shadow:none}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:\"\\\\e001\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:\"\\\\e002\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:\"\\\\e001\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:\"\\\\e001\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:\"\\\\e003\"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:\"\\\\e001\"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{margin-left:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.5);margin-right:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:\"|\";margin:0 3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5);-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;height:32px;cursor:pointer;margin:0 6px;box-sizing:border-box}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{float:left;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;box-sizing:content-box;width:16px;height:32px;margin-right:6px;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:\"\\\\e004\"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted{opacity:.5}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:hover{opacity:.7}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:\"\\\\e005\"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{float:left;position:relative;top:6px;width:42px;height:18px;padding:3px 0;overflow:hidden;-webkit-transition:width .2s;-webkit-transition-delay:ease-out;-moz-transition:width .2s ease-out;-o-transition:width .2s ease-out;transition:width .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]{float:left;width:4px;padding-left:2px;height:12px;opacity:.5;-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;-webkit-transition:-webkit-transform .2s;-webkit-transition-delay:ease-out;-moz-transition:-moz-transform .2s ease-out;-o-transition:-o-transform .2s ease-out;transition:transform .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill{-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1){padding-left:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover{-webkit-transform:scaleY(1.5);-moz-transform:scaleY(1.5);-ms-transform:scaleY(1.5);-o-transform:scaleY(1.5);transform:scaleY(1.5)}.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{height:12px;top:9px;padding:0;width:0}',\n 'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;line-height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}',\n 'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}',\n 'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}',\n 'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}',\n 'html_img': '[data-html-img]{max-width:100%;max-height:100%}',\n 'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}',\n 'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);pointer-events:none;-webkit-transition:all .4s;-webkit-transition-delay:ease-out;-moz-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.background-button[data-background-button].hide{background-color:transparent}.background-button[data-background-button].hide .background-button-wrapper[data-background-button]{opacity:0}.background-button[data-background-button] .background-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]{cursor:pointer;pointer-events:auto;font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;border:0;outline:0;background-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playing:before{content:\"\\\\e002\"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].notplaying:before{content:\"\\\\e001\"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.playing:before{content:\"\\\\e003\"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.notplaying:before{content:\"\\\\e001\"}.media-control.media-control-hide[data-media-control] .background-button[data-background-button]{opacity:0}',\n 'dvr_controls': '@import url(http://fonts.googleapis.com/css?family=Roboto);.dvr-controls[data-dvr-controls]{display:inline-block;float:left;color:#fff;line-height:32px;font-size:10px;font-weight:700;margin-left:6px}.dvr-controls[data-dvr-controls] .live-info{cursor:default;font-family:Roboto,\"Open Sans\",Arial,sans-serif}.dvr-controls[data-dvr-controls] .live-info:before{content:\"\";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#ff0101}.dvr-controls[data-dvr-controls] .live-info.disabled{opacity:.3}.dvr-controls[data-dvr-controls] .live-info.disabled:before{background-color:#fff}.dvr-controls[data-dvr-controls] .live-button{cursor:pointer;outline:0;display:none;border:0;color:#fff;background-color:transparent;height:32px;padding:0;opacity:.7;font-family:Roboto,\"Open Sans\",Arial,sans-serif;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.dvr-controls[data-dvr-controls] .live-button:before{content:\"\";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#fff}.dvr-controls[data-dvr-controls] .live-button:hover{opacity:1;text-shadow:rgba(255,255,255,.75) 0 0 5px}.dvr .dvr-controls[data-dvr-controls] .live-info{display:none}.dvr .dvr-controls[data-dvr-controls] .live-button{display:block}.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#005aff}.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#ff0101}.seek-time[data-seek-time] span[data-duration]{position:relative;color:rgba(255,255,255,.5);font-size:10px;padding-right:7px}.seek-time[data-seek-time] span[data-duration]:before{content:\"|\";margin-right:7px}',\n 'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format(\"embedded-opentype\"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format(\"truetype\"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format(\"svg\")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:opacity text-shadow;-webkit-transition-delay:.1s;-moz-transition:opacity text-shadow .1s;-o-transition:opacity text-shadow .1s;transition:opacity text-shadow .1s ease}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:\"\\\\e001\"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}',\n 'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:999;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}',\n 'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}'\n }\n};\n\n\n},{\"underscore\":\"underscore\"}],8:[function(require,module,exports){\n\"use strict\";\nvar $ = require('zepto');\nvar _ = require('underscore');\nvar JST = require('./jst');\nvar Styler = {getStyleFor: function(name, options) {\n options = options || {};\n return $('').html(_.template(JST.CSS[name])(options))[0];\n }};\nmodule.exports = Styler;\n\n\n},{\"./jst\":7,\"underscore\":\"underscore\",\"zepto\":\"zepto\"}],9:[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nvar Browser = require('browser');\nvar extend = function(protoProps, staticProps) {\n var parent = this;\n var child;\n if (protoProps && _.has(protoProps, 'constructor')) {\n child = protoProps.constructor;\n } else {\n child = function() {\n return parent.apply(this, arguments);\n };\n }\n _.extend(child, parent, staticProps);\n var Surrogate = function() {\n this.constructor = child;\n };\n Surrogate.prototype = parent.prototype;\n child.prototype = new Surrogate();\n if (protoProps)\n _.extend(child.prototype, protoProps);\n child.__super__ = parent.prototype;\n child.super = function(name) {\n return parent.prototype[name];\n };\n child.prototype.getClass = function() {\n return child;\n };\n return child;\n};\nvar formatTime = function(time) {\n time = time * 1000;\n time = parseInt(time / 1000);\n var seconds = time % 60;\n time = parseInt(time / 60);\n var minutes = time % 60;\n time = parseInt(time / 60);\n var hours = time % 24;\n var out = \"\";\n if (hours && hours > 0)\n out += (\"0\" + hours).slice(-2) + \":\";\n out += (\"0\" + minutes).slice(-2) + \":\";\n out += (\"0\" + seconds).slice(-2);\n return out.trim();\n};\nvar Fullscreen = {\n isFullscreen: function() {\n return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement || window.iframeFullScreen;\n },\n requestFullscreen: function(el) {\n if (el.requestFullscreen) {\n el.requestFullscreen();\n } else if (el.webkitRequestFullscreen) {\n el.webkitRequestFullscreen();\n } else if (el.mozRequestFullScreen) {\n el.mozRequestFullScreen();\n } else if (el.msRequestFullscreen) {\n el.msRequestFullscreen();\n }\n },\n cancelFullscreen: function() {\n if (document.exitFullscreen) {\n document.exitFullscreen();\n } else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n } else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n } else if (document.msExitFullscreen) {\n document.msExitFullscreen();\n }\n }\n};\nvar Config = function Config() {};\n($traceurRuntime.createClass)(Config, {}, {\n _defaultConfig: function() {\n return {volume: {\n value: 100,\n parse: parseInt\n }};\n },\n _defaultValueFor: function(key) {\n try {\n return this._defaultConfig()[key]['parse'](this._defaultConfig()[key]['value']);\n } catch (e) {\n return undefined;\n }\n },\n _create_keyspace: function(key) {\n return 'clappr.' + document.domain + '.' + key;\n },\n restore: function(key) {\n if (Browser.hasLocalstorage && localStorage[this._create_keyspace(key)]) {\n return this._defaultConfig()[key]['parse'](localStorage[this._create_keyspace(key)]);\n }\n return this._defaultValueFor(key);\n },\n persist: function(key, value) {\n if (Browser.hasLocalstorage) {\n try {\n localStorage[this._create_keyspace(key)] = value;\n return true;\n } catch (e) {\n return false;\n }\n }\n }\n});\nvar seekStringToSeconds = function(url) {\n var elements = _.rest(_.compact(url.match(/t=([0-9]*)h?([0-9]*)m?([0-9]*)s/))).reverse();\n var seconds = 0;\n var factor = 1;\n _.each(elements, function(el) {\n seconds += (parseInt(el) * factor);\n factor = factor * 60;\n }, this);\n return seconds;\n};\nmodule.exports = {\n extend: extend,\n formatTime: formatTime,\n Fullscreen: Fullscreen,\n Config: Config,\n seekStringToSeconds: seekStringToSeconds\n};\n\n\n},{\"browser\":\"browser\",\"underscore\":\"underscore\"}],10:[function(require,module,exports){\n\"use strict\";\nvar UIObject = require('ui_object');\nvar Styler = require('../../base/styler');\nvar _ = require('underscore');\nvar Events = require('events');\nvar Container = function Container(options) {\n $traceurRuntime.superCall(this, $Container.prototype, \"constructor\", [options]);\n this.playback = options.playback;\n this.settings = this.playback.settings;\n this.isReady = false;\n this.mediaControlDisabled = false;\n this.plugins = [this.playback];\n this.bindEvents();\n};\nvar $Container = Container;\n($traceurRuntime.createClass)(Container, {\n get name() {\n return 'Container';\n },\n get attributes() {\n return {\n class: 'container',\n 'data-container': ''\n };\n },\n get events() {\n return {'click': 'clicked'};\n },\n bindEvents: function() {\n this.listenTo(this.playback, Events.PLAYBACK_PROGRESS, this.progress);\n this.listenTo(this.playback, Events.PLAYBACK_TIMEUPDATE, this.timeUpdated);\n this.listenTo(this.playback, Events.PLAYBACK_READY, this.ready);\n this.listenTo(this.playback, Events.PLAYBACK_BUFFERING, this.buffering);\n this.listenTo(this.playback, Events.PLAYBACK_BUFFERFULL, this.bufferfull);\n this.listenTo(this.playback, Events.PLAYBACK_SETTINGSUPDATE, this.settingsUpdate);\n this.listenTo(this.playback, Events.PLAYBACK_LOADEDMETADATA, this.loadedMetadata);\n this.listenTo(this.playback, Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);\n this.listenTo(this.playback, Events.PLAYBACK_BITRATE, this.updateBitrate);\n this.listenTo(this.playback, Events.PLAYBACK_PLAYBACKSTATE, this.playbackStateChanged);\n this.listenTo(this.playback, Events.PLAYBACK_DVR, this.playbackDvrStateChanged);\n this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_DISABLE, this.disableMediaControl);\n this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_ENABLE, this.enableMediaControl);\n this.listenTo(this.playback, Events.PLAYBACK_ENDED, this.ended);\n this.listenTo(this.playback, Events.PLAYBACK_PLAY, this.playing);\n this.listenTo(this.playback, Events.PLAYBACK_ERROR, this.error);\n },\n with: function(klass) {\n _.extend(this, klass);\n return this;\n },\n playbackStateChanged: function() {\n this.trigger(Events.CONTAINER_PLAYBACKSTATE);\n },\n playbackDvrStateChanged: function(dvrInUse) {\n this.settings = this.playback.settings;\n this.dvrInUse = dvrInUse;\n this.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, dvrInUse);\n },\n updateBitrate: function(newBitrate) {\n this.trigger(Events.CONTAINER_BITRATE, newBitrate);\n },\n statsReport: function(metrics) {\n this.trigger(Events.CONTAINER_STATS_REPORT, metrics);\n },\n getPlaybackType: function() {\n return this.playback.getPlaybackType();\n },\n isDvrEnabled: function() {\n return !!this.playback.dvrEnabled;\n },\n isDvrInUse: function() {\n return !!this.dvrInUse;\n },\n destroy: function() {\n this.trigger(Events.CONTAINER_DESTROYED, this, this.name);\n this.playback.destroy();\n _(this.plugins).each((function(plugin) {\n return plugin.destroy();\n }));\n this.$el.remove();\n },\n setStyle: function(style) {\n this.$el.css(style);\n },\n animate: function(style, duration) {\n return this.$el.animate(style, duration).promise();\n },\n ready: function() {\n this.isReady = true;\n this.trigger(Events.CONTAINER_READY, this.name);\n },\n isPlaying: function() {\n return this.playback.isPlaying();\n },\n getDuration: function() {\n return this.playback.getDuration();\n },\n error: function(errorObj) {\n this.$el.append(errorObj.render().el);\n this.trigger(Events.CONTAINER_ERROR, {\n error: errorObj,\n container: this\n }, this.name);\n },\n loadedMetadata: function(duration) {\n this.trigger(Events.CONTAINER_LOADEDMETADATA, duration);\n },\n timeUpdated: function(position, duration) {\n this.trigger(Events.CONTAINER_TIMEUPDATE, position, duration, this.name);\n },\n progress: function(startPosition, endPosition, duration) {\n this.trigger(Events.CONTAINER_PROGRESS, startPosition, endPosition, duration, this.name);\n },\n playing: function() {\n this.trigger(Events.CONTAINER_PLAY, this.name);\n },\n play: function() {\n this.playback.play();\n },\n stop: function() {\n this.trigger(Events.CONTAINER_STOP, this.name);\n this.playback.stop();\n },\n pause: function() {\n this.trigger(Events.CONTAINER_PAUSE, this.name);\n this.playback.pause();\n },\n ended: function() {\n this.trigger(Events.CONTAINER_ENDED, this, this.name);\n },\n clicked: function() {\n this.trigger(Events.CONTAINER_CLICK, this, this.name);\n },\n setCurrentTime: function(time) {\n this.trigger(Events.CONTAINER_SEEK, time, this.name);\n this.playback.seek(time);\n },\n setVolume: function(value) {\n this.trigger(Events.CONTAINER_VOLUME, value, this.name);\n this.playback.volume(value);\n },\n fullscreen: function() {\n this.trigger(Events.CONTAINER_FULLSCREEN, this.name);\n },\n buffering: function() {\n this.trigger(Events.CONTAINER_STATE_BUFFERING, this.name);\n },\n bufferfull: function() {\n this.trigger(Events.CONTAINER_STATE_BUFFERFULL, this.name);\n },\n addPlugin: function(plugin) {\n this.plugins.push(plugin);\n },\n hasPlugin: function(name) {\n return !!this.getPlugin(name);\n },\n getPlugin: function(name) {\n return _(this.plugins).find(function(plugin) {\n return plugin.name === name;\n });\n },\n settingsUpdate: function() {\n this.settings = this.playback.settings;\n this.trigger(Events.CONTAINER_SETTINGSUPDATE);\n },\n highDefinitionUpdate: function() {\n this.trigger(Events.CONTAINER_HIGHDEFINITIONUPDATE);\n },\n isHighDefinitionInUse: function() {\n return this.playback.isHighDefinitionInUse();\n },\n disableMediaControl: function() {\n this.mediaControlDisabled = true;\n this.trigger(Events.CONTAINER_MEDIACONTROL_DISABLE);\n },\n enableMediaControl: function() {\n this.mediaControlDisabled = false;\n this.trigger(Events.CONTAINER_MEDIACONTROL_ENABLE);\n },\n render: function() {\n var style = Styler.getStyleFor('container');\n this.$el.append(style);\n this.$el.append(this.playback.render().el);\n return this;\n }\n}, {}, UIObject);\nmodule.exports = Container;\n\n\n},{\"../../base/styler\":8,\"events\":\"events\",\"ui_object\":\"ui_object\",\"underscore\":\"underscore\"}],11:[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nvar BaseObject = require('base_object');\nvar Container = require('container');\nvar $ = require('zepto');\nvar Events = require('events');\nvar ContainerFactory = function ContainerFactory(options, loader) {\n $traceurRuntime.superCall(this, $ContainerFactory.prototype, \"constructor\", [options]);\n this.options = options;\n this.loader = loader;\n};\nvar $ContainerFactory = ContainerFactory;\n($traceurRuntime.createClass)(ContainerFactory, {\n createContainers: function() {\n var $__0 = this;\n return $.Deferred((function(promise) {\n promise.resolve(_.map($__0.options.sources, (function(source) {\n return $__0.createContainer(source);\n }), $__0));\n }));\n },\n findPlaybackPlugin: function(source) {\n return _.find(this.loader.playbackPlugins, (function(p) {\n return p.canPlay(source.toString());\n }), this);\n },\n createContainer: function(source) {\n var playbackPlugin = this.findPlaybackPlugin(source);\n var options = _.extend({}, this.options, {\n src: source,\n autoPlay: !!this.options.autoPlay\n });\n var playback = new playbackPlugin(options);\n var container = new Container({playback: playback});\n var defer = $.Deferred();\n defer.promise(container);\n this.addContainerPlugins(container, source);\n this.listenToOnce(container, Events.CONTAINER_READY, (function() {\n return defer.resolve(container);\n }));\n return container;\n },\n addContainerPlugins: function(container, source) {\n _.each(this.loader.containerPlugins, function(Plugin) {\n var options = _.extend(this.options, {\n container: container,\n src: source\n });\n container.addPlugin(new Plugin(options));\n }, this);\n }\n}, {}, BaseObject);\nmodule.exports = ContainerFactory;\n\n\n},{\"base_object\":\"base_object\",\"container\":\"container\",\"events\":\"events\",\"underscore\":\"underscore\",\"zepto\":\"zepto\"}],12:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./container_factory');\n\n\n},{\"./container_factory\":11}],13:[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nvar $ = require('zepto');\nvar UIObject = require('ui_object');\nvar ContainerFactory = require('../container_factory');\nvar Fullscreen = require('../../base/utils').Fullscreen;\nvar Styler = require('../../base/styler');\nvar MediaControl = require('media_control');\nvar PlayerInfo = require('player_info');\nvar Mediator = require('mediator');\nvar Events = require('events');\nvar Core = function Core(options) {\n var $__0 = this;\n $traceurRuntime.superCall(this, $Core.prototype, \"constructor\", [options]);\n PlayerInfo.options = options;\n this.options = options;\n this.plugins = [];\n this.containers = [];\n this.createContainers(options);\n $(document).bind('fullscreenchange', (function() {\n return $__0.exit();\n }));\n $(document).bind('MSFullscreenChange', (function() {\n return $__0.exit();\n }));\n $(document).bind('mozfullscreenchange', (function() {\n return $__0.exit();\n }));\n};\nvar $Core = Core;\n($traceurRuntime.createClass)(Core, {\n get events() {\n return {\n 'webkitfullscreenchange': 'exit',\n 'mousemove': 'showMediaControl',\n 'mouseleave': 'hideMediaControl'\n };\n },\n get attributes() {\n return {'data-player': ''};\n },\n createContainers: function(options) {\n var $__0 = this;\n this.defer = $.Deferred();\n this.defer.promise(this);\n this.containerFactory = new ContainerFactory(options, options.loader);\n this.containerFactory.createContainers().then((function(containers) {\n return $__0.setupContainers(containers);\n })).then((function(containers) {\n return $__0.resolveOnContainersReady(containers);\n }));\n },\n updateSize: function() {\n if (Fullscreen.isFullscreen()) {\n this.setFullscreen();\n } else {\n this.setPlayerSize();\n }\n Mediator.trigger(Events.PLAYER_RESIZE);\n },\n setFullscreen: function() {\n this.$el.addClass('fullscreen');\n this.$el.removeAttr('style');\n PlayerInfo.previousSize = PlayerInfo.currentSize;\n PlayerInfo.currentSize = {\n width: $(window).width(),\n height: $(window).height()\n };\n },\n setPlayerSize: function() {\n this.$el.removeClass('fullscreen');\n PlayerInfo.currentSize = PlayerInfo.previousSize;\n PlayerInfo.previousSize = {\n width: $(window).width(),\n height: $(window).height()\n };\n this.resize(PlayerInfo.currentSize);\n },\n resize: function(options) {\n var size = _.pick(options, 'width', 'height');\n this.el.style.height = (size.height + \"px\");\n this.el.style.width = (size.width + \"px\");\n PlayerInfo.previousSize = PlayerInfo.currentSize;\n PlayerInfo.currentSize = size;\n Mediator.trigger(Events.PLAYER_RESIZE);\n },\n resolveOnContainersReady: function(containers) {\n var $__0 = this;\n $.when.apply($, containers).done((function() {\n return $__0.defer.resolve($__0);\n }));\n },\n addPlugin: function(plugin) {\n this.plugins.push(plugin);\n },\n hasPlugin: function(name) {\n return !!this.getPlugin(name);\n },\n getPlugin: function(name) {\n return _(this.plugins).find((function(plugin) {\n return plugin.name === name;\n }));\n },\n load: function(sources) {\n var $__0 = this;\n sources = _.isArray(sources) ? sources : [sources.toString()];\n _(this.containers).each((function(container) {\n return container.destroy();\n }));\n this.containerFactory.options = _(this.options).extend({sources: sources});\n this.containerFactory.createContainers().then((function(containers) {\n $__0.setupContainers(containers);\n }));\n },\n destroy: function() {\n _(this.containers).each((function(container) {\n return container.destroy();\n }));\n _(this.plugins).each((function(plugin) {\n return plugin.destroy();\n }));\n this.$el.remove();\n this.mediaControl.destroy();\n $(document).unbind('fullscreenchange');\n $(document).unbind('MSFullscreenChange');\n $(document).unbind('mozfullscreenchange');\n },\n exit: function() {\n this.updateSize();\n this.mediaControl.show();\n },\n setMediaControlContainer: function(container) {\n this.mediaControl.setContainer(container);\n this.mediaControl.render();\n },\n disableMediaControl: function() {\n this.mediaControl.disable();\n this.$el.removeClass('nocursor');\n },\n enableMediaControl: function() {\n this.mediaControl.enable();\n },\n removeContainer: function(container) {\n this.stopListening(container);\n this.containers = _.without(this.containers, container);\n },\n appendContainer: function(container) {\n this.listenTo(container, Events.CONTAINER_DESTROYED, this.removeContainer);\n this.el.appendChild(container.render().el);\n this.containers.push(container);\n },\n setupContainers: function(containers) {\n _.map(containers, this.appendContainer, this);\n this.setupMediaControl(this.getCurrentContainer());\n this.render();\n this.$el.appendTo(this.options.parentElement);\n return containers;\n },\n createContainer: function(source) {\n var container = this.containerFactory.createContainer(source);\n this.appendContainer(container);\n return container;\n },\n setupMediaControl: function(container) {\n if (this.mediaControl) {\n this.mediaControl.setContainer(container);\n } else {\n this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options));\n this.listenTo(this.mediaControl, Events.MEDIACONTROL_FULLSCREEN, this.toggleFullscreen);\n this.listenTo(this.mediaControl, Events.MEDIACONTROL_SHOW, this.onMediaControlShow.bind(this, true));\n this.listenTo(this.mediaControl, Events.MEDIACONTROL_HIDE, this.onMediaControlShow.bind(this, false));\n }\n },\n createMediaControl: function(options) {\n if (options.mediacontrol && options.mediacontrol.external) {\n return new options.mediacontrol.external(options);\n } else {\n return new MediaControl(options);\n }\n },\n getCurrentContainer: function() {\n return this.containers[0];\n },\n toggleFullscreen: function() {\n if (!Fullscreen.isFullscreen()) {\n Fullscreen.requestFullscreen(this.el);\n this.$el.addClass('fullscreen');\n } else {\n Fullscreen.cancelFullscreen();\n this.$el.removeClass('fullscreen nocursor');\n }\n this.mediaControl.show();\n },\n showMediaControl: function(event) {\n this.mediaControl.show(event);\n },\n hideMediaControl: function(event) {\n this.mediaControl.hide(event);\n },\n onMediaControlShow: function(showing) {\n if (showing)\n this.$el.removeClass('nocursor');\n else if (Fullscreen.isFullscreen())\n this.$el.addClass('nocursor');\n },\n render: function() {\n var style = Styler.getStyleFor('core');\n this.$el.append(style);\n this.$el.append(this.mediaControl.render().el);\n this.options.width = this.options.width || this.$el.width();\n this.options.height = this.options.height || this.$el.height();\n PlayerInfo.previousSize = PlayerInfo.currentSize = _.pick(this.options, 'width', 'height');\n this.updateSize();\n return this;\n }\n}, {}, UIObject);\nmodule.exports = Core;\n\n\n},{\"../../base/styler\":8,\"../../base/utils\":9,\"../container_factory\":12,\"events\":\"events\",\"media_control\":\"media_control\",\"mediator\":\"mediator\",\"player_info\":\"player_info\",\"ui_object\":\"ui_object\",\"underscore\":\"underscore\",\"zepto\":\"zepto\"}],14:[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nvar BaseObject = require('base_object');\nvar Core = require('core');\nvar CoreFactory = function CoreFactory(player, loader) {\n this.player = player;\n this.options = player.options;\n this.loader = loader;\n this.options.loader = this.loader;\n};\n($traceurRuntime.createClass)(CoreFactory, {\n create: function() {\n this.core = new Core(this.options);\n this.core.then(this.addCorePlugins.bind(this));\n return this.core;\n },\n addCorePlugins: function() {\n _.each(this.loader.corePlugins, function(Plugin) {\n var plugin = new Plugin(this.core);\n this.core.addPlugin(plugin);\n this.setupExternalInterface(plugin);\n }, this);\n return this.core;\n },\n setupExternalInterface: function(plugin) {\n _.each(plugin.getExternalInterface(), function(value, key) {\n this.player[key] = value.bind(plugin);\n }, this);\n }\n}, {}, BaseObject);\nmodule.exports = CoreFactory;\n\n\n},{\"base_object\":\"base_object\",\"core\":\"core\",\"underscore\":\"underscore\"}],15:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./core_factory');\n\n\n},{\"./core_factory\":14}],16:[function(require,module,exports){\n\"use strict\";\nvar BaseObject = require('base_object');\nvar $ = require('zepto');\nvar Player = require('../player');\nvar IframePlayer = function IframePlayer(options) {\n $traceurRuntime.superCall(this, $IframePlayer.prototype, \"constructor\", [options]);\n this.options = options;\n this.createIframe();\n};\nvar $IframePlayer = IframePlayer;\n($traceurRuntime.createClass)(IframePlayer, {\n createIframe: function() {\n this.iframe = document.createElement(\"iframe\");\n this.iframe.setAttribute(\"frameborder\", 0);\n this.iframe.setAttribute(\"id\", this.uniqueId);\n this.iframe.setAttribute(\"allowfullscreen\", true);\n this.iframe.setAttribute(\"scrolling\", \"no\");\n this.iframe.setAttribute(\"src\", \"http://cdn.clappr.io/latest/assets/iframe.htm\" + this.buildQueryString());\n this.iframe.setAttribute('width', this.options.width);\n this.iframe.setAttribute('height', this.options.height);\n },\n attachTo: function(element) {\n element.appendChild(this.iframe);\n },\n addEventListeners: function() {\n var $__0 = this;\n this.iframe.contentWindow.addEventListener(\"fullscreenchange\", (function() {\n return $__0.updateSize();\n }));\n this.iframe.contentWindow.addEventListener(\"webkitfullscreenchange\", (function() {\n return $__0.updateSize();\n }));\n this.iframe.contentWindow.addEventListener(\"mozfullscreenchange\", (function() {\n return $__0.updateSize();\n }));\n },\n buildQueryString: function() {\n var result = \"\";\n for (var param in this.options) {\n result += !!result ? \"&\" : \"?\";\n result += encodeURIComponent(param) + \"=\" + encodeURIComponent(this.options[param]);\n }\n return result;\n }\n}, {}, BaseObject);\nmodule.exports = IframePlayer;\n\n\n},{\"../player\":21,\"base_object\":\"base_object\",\"zepto\":\"zepto\"}],17:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./iframe_player');\n\n\n},{\"./iframe_player\":16}],18:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./loader');\n\n\n},{\"./loader\":19}],19:[function(require,module,exports){\n\"use strict\";\nvar BaseObject = require('base_object');\nvar _ = require('underscore');\nvar PlayerInfo = require('player_info');\nvar HTML5VideoPlayback = require('html5_video');\nvar FlashVideoPlayback = require('flash');\nvar HTML5AudioPlayback = require('html5_audio');\nvar HLSVideoPlayback = require('hls');\nvar HTMLImgPlayback = require('html_img');\nvar NoOp = require('../../playbacks/no_op');\nvar SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce');\nvar StatsPlugin = require('../../plugins/stats');\nvar WaterMarkPlugin = require('../../plugins/watermark');\nvar PosterPlugin = require('poster');\nvar GoogleAnalyticsPlugin = require('../../plugins/google_analytics');\nvar ClickToPausePlugin = require('../../plugins/click_to_pause');\nvar BackgroundButton = require('../../plugins/background_button');\nvar DVRControls = require('../../plugins/dvr_controls');\nvar Loader = function Loader(externalPlugins) {\n $traceurRuntime.superCall(this, $Loader.prototype, \"constructor\", []);\n this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, HTMLImgPlayback, NoOp];\n this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin, GoogleAnalyticsPlugin, ClickToPausePlugin];\n this.corePlugins = [BackgroundButton, DVRControls];\n if (externalPlugins) {\n this.addExternalPlugins(externalPlugins);\n }\n};\nvar $Loader = Loader;\n($traceurRuntime.createClass)(Loader, {\n addExternalPlugins: function(plugins) {\n var pluginName = function(plugin) {\n return plugin.prototype.name;\n };\n if (plugins.playback) {\n this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName);\n }\n if (plugins.container) {\n this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName);\n }\n if (plugins.core) {\n this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName);\n }\n PlayerInfo.playbackPlugins = this.playbackPlugins;\n },\n getPlugin: function(name) {\n var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins);\n return _.find(allPlugins, function(plugin) {\n return plugin.prototype.name === name;\n });\n }\n}, {}, BaseObject);\nmodule.exports = Loader;\n\n\n},{\"../../playbacks/no_op\":29,\"../../plugins/background_button\":32,\"../../plugins/click_to_pause\":34,\"../../plugins/dvr_controls\":36,\"../../plugins/google_analytics\":38,\"../../plugins/spinner_three_bounce\":42,\"../../plugins/stats\":44,\"../../plugins/watermark\":46,\"base_object\":\"base_object\",\"flash\":\"flash\",\"hls\":\"hls\",\"html5_audio\":\"html5_audio\",\"html5_video\":\"html5_video\",\"html_img\":\"html_img\",\"player_info\":\"player_info\",\"poster\":\"poster\",\"underscore\":\"underscore\"}],20:[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nvar $ = require('zepto');\nvar JST = require('../../base/jst');\nvar Styler = require('../../base/styler');\nvar UIObject = require('ui_object');\nvar Utils = require('../../base/utils');\nvar SeekTime = require('../seek_time');\nvar Mediator = require('mediator');\nvar PlayerInfo = require('player_info');\nvar Events = require('events');\nrequire('mousetrap');\nvar MediaControl = function MediaControl(options) {\n var $__0 = this;\n $traceurRuntime.superCall(this, $MediaControl.prototype, \"constructor\", [options]);\n this.seekTime = new SeekTime(this);\n this.options = options;\n this.mute = this.options.mute;\n this.persistConfig = this.options.persistConfig;\n this.container = options.container;\n var initialVolume = (this.persistConfig) ? Utils.Config.restore(\"volume\") : 100;\n this.setVolume(this.mute ? 0 : initialVolume);\n this.keepVisible = false;\n this.addEventListeners();\n this.settings = {\n left: ['play', 'stop', 'pause'],\n right: ['volume'],\n default: ['position', 'seekbar', 'duration']\n };\n this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;\n this.disabled = false;\n if (this.container.mediaControlDisabled || this.options.chromeless) {\n this.disable();\n }\n $(document).bind('mouseup', (function(event) {\n return $__0.stopDrag(event);\n }));\n $(document).bind('mousemove', (function(event) {\n return $__0.updateDrag(event);\n }));\n Mediator.on(Events.PLAYER_RESIZE, (function() {\n return $__0.playerResize();\n }));\n};\nvar $MediaControl = MediaControl;\n($traceurRuntime.createClass)(MediaControl, {\n get name() {\n return 'MediaControl';\n },\n get attributes() {\n return {\n class: 'media-control',\n 'data-media-control': ''\n };\n },\n get events() {\n return {\n 'click [data-play]': 'play',\n 'click [data-pause]': 'pause',\n 'click [data-playpause]': 'togglePlayPause',\n 'click [data-stop]': 'stop',\n 'click [data-playstop]': 'togglePlayStop',\n 'click [data-fullscreen]': 'toggleFullscreen',\n 'click .bar-container[data-seekbar]': 'seek',\n 'click .bar-container[data-volume]': 'volume',\n 'click .drawer-icon[data-volume]': 'toggleMute',\n 'mouseenter .drawer-container[data-volume]': 'showVolumeBar',\n 'mouseleave .drawer-container[data-volume]': 'hideVolumeBar',\n 'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag',\n 'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag',\n 'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar',\n 'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar',\n 'mouseenter .media-control-layer[data-controls]': 'setKeepVisible',\n 'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible'\n };\n },\n get template() {\n return JST.media_control;\n },\n addEventListeners: function() {\n this.listenTo(this.container, Events.CONTAINER_PLAY, this.changeTogglePlay);\n this.listenTo(this.container, Events.CONTAINER_TIMEUPDATE, this.updateSeekBar);\n this.listenTo(this.container, Events.CONTAINER_PROGRESS, this.updateProgressBar);\n this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);\n this.listenTo(this.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate);\n this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);\n this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_DISABLE, this.disable);\n this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_ENABLE, this.enable);\n this.listenTo(this.container, Events.CONTAINER_ENDED, this.ended);\n },\n disable: function() {\n this.disabled = true;\n this.hide();\n this.$el.hide();\n },\n enable: function() {\n if (this.options.chromeless)\n return;\n this.disabled = false;\n this.show();\n },\n play: function() {\n this.container.play();\n },\n pause: function() {\n this.container.pause();\n },\n stop: function() {\n this.container.stop();\n },\n changeTogglePlay: function() {\n if (this.container.isPlaying()) {\n this.$playPauseToggle.removeClass('paused').addClass('playing');\n this.$playStopToggle.removeClass('stopped').addClass('playing');\n this.trigger(Events.MEDIACONTROL_PLAYING);\n } else {\n this.$playPauseToggle.removeClass('playing').addClass('paused');\n this.$playStopToggle.removeClass('playing').addClass('stopped');\n this.trigger(Events.MEDIACONTROL_NOTPLAYING);\n }\n },\n mousemoveOnSeekBar: function(event) {\n if (this.container.settings.seekEnabled) {\n var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2);\n this.$seekBarHover.css({left: offsetX});\n }\n this.trigger(Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, event);\n },\n mouseleaveOnSeekBar: function(event) {\n this.trigger(Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, event);\n },\n playerResize: function() {\n if (Utils.Fullscreen.isFullscreen()) {\n this.$fullscreenToggle.addClass('shrink');\n } else {\n this.$fullscreenToggle.removeClass('shrink');\n }\n this.$el.removeClass('w320');\n if (PlayerInfo.currentSize.width <= 320) {\n this.$el.addClass('w320');\n }\n },\n togglePlayPause: function() {\n if (this.container.isPlaying()) {\n this.container.pause();\n } else {\n this.container.play();\n }\n this.changeTogglePlay();\n },\n togglePlayStop: function() {\n if (this.container.isPlaying()) {\n this.container.stop();\n } else {\n this.container.play();\n }\n this.changeTogglePlay();\n },\n startSeekDrag: function(event) {\n if (!this.container.settings.seekEnabled)\n return;\n this.draggingSeekBar = true;\n this.$el.addClass('dragging');\n this.$seekBarLoaded.addClass('media-control-notransition');\n this.$seekBarPosition.addClass('media-control-notransition');\n this.$seekBarScrubber.addClass('media-control-notransition');\n if (event) {\n event.preventDefault();\n }\n },\n startVolumeDrag: function(event) {\n this.draggingVolumeBar = true;\n this.$el.addClass('dragging');\n if (event) {\n event.preventDefault();\n }\n },\n stopDrag: function(event) {\n if (this.draggingSeekBar) {\n this.seek(event);\n }\n this.$el.removeClass('dragging');\n this.$seekBarLoaded.removeClass('media-control-notransition');\n this.$seekBarPosition.removeClass('media-control-notransition');\n this.$seekBarScrubber.removeClass('media-control-notransition dragging');\n this.draggingSeekBar = false;\n this.draggingVolumeBar = false;\n },\n updateDrag: function(event) {\n if (event) {\n event.preventDefault();\n }\n if (this.draggingSeekBar) {\n var offsetX = event.pageX - this.$seekBarContainer.offset().left;\n var pos = offsetX / this.$seekBarContainer.width() * 100;\n pos = Math.min(100, Math.max(pos, 0));\n this.setSeekPercentage(pos);\n } else if (this.draggingVolumeBar) {\n this.volume(event);\n }\n },\n volume: function(event) {\n var offsetY = event.pageX - this.$volumeBarContainer.offset().left;\n var volumeFromUI = (offsetY / this.$volumeBarContainer.width()) * 100;\n this.setVolume(volumeFromUI);\n },\n toggleMute: function() {\n if (this.mute) {\n if (this.currentVolume <= 0) {\n this.currentVolume = 100;\n }\n this.setVolume(this.currentVolume);\n } else {\n this.setVolume(0);\n }\n },\n setVolume: function(value) {\n this.currentVolume = Math.min(100, Math.max(value, 0));\n this.container.setVolume(this.currentVolume);\n this.setVolumeLevel(this.currentVolume);\n this.mute = this.currentVolume === 0;\n this.persistConfig && Utils.Config.persist(\"volume\", this.currentVolume);\n },\n toggleFullscreen: function() {\n this.trigger(Events.MEDIACONTROL_FULLSCREEN, this.name);\n this.container.fullscreen();\n this.resetKeepVisible();\n },\n setContainer: function(container) {\n this.stopListening(this.container);\n this.container = container;\n this.changeTogglePlay();\n this.addEventListeners();\n this.settingsUpdate();\n this.container.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.container.isDvrInUse());\n this.setVolume(this.currentVolume);\n if (this.container.mediaControlDisabled) {\n this.disable();\n }\n this.trigger(Events.MEDIACONTROL_CONTAINERCHANGED);\n },\n showVolumeBar: function() {\n if (this.hideVolumeId) {\n clearTimeout(this.hideVolumeId);\n }\n this.$volumeBarContainer.removeClass('volume-bar-hide');\n },\n hideVolumeBar: function() {\n var $__0 = this;\n var timeout = 400;\n if (!this.$volumeBarContainer)\n return;\n if (this.draggingVolumeBar) {\n this.hideVolumeId = setTimeout((function() {\n return $__0.hideVolumeBar();\n }), timeout);\n } else {\n if (this.hideVolumeId) {\n clearTimeout(this.hideVolumeId);\n }\n this.hideVolumeId = setTimeout((function() {\n return $__0.$volumeBarContainer.addClass('volume-bar-hide');\n }), timeout);\n }\n },\n ended: function() {\n this.changeTogglePlay();\n },\n updateProgressBar: function(startPosition, endPosition, duration) {\n var loadedStart = startPosition / duration * 100;\n var loadedEnd = endPosition / duration * 100;\n this.$seekBarLoaded.css({\n left: loadedStart + '%',\n width: (loadedEnd - loadedStart) + '%'\n });\n },\n updateSeekBar: function(position, duration) {\n if (this.draggingSeekBar)\n return;\n if (position < 0)\n position = duration;\n this.$seekBarPosition.removeClass('media-control-notransition');\n this.$seekBarScrubber.removeClass('media-control-notransition');\n var seekbarValue = (100 / duration) * position;\n this.setSeekPercentage(seekbarValue);\n this.$('[data-position]').html(Utils.formatTime(position));\n this.$('[data-duration]').html(Utils.formatTime(duration));\n },\n seek: function(event) {\n if (!this.container.settings.seekEnabled)\n return;\n var offsetX = event.pageX - this.$seekBarContainer.offset().left;\n var pos = offsetX / this.$seekBarContainer.width() * 100;\n pos = Math.min(100, Math.max(pos, 0));\n this.container.setCurrentTime(pos);\n this.setSeekPercentage(pos);\n return false;\n },\n setKeepVisible: function() {\n this.keepVisible = true;\n },\n resetKeepVisible: function() {\n this.keepVisible = false;\n },\n isVisible: function() {\n return !this.$el.hasClass('media-control-hide');\n },\n show: function(event) {\n var $__0 = this;\n if (this.disabled || this.container.getPlaybackType() === null)\n return;\n var timeout = 2000;\n if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) {\n clearTimeout(this.hideId);\n this.$el.show();\n this.trigger(Events.MEDIACONTROL_SHOW, this.name);\n this.$el.removeClass('media-control-hide');\n this.hideId = setTimeout((function() {\n return $__0.hide();\n }), timeout);\n if (event) {\n this.lastMouseX = event.clientX;\n this.lastMouseY = event.clientY;\n }\n }\n },\n hide: function() {\n var $__0 = this;\n var timeout = 2000;\n clearTimeout(this.hideId);\n if (!this.isVisible() || this.options.hideMediaControl === false)\n return;\n if (this.keepVisible || this.draggingSeekBar || this.draggingVolumeBar) {\n this.hideId = setTimeout((function() {\n return $__0.hide();\n }), timeout);\n } else {\n this.trigger(Events.MEDIACONTROL_HIDE, this.name);\n this.$el.addClass('media-control-hide');\n this.hideVolumeBar();\n }\n },\n settingsUpdate: function() {\n if (this.container.getPlaybackType() !== null && !_.isEmpty(this.container.settings)) {\n this.settings = this.container.settings;\n this.render();\n this.enable();\n } else {\n this.disable();\n }\n },\n highDefinitionUpdate: function() {\n if (this.container.isHighDefinitionInUse()) {\n this.$el.find('button[data-hd-indicator]').addClass(\"enabled\");\n } else {\n this.$el.find('button[data-hd-indicator]').removeClass(\"enabled\");\n }\n },\n createCachedElements: function() {\n this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]');\n this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]');\n this.$fullscreenToggle = this.$el.find('button.media-control-button[data-fullscreen]');\n this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]');\n this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]');\n this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]');\n this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]');\n this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]');\n this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]');\n this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]');\n },\n setVolumeLevel: function(value) {\n var $__0 = this;\n if (!this.container.isReady || !this.$volumeBarContainer) {\n this.listenToOnce(this.container, Events.CONTAINER_READY, (function() {\n return $__0.setVolumeLevel(value);\n }));\n } else {\n this.$volumeBarContainer.find('.segmented-bar-element').removeClass('fill');\n var item = Math.ceil(value / 10.0);\n this.$volumeBarContainer.find('.segmented-bar-element').slice(0, item).addClass('fill');\n if (value > 0) {\n this.$volumeIcon.removeClass('muted');\n } else {\n this.$volumeIcon.addClass('muted');\n }\n }\n },\n setSeekPercentage: function(value) {\n if (value > 100)\n return;\n var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0);\n this.currentSeekPercentage = value;\n this.$seekBarPosition.css({width: value + '%'});\n this.$seekBarScrubber.css({left: pos});\n },\n bindKeyEvents: function() {\n var $__0 = this;\n Mousetrap.bind(['space'], (function() {\n return $__0.togglePlayPause();\n }));\n },\n unbindKeyEvents: function() {\n Mousetrap.unbind('space');\n },\n parseColors: function() {\n if (this.options.mediacontrol) {\n var buttonsColor = this.options.mediacontrol.buttons;\n var seekbarColor = this.options.mediacontrol.seekbar;\n this.$el.find('.bar-fill-2[data-seekbar]').css('background-color', seekbarColor);\n this.$el.find('[data-media-control] > .media-control-icon, .drawer-icon').css('color', buttonsColor);\n this.$el.find('.segmented-bar-element[data-volume]').css('boxShadow', \"inset 2px 0 0 \" + buttonsColor);\n }\n },\n render: function() {\n var $__0 = this;\n var timeout = 1000;\n var style = Styler.getStyleFor('media_control');\n this.$el.html(this.template({settings: this.settings}));\n this.$el.append(style);\n this.createCachedElements();\n this.$playPauseToggle.addClass('paused');\n this.$playStopToggle.addClass('stopped');\n this.changeTogglePlay();\n this.hideId = setTimeout((function() {\n return $__0.hide();\n }), timeout);\n if (this.disabled) {\n this.hide();\n }\n this.$seekBarPosition.addClass('media-control-notransition');\n this.$seekBarScrubber.addClass('media-control-notransition');\n if (!this.currentSeekPercentage) {\n this.currentSeekPercentage = 0;\n }\n this.setSeekPercentage(this.currentSeekPercentage);\n this.$el.ready((function() {\n if (!$__0.container.settings.seekEnabled) {\n $__0.$seekBarContainer.addClass('seek-disabled');\n }\n $__0.setVolume($__0.currentVolume);\n $__0.bindKeyEvents();\n $__0.hideVolumeBar();\n }));\n this.parseColors();\n this.seekTime.render();\n this.trigger(Events.MEDIACONTROL_RENDERED);\n return this;\n },\n destroy: function() {\n $(document).unbind('mouseup');\n $(document).unbind('mousemove');\n this.unbindKeyEvents();\n }\n}, {}, UIObject);\nmodule.exports = MediaControl;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"../../base/utils\":9,\"../seek_time\":22,\"events\":\"events\",\"mediator\":\"mediator\",\"mousetrap\":4,\"player_info\":\"player_info\",\"ui_object\":\"ui_object\",\"underscore\":\"underscore\",\"zepto\":\"zepto\"}],21:[function(require,module,exports){\n\"use strict\";\nvar BaseObject = require('base_object');\nvar CoreFactory = require('./core_factory');\nvar Loader = require('./loader');\nvar _ = require('underscore');\nvar ScrollMonitor = require('scrollmonitor');\nvar PlayerInfo = require('player_info');\nvar Player = function Player(options) {\n $traceurRuntime.superCall(this, $Player.prototype, \"constructor\", [options]);\n window.p = this;\n var defaultOptions = {\n persistConfig: true,\n width: 640,\n height: 360\n };\n this.options = _.extend(defaultOptions, options);\n this.options.sources = this.normalizeSources(options);\n this.loader = new Loader(this.options.plugins || {});\n this.coreFactory = new CoreFactory(this, this.loader);\n PlayerInfo.currentSize = {\n width: options.width,\n height: options.height\n };\n if (this.options.parentId) {\n this.setParentId(this.options.parentId);\n }\n};\nvar $Player = Player;\n($traceurRuntime.createClass)(Player, {\n setParentId: function(parentId) {\n var el = document.querySelector(parentId);\n if (el) {\n this.attachTo(el);\n }\n },\n attachTo: function(element) {\n this.options.parentElement = element;\n this.core = this.coreFactory.create();\n if (this.options.autoPlayVisible) {\n this.bindAutoPlayVisible(this.options.autoPlayVisible);\n }\n },\n bindAutoPlayVisible: function(option) {\n var $__0 = this;\n this.elementWatcher = ScrollMonitor.create(this.core.$el);\n if (option === 'full') {\n this.elementWatcher.fullyEnterViewport((function() {\n return $__0.enterViewport();\n }));\n } else if (option === 'partial') {\n this.elementWatcher.enterViewport((function() {\n return $__0.enterViewport();\n }));\n }\n },\n enterViewport: function() {\n if (this.elementWatcher.top !== 0 && !this.isPlaying()) {\n this.play();\n }\n },\n normalizeSources: function(options) {\n var sources = _.compact(_.flatten([options.source, options.sources]));\n return _.isEmpty(sources) ? ['no.op'] : sources;\n },\n resize: function(size) {\n this.core.resize(size);\n },\n load: function(sources) {\n this.core.load(sources);\n },\n destroy: function() {\n this.core.destroy();\n },\n play: function() {\n this.core.mediaControl.container.play();\n },\n pause: function() {\n this.core.mediaControl.container.pause();\n },\n stop: function() {\n this.core.mediaControl.container.stop();\n },\n seek: function(time) {\n this.core.mediaControl.container.setCurrentTime(time);\n },\n setVolume: function(volume) {\n this.core.mediaControl.container.setVolume(volume);\n },\n mute: function() {\n this.core.mediaControl.container.setVolume(0);\n },\n unmute: function() {\n this.core.mediaControl.container.setVolume(100);\n },\n isPlaying: function() {\n return this.core.mediaControl.container.isPlaying();\n }\n}, {}, BaseObject);\nmodule.exports = Player;\n\n\n},{\"./core_factory\":15,\"./loader\":18,\"base_object\":\"base_object\",\"player_info\":\"player_info\",\"scrollmonitor\":5,\"underscore\":\"underscore\"}],22:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./seek_time');\n\n\n},{\"./seek_time\":23}],23:[function(require,module,exports){\n\"use strict\";\nvar UIObject = require('ui_object');\nvar Styler = require('../../base/styler');\nvar JST = require('../../base/jst');\nvar formatTime = require('../../base/utils').formatTime;\nvar Events = require('events');\nvar SeekTime = function SeekTime(mediaControl) {\n $traceurRuntime.superCall(this, $SeekTime.prototype, \"constructor\", []);\n this.mediaControl = mediaControl;\n this.addEventListeners();\n};\nvar $SeekTime = SeekTime;\n($traceurRuntime.createClass)(SeekTime, {\n get name() {\n return 'seek_time';\n },\n get template() {\n return JST.seek_time;\n },\n get attributes() {\n return {\n 'class': 'seek-time hidden',\n 'data-seek-time': ''\n };\n },\n addEventListeners: function() {\n this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, this.showTime);\n this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, this.hideTime);\n },\n showTime: function(event) {\n var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left;\n var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0));\n var pointerPosition = event.pageX - this.mediaControl.$el.offset().left - (this.$el.width() / 2);\n pointerPosition = Math.min(Math.max(0, pointerPosition), this.mediaControl.$el.width() - this.$el.width());\n var currentTime = timePosition * this.mediaControl.container.getDuration() / 100;\n var options = {\n timestamp: currentTime,\n formattedTime: formatTime(currentTime),\n pointerPosition: pointerPosition\n };\n this.update(options);\n },\n hideTime: function() {\n this.$el.addClass('hidden');\n this.$el.css('left', '-100%');\n },\n update: function(options) {\n if (this.mediaControl.container.getPlaybackType() === 'vod' || this.mediaControl.container.isDvrInUse()) {\n this.$el.find('[data-seek-time]').text(options.formattedTime);\n this.$el.css('left', options.pointerPosition);\n this.$el.removeClass('hidden');\n }\n },\n render: function() {\n var style = Styler.getStyleFor(this.name);\n this.$el.html(this.template());\n this.$el.append(style);\n this.mediaControl.$el.append(this.el);\n }\n}, {}, UIObject);\nmodule.exports = SeekTime;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"../../base/utils\":9,\"events\":\"events\",\"ui_object\":\"ui_object\"}],24:[function(require,module,exports){\n\"use strict\";\nvar Playback = require('playback');\nvar Styler = require('../../base/styler');\nvar JST = require('../../base/jst');\nvar Mediator = require('mediator');\nvar _ = require('underscore');\nvar $ = require('zepto');\nvar Browser = require('browser');\nvar seekStringToSeconds = require('../../base/utils').seekStringToSeconds;\nvar Events = require('events');\nrequire('mousetrap');\nvar objectIE = '\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" data-flash-vod=\"\">\"> \" /> ';\nvar Flash = function Flash(options) {\n $traceurRuntime.superCall(this, $Flash.prototype, \"constructor\", [options]);\n this.src = options.src;\n this.defaultBaseSwfPath = \"http://cdn.clappr.io/\" + Clappr.version + \"/assets/\";\n this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + \"Player.swf\";\n this.autoPlay = options.autoPlay;\n this.settings = {default: ['seekbar']};\n this.settings.left = [\"playpause\", \"position\", \"duration\"];\n this.settings.right = [\"fullscreen\", \"volume\"];\n this.settings.seekEnabled = true;\n this.isReady = false;\n this.addListeners();\n};\nvar $Flash = Flash;\n($traceurRuntime.createClass)(Flash, {\n get name() {\n return 'flash';\n },\n get tagName() {\n return 'object';\n },\n get template() {\n return JST.flash;\n },\n bootstrap: function() {\n this.el.width = \"100%\";\n this.el.height = \"100%\";\n this.isReady = true;\n if (this.currentState === 'PLAYING') {\n this.firstPlay();\n } else {\n this.currentState = \"IDLE\";\n this.autoPlay && this.play();\n }\n $('
').insertAfter(this.$el);\n this.trigger(Events.PLAYBACK_READY, this.name);\n },\n getPlaybackType: function() {\n return 'vod';\n },\n setupFirefox: function() {\n var $el = this.$('embed');\n $el.attr('data-flash', '');\n this.setElement($el[0]);\n },\n isHighDefinitionInUse: function() {\n return false;\n },\n updateTime: function() {\n this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.getPosition(), this.el.getDuration(), this.name);\n },\n addListeners: function() {\n Mediator.on(this.uniqueId + ':progress', this.progress, this);\n Mediator.on(this.uniqueId + ':timeupdate', this.updateTime, this);\n Mediator.on(this.uniqueId + ':statechanged', this.checkState, this);\n Mediator.on(this.uniqueId + ':flashready', this.bootstrap, this);\n _.each(_.range(1, 10), function(i) {\n var $__0 = this;\n Mousetrap.bind([i.toString()], (function() {\n return $__0.seek(i * 10);\n }));\n }.bind(this));\n },\n stopListening: function() {\n $traceurRuntime.superCall(this, $Flash.prototype, \"stopListening\", []);\n Mediator.off(this.uniqueId + ':progress');\n Mediator.off(this.uniqueId + ':timeupdate');\n Mediator.off(this.uniqueId + ':statechanged');\n Mediator.off(this.uniqueId + ':flashready');\n _.each(_.range(1, 10), function(i) {\n var $__0 = this;\n Mousetrap.unbind([i.toString()], (function() {\n return $__0.seek(i * 10);\n }));\n }.bind(this));\n },\n checkState: function() {\n if (this.currentState === \"PAUSED\") {\n return;\n } else if (this.currentState !== \"PLAYING_BUFFERING\" && this.el.getState() === \"PLAYING_BUFFERING\") {\n this.trigger(Events.PLAYBACK_BUFFERING, this.name);\n this.currentState = \"PLAYING_BUFFERING\";\n } else if (this.el.getState() === \"PLAYING\") {\n this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);\n this.currentState = \"PLAYING\";\n } else if (this.el.getState() === \"IDLE\") {\n this.currentState = \"IDLE\";\n } else if (this.el.getState() === \"ENDED\") {\n this.trigger(Events.PLAYBACK_ENDED, this.name);\n this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.getDuration(), this.name);\n this.currentState = \"ENDED\";\n }\n },\n progress: function() {\n if (this.currentState !== \"IDLE\" && this.currentState !== \"ENDED\") {\n this.trigger(Events.PLAYBACK_PROGRESS, 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name);\n }\n },\n firstPlay: function() {\n var $__0 = this;\n if (this.el.playerPlay) {\n this.el.playerPlay(this.src);\n this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {\n return $__0.checkInitialSeek();\n }));\n this.currentState = \"PLAYING\";\n } else {\n this.listenToOnce(this, Events.PLAYBACK_READY, this.firstPlay);\n }\n },\n checkInitialSeek: function() {\n var seekTime = seekStringToSeconds(window.location.href);\n if (seekTime !== 0) {\n this.seekSeconds(seekTime);\n }\n },\n play: function() {\n if (this.el.getState() === 'PAUSED' || this.el.getState() === 'PLAYING_BUFFERING') {\n this.currentState = \"PLAYING\";\n this.el.playerResume();\n } else if (this.el.getState() !== 'PLAYING') {\n this.firstPlay();\n }\n this.trigger(Events.PLAYBACK_PLAY, this.name);\n },\n volume: function(value) {\n var $__0 = this;\n if (this.isReady) {\n this.el.playerVolume(value);\n } else {\n this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {\n return $__0.volume(value);\n }));\n }\n },\n pause: function() {\n this.currentState = \"PAUSED\";\n this.el.playerPause();\n },\n stop: function() {\n this.el.playerStop();\n this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name);\n },\n isPlaying: function() {\n return !!(this.isReady && this.currentState.indexOf(\"PLAYING\") > -1);\n },\n getDuration: function() {\n return this.el.getDuration();\n },\n seek: function(seekBarValue) {\n var seekTo = this.el.getDuration() * (seekBarValue / 100);\n this.seekSeconds(seekTo);\n },\n seekSeconds: function(seekTo) {\n this.el.playerSeek(seekTo);\n this.trigger(Events.PLAYBACK_TIMEUPDATE, seekTo, this.el.getDuration(), this.name);\n if (this.currentState === \"PAUSED\") {\n this.el.playerPause();\n }\n },\n destroy: function() {\n clearInterval(this.bootstrapId);\n this.stopListening();\n this.$el.remove();\n },\n setupIE: function() {\n this.setElement($(_.template(objectIE)({\n cid: this.cid,\n swfPath: this.swfPath,\n playbackId: this.uniqueId\n })));\n },\n render: function() {\n var style = Styler.getStyleFor(this.name);\n this.$el.html(this.template({\n cid: this.cid,\n swfPath: this.swfPath,\n playbackId: this.uniqueId\n }));\n if (Browser.isFirefox) {\n this.setupFirefox();\n } else if (Browser.isLegacyIE) {\n this.setupIE();\n }\n this.$el.append(style);\n return this;\n }\n}, {}, Playback);\nFlash.canPlay = function(resource) {\n if ((!Browser.isMobile && Browser.isFirefox) || Browser.isLegacyIE) {\n return _.isString(resource) && !!resource.match(/(.*)\\.(mp4|mov|f4v|3gpp|3gp)/);\n } else {\n return _.isString(resource) && !!resource.match(/(.*)\\.(mov|f4v|3gpp|3gp)/);\n }\n};\nmodule.exports = Flash;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"../../base/utils\":9,\"browser\":\"browser\",\"events\":\"events\",\"mediator\":\"mediator\",\"mousetrap\":4,\"playback\":\"playback\",\"underscore\":\"underscore\",\"zepto\":\"zepto\"}],25:[function(require,module,exports){\n\"use strict\";\nvar Playback = require('playback');\nvar JST = require('../../base/jst');\nvar _ = require(\"underscore\");\nvar Mediator = require('mediator');\nvar Browser = require('browser');\nvar Events = require('events');\nvar objectIE = '\" class=\"hls-playback\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" data-hls=\"\" width=\"100%\" height=\"100%\">\"> \" /> ';\nvar HLS = function HLS(options) {\n $traceurRuntime.superCall(this, $HLS.prototype, \"constructor\", [options]);\n this.src = options.src;\n this.defaultBaseSwfPath = \"http://cdn.clappr.io/\" + Clappr.version + \"/assets/\";\n this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + \"HLSPlayer.swf\";\n this.flushLiveURLCache = (options.flushLiveURLCache === undefined) ? true : options.flushLiveURLCache;\n this.capLevelToStage = (options.capLevelToStage === undefined) ? false : options.capLevelToStage;\n this.highDefinition = false;\n this.autoPlay = options.autoPlay;\n this.defaultSettings = {\n left: [\"playstop\"],\n default: ['seekbar'],\n right: [\"fullscreen\", \"volume\", \"hd-indicator\"],\n seekEnabled: false\n };\n this.settings = _.extend({}, this.defaultSettings);\n this.playbackType = 'live';\n this.addListeners();\n};\nvar $HLS = HLS;\n($traceurRuntime.createClass)(HLS, {\n get name() {\n return 'hls';\n },\n get tagName() {\n return 'object';\n },\n get template() {\n return JST.hls;\n },\n get attributes() {\n return {\n 'class': 'hls-playback',\n 'data-hls': '',\n 'type': 'application/x-shockwave-flash',\n 'width': '100%',\n 'height': '100%'\n };\n },\n addListeners: function() {\n var $__0 = this;\n Mediator.on(this.uniqueId + ':flashready', (function() {\n return $__0.bootstrap();\n }));\n Mediator.on(this.uniqueId + ':timeupdate', (function() {\n return $__0.updateTime();\n }));\n Mediator.on(this.uniqueId + ':playbackstate', (function(state) {\n return $__0.setPlaybackState(state);\n }));\n Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) {\n return $__0.updateHighDefinition(isHD);\n }));\n Mediator.on(this.uniqueId + ':playbackerror', (function() {\n return $__0.flashPlaybackError();\n }));\n },\n stopListening: function() {\n $traceurRuntime.superCall(this, $HLS.prototype, \"stopListening\", []);\n Mediator.off(this.uniqueId + ':flashready');\n Mediator.off(this.uniqueId + ':timeupdate');\n Mediator.off(this.uniqueId + ':playbackstate');\n Mediator.off(this.uniqueId + ':highdefinition');\n Mediator.off(this.uniqueId + ':playbackerror');\n },\n bootstrap: function() {\n this.el.width = \"100%\";\n this.el.height = \"100%\";\n this.isReady = true;\n this.trigger(Events.PLAYBACK_READY, this.name);\n this.currentState = \"IDLE\";\n this.setFlashSettings();\n this.autoPlay && this.play();\n },\n setFlashSettings: function() {\n this.el.globoPlayerSetflushLiveURLCache(this.flushLiveURLCache);\n this.el.globoPlayerCapLeveltoStage(this.capLevelToStage);\n this.el.globoPlayerSetmaxBufferLength(0);\n },\n updateHighDefinition: function(isHD) {\n this.highDefinition = (isHD === \"true\");\n this.trigger(Events.PLAYBACK_HIGHDEFINITIONUPDATE);\n this.trigger(Events.PLAYBACK_BITRATE, {'bitrate': this.getCurrentBitrate()});\n },\n updateTime: function() {\n var duration = this.getDuration();\n var position = Math.min(Math.max(this.el.globoGetPosition(), 0), duration);\n var previousDVRStatus = this.dvrEnabled;\n var livePlayback = (this.playbackType === 'live');\n this.dvrEnabled = (livePlayback && duration > 240);\n if (duration === 100 || livePlayback === undefined) {\n return;\n }\n if (this.dvrEnabled !== previousDVRStatus) {\n this.updateSettings();\n this.trigger(Events.PLAYBACK_SETTINGSUPDATE, this.name);\n }\n if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) {\n position = duration;\n }\n this.trigger(Events.PLAYBACK_TIMEUPDATE, position, duration, this.name);\n },\n play: function() {\n if (this.currentState === 'PAUSED') {\n this.el.globoPlayerResume();\n } else if (this.currentState !== \"PLAYING\") {\n this.firstPlay();\n }\n this.trigger(Events.PLAYBACK_PLAY, this.name);\n },\n getPlaybackType: function() {\n return this.playbackType ? this.playbackType : null;\n },\n getCurrentBitrate: function() {\n var currentLevel = this.getLevels()[this.el.globoGetLevel()];\n return currentLevel.bitrate;\n },\n getLastProgramDate: function() {\n var programDate = this.el.globoGetLastProgramDate();\n return programDate - 1.08e+7;\n },\n isHighDefinitionInUse: function() {\n return this.highDefinition;\n },\n getLevels: function() {\n if (!this.levels || this.levels.length === 0) {\n this.levels = this.el.globoGetLevels();\n }\n return this.levels;\n },\n setPlaybackState: function(state) {\n var bufferLength = this.el.globoGetbufferLength();\n if (state === \"PLAYING_BUFFERING\" && bufferLength < 1) {\n this.trigger(Events.PLAYBACK_BUFFERING, this.name);\n this.updateCurrentState(state);\n } else if (state === \"PLAYING\") {\n if (_.contains([\"PLAYING_BUFFERING\", \"PAUSED\", \"IDLE\"], this.currentState)) {\n this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);\n this.updateCurrentState(state);\n }\n } else if (state === \"PAUSED\") {\n this.updateCurrentState(state);\n } else if (state === \"IDLE\") {\n this.trigger(Events.PLAYBACK_ENDED, this.name);\n this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.globoGetDuration(), this.name);\n this.updateCurrentState(state);\n }\n this.lastBufferLength = bufferLength;\n },\n updateCurrentState: function(state) {\n this.currentState = state;\n this.updatePlaybackType();\n },\n updatePlaybackType: function() {\n this.playbackType = this.el.globoGetType();\n if (this.playbackType) {\n this.playbackType = this.playbackType.toLowerCase();\n if (this.playbackType === 'vod') {\n this.startReportingProgress();\n } else {\n this.stopReportingProgress();\n }\n }\n this.trigger(Events.PLAYBACK_PLAYBACKSTATE);\n },\n startReportingProgress: function() {\n if (!this.reportingProgress) {\n this.reportingProgress = true;\n Mediator.on(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded);\n }\n },\n stopReportingProgress: function() {\n Mediator.off(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded, this);\n },\n onFragmentLoaded: function() {\n var buffered = this.el.globoGetPosition() + this.el.globoGetbufferLength();\n this.trigger(Events.PLAYBACK_PROGRESS, this.el.globoGetPosition(), buffered, this.getDuration(), this.name);\n },\n firstPlay: function() {\n this.setFlashSettings();\n this.el.globoPlayerLoad(this.src);\n this.el.globoPlayerPlay();\n },\n volume: function(value) {\n var $__0 = this;\n if (this.isReady) {\n this.el.globoPlayerVolume(value);\n } else {\n this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {\n return $__0.volume(value);\n }));\n }\n },\n pause: function() {\n if (this.playbackType !== 'live' || this.dvrEnabled) {\n this.el.globoPlayerPause();\n if (this.playbackType === 'live' && this.dvrEnabled) {\n this.updateDvr(true);\n }\n }\n },\n stop: function() {\n this.el.globoPlayerStop();\n this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name);\n },\n isPlaying: function() {\n if (this.currentState) {\n return !!(this.currentState.match(/playing/i));\n }\n return false;\n },\n getDuration: function() {\n var duration = this.el.globoGetDuration();\n if (this.playbackType === 'live') {\n duration = duration - 10;\n }\n return duration;\n },\n seek: function(time) {\n var duration = this.getDuration();\n if (time > 0) {\n time = duration * time / 100;\n }\n if (this.playbackType === 'live') {\n var dvrInUse = (time >= 0 && duration - time > 5);\n if (!dvrInUse) {\n time = -1;\n }\n this.updateDvr(dvrInUse);\n }\n this.el.globoPlayerSeek(time);\n this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name);\n },\n updateDvr: function(dvrInUse) {\n var previousDvrInUse = !!this.dvrInUse;\n this.dvrInUse = dvrInUse;\n if (this.dvrInUse !== previousDvrInUse) {\n this.updateSettings();\n this.trigger(Events.PLAYBACK_DVR, this.dvrInUse);\n this.trigger(Events.PLAYBACK_STATS_ADD, {'dvr': this.dvrInUse});\n }\n },\n flashPlaybackError: function() {\n this.trigger(Events.PLAYBACK_STOP);\n },\n timeUpdate: function(time, duration) {\n this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name);\n },\n destroy: function() {\n this.stopListening();\n this.$el.remove();\n },\n setupFirefox: function() {\n var $el = this.$('embed');\n $el.attr('data-hls', '');\n this.setElement($el);\n },\n setupIE: function() {\n this.setElement($(_.template(objectIE)({\n cid: this.cid,\n swfPath: this.swfPath,\n playbackId: this.uniqueId\n })));\n },\n updateSettings: function() {\n this.settings = _.extend({}, this.defaultSettings);\n if (this.playbackType === \"vod\" || this.dvrInUse) {\n this.settings.left = [\"playpause\", \"position\", \"duration\"];\n this.settings.seekEnabled = true;\n } else if (this.dvrEnabled) {\n this.settings.left = [\"playpause\"];\n this.settings.seekEnabled = true;\n } else {\n this.settings.seekEnabled = false;\n }\n },\n setElement: function(element) {\n this.$el = element;\n this.el = element[0];\n },\n render: function() {\n if (Browser.isLegacyIE) {\n this.setupIE();\n } else {\n this.$el.html(this.template({\n cid: this.cid,\n swfPath: this.swfPath,\n playbackId: this.uniqueId\n }));\n if (Browser.isFirefox) {\n this.setupFirefox();\n } else if (Browser.isIE) {\n this.$('embed').remove();\n }\n }\n this.el.id = this.cid;\n return this;\n }\n}, {}, Playback);\nHLS.canPlay = function(resource) {\n return !!resource.match(/^http(.*).m3u8?/);\n};\nmodule.exports = HLS;\n\n\n},{\"../../base/jst\":7,\"browser\":\"browser\",\"events\":\"events\",\"mediator\":\"mediator\",\"playback\":\"playback\",\"underscore\":\"underscore\"}],26:[function(require,module,exports){\n\"use strict\";\nvar Playback = require('playback');\nvar Events = require('events');\nvar HTML5Audio = function HTML5Audio(params) {\n $traceurRuntime.superCall(this, $HTML5Audio.prototype, \"constructor\", [params]);\n this.el.src = params.src;\n this.settings = {\n left: ['playpause', 'position', 'duration'],\n right: ['fullscreen', 'volume'],\n default: ['seekbar']\n };\n this.render();\n params.autoPlay && this.play();\n};\nvar $HTML5Audio = HTML5Audio;\n($traceurRuntime.createClass)(HTML5Audio, {\n get name() {\n return 'html5_audio';\n },\n get tagName() {\n return 'audio';\n },\n get events() {\n return {\n 'timeupdate': 'timeUpdated',\n 'ended': 'ended',\n 'canplaythrough': 'bufferFull'\n };\n },\n bindEvents: function() {\n this.listenTo(this.container, Events.CONTAINER_PLAY, this.play);\n this.listenTo(this.container, Events.CONTAINER_PAUSE, this.pause);\n this.listenTo(this.container, Events.CONTAINER_SEEK, this.seek);\n this.listenTo(this.container, Events.CONTAINER_VOLUME, this.volume);\n this.listenTo(this.container, Events.CONTAINER_STOP, this.stop);\n },\n getPlaybackType: function() {\n return \"aod\";\n },\n play: function() {\n this.el.play();\n this.trigger(Events.PLAYBACK_PLAY);\n },\n pause: function() {\n this.el.pause();\n },\n stop: function() {\n this.pause();\n this.el.currentTime = 0;\n },\n volume: function(value) {\n this.el.volume = value / 100;\n },\n mute: function() {\n this.el.volume = 0;\n },\n unmute: function() {\n this.el.volume = 1;\n },\n isMuted: function() {\n return !!this.el.volume;\n },\n ended: function() {\n this.trigger(Events.CONTAINER_TIMEUPDATE, 0);\n },\n seek: function(seekBarValue) {\n var time = this.el.duration * (seekBarValue / 100);\n this.el.currentTime = time;\n },\n getCurrentTime: function() {\n return this.el.currentTime;\n },\n getDuration: function() {\n return this.el.duration;\n },\n isPlaying: function() {\n return !this.el.paused && !this.el.ended;\n },\n timeUpdated: function() {\n this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);\n },\n bufferFull: function() {\n this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);\n this.trigger(Events.PLAYBACK_BUFFERFULL);\n },\n render: function() {\n this.trigger(Events.PLAYBACK_READY, this.name);\n return this;\n }\n}, {}, Playback);\nHTML5Audio.canPlay = function(resource) {\n return !!resource.match(/(.*).mp3/);\n};\nmodule.exports = HTML5Audio;\n\n\n},{\"events\":\"events\",\"playback\":\"playback\"}],27:[function(require,module,exports){\n(function (process){\n\"use strict\";\nvar Playback = require('playback');\nvar JST = require('../../base/jst');\nvar Styler = require('../../base/styler');\nvar Browser = require('browser');\nvar seekStringToSeconds = require('../../base/utils').seekStringToSeconds;\nvar Events = require('events');\nvar _ = require('underscore');\nrequire('mousetrap');\nvar HTML5Video = function HTML5Video(options) {\n $traceurRuntime.superCall(this, $HTML5Video.prototype, \"constructor\", [options]);\n this.options = options;\n this.src = options.src;\n this.el.src = options.src;\n this.el.loop = options.loop;\n this.firstBuffer = true;\n this.isHLS = (this.src.indexOf('m3u8') > -1);\n this.settings = {default: ['seekbar']};\n if (this.isHLS && Browser.isSafari) {\n this.settings.left = [\"playstop\"];\n this.settings.right = [\"fullscreen\", \"volume\"];\n } else {\n this.el.preload = options.preload ? options.preload : 'metadata';\n this.settings.left = [\"playpause\", \"position\", \"duration\"];\n this.settings.right = [\"fullscreen\", \"volume\"];\n this.settings.seekEnabled = true;\n }\n this.bindEvents();\n};\nvar $HTML5Video = HTML5Video;\n($traceurRuntime.createClass)(HTML5Video, {\n get name() {\n return 'html5_video';\n },\n get tagName() {\n return 'video';\n },\n get template() {\n return JST.html5_video;\n },\n get attributes() {\n return {'data-html5-video': ''};\n },\n get events() {\n return {\n 'timeupdate': 'timeUpdated',\n 'progress': 'progress',\n 'ended': 'ended',\n 'stalled': 'stalled',\n 'waiting': 'waiting',\n 'canplaythrough': 'bufferFull',\n 'loadedmetadata': 'loadedMetadata'\n };\n },\n bindEvents: function() {\n _.each(_.range(1, 10), function(i) {\n var $__0 = this;\n Mousetrap.bind([i.toString()], (function() {\n return $__0.seek(i * 10);\n }));\n }.bind(this));\n },\n loadedMetadata: function(e) {\n this.trigger(Events.PLAYBACK_LOADEDMETADATA, e.target.duration);\n this.trigger(Events.PLAYBACK_SETTINGSUPDATE);\n this.checkInitialSeek();\n },\n getPlaybackType: function() {\n return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod';\n },\n isHighDefinitionInUse: function() {\n return false;\n },\n play: function() {\n this.el.play();\n this.trigger(Events.PLAYBACK_PLAY);\n if (this.isHLS) {\n this.trigger(Events.PLAYBACK_TIMEUPDATE, 1, 1, this.name);\n }\n },\n pause: function() {\n this.el.pause();\n },\n stop: function() {\n this.pause();\n if (this.el.readyState !== 0) {\n this.el.currentTime = 0;\n }\n },\n volume: function(value) {\n this.el.volume = value / 100;\n },\n mute: function() {\n this.el.volume = 0;\n },\n unmute: function() {\n this.el.volume = 1;\n },\n isMuted: function() {\n return !!this.el.volume;\n },\n isPlaying: function() {\n return !this.el.paused && !this.el.ended;\n },\n ended: function() {\n this.trigger(Events.PLAYBACK_ENDED, this.name);\n this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.duration, this.name);\n },\n stalled: function() {\n if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) {\n this.trigger(Events.PLAYBACK_BUFFERING, this.name);\n }\n },\n waiting: function() {\n if (this.el.readyState < this.el.HAVE_FUTURE_DATA) {\n this.trigger(Events.PLAYBACK_BUFFERING, this.name);\n }\n },\n bufferFull: function() {\n if (this.options.poster && this.firstBuffer) {\n this.firstBuffer = false;\n if (!this.isPlaying()) {\n this.el.poster = this.options.poster;\n }\n } else {\n this.el.poster = '';\n }\n this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);\n },\n destroy: function() {\n this.stop();\n this.el.src = '';\n this.$el.remove();\n },\n seek: function(seekBarValue) {\n var time = this.el.duration * (seekBarValue / 100);\n this.seekSeconds(time);\n },\n seekSeconds: function(time) {\n this.el.currentTime = time;\n },\n checkInitialSeek: function() {\n var seekTime = seekStringToSeconds(window.location.href);\n this.seekSeconds(seekTime);\n },\n getCurrentTime: function() {\n return this.el.currentTime;\n },\n getDuration: function() {\n return this.el.duration;\n },\n timeUpdated: function() {\n if (this.getPlaybackType() !== 'live') {\n this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);\n }\n },\n progress: function() {\n if (!this.el.buffered.length)\n return;\n var bufferedPos = 0;\n for (var i = 0; i < this.el.buffered.length; i++) {\n if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {\n bufferedPos = i;\n break;\n }\n }\n this.trigger(Events.PLAYBACK_PROGRESS, this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name);\n },\n typeFor: function(src) {\n return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4';\n },\n render: function() {\n var $__0 = this;\n var style = Styler.getStyleFor(this.name);\n this.$el.html(this.template({\n src: this.src,\n type: this.typeFor(this.src)\n }));\n this.$el.append(style);\n this.trigger(Events.PLAYBACK_READY, this.name);\n process.nextTick((function() {\n return $__0.options.autoPlay && $__0.play();\n }));\n return this;\n }\n}, {}, Playback);\nHTML5Video.canPlay = function(resource) {\n var mimetypes = {\n 'mp4': _.map([\"avc1.42E01E\", \"avc1.58A01E\", \"avc1.4D401E\", \"avc1.64001E\", \"mp4v.20.8\", \"mp4v.20.240\"], function(codec) {\n return 'video/mp4; codecs=' + codec + ', mp4a.40.2';\n }),\n 'ogg': ['video/ogg; codecs=\"theora, vorbis\"', 'video/ogg; codecs=\"dirac\"', 'video/ogg; codecs=\"theora, speex\"'],\n '3gpp': ['video/3gpp; codecs=\"mp4v.20.8, samr\"'],\n 'webm': ['video/webm; codecs=\"vp8, vorbis\"'],\n 'mkv': ['video/x-matroska; codecs=\"theora, vorbis\"'],\n 'm3u8': ['application/x-mpegURL']\n };\n mimetypes['ogv'] = mimetypes['ogg'];\n mimetypes['3gp'] = mimetypes['3gpp'];\n var extension = resource.split('?')[0].match(/.*\\.(.*)$/)[1];\n if (_.has(mimetypes, extension)) {\n var v = document.createElement('video');\n return !!_.find(mimetypes[extension], function(ext) {\n return !!v.canPlayType(ext).replace(/no/, '');\n });\n }\n return false;\n};\nmodule.exports = HTML5Video;\n\n\n}).call(this,require('_process'))\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"../../base/utils\":9,\"_process\":2,\"browser\":\"browser\",\"events\":\"events\",\"mousetrap\":4,\"playback\":\"playback\",\"underscore\":\"underscore\"}],28:[function(require,module,exports){\n\"use strict\";\nvar Playback = require('playback');\nvar Styler = require('../../base/styler');\nvar JST = require('../../base/jst');\nvar Events = require('events');\nvar HTMLImg = function HTMLImg(params) {\n $traceurRuntime.superCall(this, $HTMLImg.prototype, \"constructor\", [params]);\n this.el.src = params.src;\n setTimeout(function() {\n this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);\n }.bind(this), 1);\n};\nvar $HTMLImg = HTMLImg;\n($traceurRuntime.createClass)(HTMLImg, {\n get name() {\n return 'html_img';\n },\n get tagName() {\n return 'img';\n },\n get attributes() {\n return {'data-html-img': ''};\n },\n getPlaybackType: function() {\n return null;\n },\n render: function() {\n var style = Styler.getStyleFor(this.name);\n this.$el.append(style);\n return this;\n }\n}, {}, Playback);\nHTMLImg.canPlay = function(resource) {\n return !!resource.match(/(.*).(png|jpg|jpeg|gif|bmp)/);\n};\nmodule.exports = HTMLImg;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"events\":\"events\",\"playback\":\"playback\"}],29:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./no_op');\n\n\n},{\"./no_op\":30}],30:[function(require,module,exports){\n\"use strict\";\nvar Playback = require('playback');\nvar JST = require('../../base/jst');\nvar Styler = require('../../base/styler');\nvar NoOp = function NoOp(options) {\n $traceurRuntime.superCall(this, $NoOp.prototype, \"constructor\", [options]);\n};\nvar $NoOp = NoOp;\n($traceurRuntime.createClass)(NoOp, {\n get name() {\n return 'no_op';\n },\n get template() {\n return JST.no_op;\n },\n get attributes() {\n return {'data-no-op': ''};\n },\n render: function() {\n var style = Styler.getStyleFor(this.name);\n this.$el.html(this.template());\n this.$el.append(style);\n return this;\n }\n}, {}, Playback);\nNoOp.canPlay = (function(source) {\n return true;\n});\nmodule.exports = NoOp;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"playback\":\"playback\"}],31:[function(require,module,exports){\n(function (process){\n\"use strict\";\nvar UICorePlugin = require('ui_core_plugin');\nvar JST = require('../../base/jst');\nvar Styler = require('../../base/styler');\nvar Events = require('events');\nvar Browser = require('browser');\nvar Mediator = require('mediator');\nvar PlayerInfo = require('player_info');\nvar BackgroundButton = function BackgroundButton(core) {\n $traceurRuntime.superCall(this, $BackgroundButton.prototype, \"constructor\", [core]);\n this.core = core;\n this.settingsUpdate();\n};\nvar $BackgroundButton = BackgroundButton;\n($traceurRuntime.createClass)(BackgroundButton, {\n get template() {\n return JST.background_button;\n },\n get name() {\n return 'background_button';\n },\n get attributes() {\n return {\n 'class': 'background-button',\n 'data-background-button': ''\n };\n },\n get events() {\n return {'click .background-button-icon': 'click'};\n },\n bindEvents: function() {\n this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERING, this.hide);\n this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERFULL, this.show);\n this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate);\n this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_SHOW, this.updateSize);\n this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_PLAYING, this.playing);\n this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_NOTPLAYING, this.notplaying);\n Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this);\n },\n stopListening: function() {\n $traceurRuntime.superCall(this, $BackgroundButton.prototype, \"stopListening\", []);\n Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this);\n },\n settingsUpdate: function() {\n this.stopListening();\n if (this.shouldRender()) {\n this.render();\n this.bindEvents();\n if (this.core.mediaControl.container.isPlaying()) {\n this.playing();\n } else {\n this.notplaying();\n }\n } else {\n this.$el.remove();\n this.$playPauseButton.show();\n this.$playStopButton.show();\n this.listenTo(this.core.mediaControl.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);\n this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate);\n this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.settingsUpdate);\n }\n },\n shouldRender: function() {\n var useBackgroundButton = (this.core.options.useBackgroundButton === undefined && Browser.isMobile) || !!this.core.options.useBackgroundButton;\n return useBackgroundButton && (this.core.mediaControl.$el.find('[data-playstop]').length > 0 || this.core.mediaControl.$el.find('[data-playpause]').length > 0);\n },\n click: function() {\n this.core.mediaControl.show();\n if (this.shouldStop) {\n this.core.mediaControl.togglePlayStop();\n } else {\n this.core.mediaControl.togglePlayPause();\n }\n },\n show: function() {\n this.$el.removeClass('hide');\n },\n hide: function() {\n this.$el.addClass('hide');\n },\n enable: function() {\n this.stopListening();\n $traceurRuntime.superCall(this, $BackgroundButton.prototype, \"enable\", []);\n this.settingsUpdate();\n },\n disable: function() {\n $traceurRuntime.superCall(this, $BackgroundButton.prototype, \"disable\", []);\n this.$playPauseButton.show();\n this.$playStopButton.show();\n },\n playing: function() {\n this.$buttonIcon.removeClass('notplaying').addClass('playing');\n },\n notplaying: function() {\n this.$buttonIcon.removeClass('playing').addClass('notplaying');\n },\n getExternalInterface: function() {},\n updateSize: function() {\n if (!this.$el)\n return;\n var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();\n this.$el.css({fontSize: height});\n this.$buttonWrapper.css({marginTop: -(this.$buttonWrapper.height() / 2)});\n },\n render: function() {\n var $__0 = this;\n var style = Styler.getStyleFor(this.name);\n this.$el.html(this.template());\n this.$el.append(style);\n this.$playPauseButton = this.core.mediaControl.$el.find('[data-playpause]');\n this.$playStopButton = this.core.mediaControl.$el.find('[data-playstop]');\n this.$buttonWrapper = this.$el.find('.background-button-wrapper[data-background-button]');\n this.$buttonIcon = this.$el.find('.background-button-icon[data-background-button]');\n this.shouldStop = this.$playStopButton.length > 0;\n this.$el.insertBefore(this.core.mediaControl.$el.find('.media-control-layer[data-controls]'));\n this.$el.click((function() {\n return $__0.click($__0.$el);\n }));\n process.nextTick((function() {\n return $__0.updateSize();\n }));\n if (this.core.options.useBackgroundButton) {\n this.$playPauseButton.hide();\n this.$playStopButton.hide();\n }\n if (this.shouldStop) {\n this.$buttonIcon.addClass('playstop');\n }\n if (this.core.mediaControl.isVisible()) {\n this.show();\n }\n return this;\n }\n}, {}, UICorePlugin);\nmodule.exports = BackgroundButton;\n\n\n}).call(this,require('_process'))\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"_process\":2,\"browser\":\"browser\",\"events\":\"events\",\"mediator\":\"mediator\",\"player_info\":\"player_info\",\"ui_core_plugin\":\"ui_core_plugin\"}],32:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./background_button');\n\n\n},{\"./background_button\":31}],33:[function(require,module,exports){\n\"use strict\";\nvar ContainerPlugin = require('container_plugin');\nvar Events = require('events');\nvar ClickToPausePlugin = function ClickToPausePlugin() {\n $traceurRuntime.defaultSuperCall(this, $ClickToPausePlugin.prototype, arguments);\n};\nvar $ClickToPausePlugin = ClickToPausePlugin;\n($traceurRuntime.createClass)(ClickToPausePlugin, {\n get name() {\n return 'click_to_pause';\n },\n bindEvents: function() {\n this.listenTo(this.container, Events.CONTAINER_CLICK, this.click);\n this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);\n },\n click: function() {\n if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {\n if (this.container.isPlaying()) {\n this.container.pause();\n } else {\n this.container.play();\n }\n }\n },\n settingsUpdate: function() {\n this.container.$el.removeClass('pointer-enabled');\n if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {\n this.container.$el.addClass('pointer-enabled');\n }\n }\n}, {}, ContainerPlugin);\nmodule.exports = ClickToPausePlugin;\n\n\n},{\"container_plugin\":\"container_plugin\",\"events\":\"events\"}],34:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./click_to_pause');\n\n\n},{\"./click_to_pause\":33}],35:[function(require,module,exports){\n\"use strict\";\nvar UICorePlugin = require('ui_core_plugin');\nvar JST = require('../../base/jst');\nvar Styler = require('../../base/styler');\nvar Events = require('events');\nvar DVRControls = function DVRControls(core) {\n $traceurRuntime.superCall(this, $DVRControls.prototype, \"constructor\", [core]);\n this.core = core;\n this.settingsUpdate();\n};\nvar $DVRControls = DVRControls;\n($traceurRuntime.createClass)(DVRControls, {\n get template() {\n return JST.dvr_controls;\n },\n get name() {\n return 'dvr_controls';\n },\n get events() {\n return {'click .live-button': 'click'};\n },\n get attributes() {\n return {\n 'class': 'dvr-controls',\n 'data-dvr-controls': ''\n };\n },\n bindEvents: function() {\n this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate);\n this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.dvrChanged);\n },\n dvrChanged: function(dvrEnabled) {\n this.settingsUpdate();\n this.core.mediaControl.$el.addClass('live');\n if (dvrEnabled) {\n this.core.mediaControl.$el.addClass('dvr');\n this.core.mediaControl.$el.find('.media-control-indicator[data-position], .media-control-indicator[data-duration]').hide();\n } else {\n this.core.mediaControl.$el.removeClass('dvr');\n }\n },\n click: function() {\n if (!this.core.mediaControl.container.isPlaying()) {\n this.core.mediaControl.container.play();\n }\n if (this.core.mediaControl.$el.hasClass('dvr')) {\n this.core.mediaControl.container.setCurrentTime(-1);\n }\n },\n settingsUpdate: function() {\n var $__0 = this;\n this.stopListening();\n if (this.shouldRender()) {\n this.render();\n this.$el.click((function() {\n return $__0.click();\n }));\n }\n this.bindEvents();\n },\n shouldRender: function() {\n var useDvrControls = this.core.options.useDvrControls === undefined || !!this.core.options.useDvrControls;\n return useDvrControls && this.core.mediaControl.container.getPlaybackType() === 'live';\n },\n render: function() {\n var style = Styler.getStyleFor(this.name);\n this.$el.html(this.template());\n this.$el.append(style);\n if (this.shouldRender()) {\n this.core.mediaControl.$el.addClass('live');\n this.core.mediaControl.$('.media-control-left-panel[data-media-control]').append(this.$el);\n if (this.$duration) {\n this.$duration.remove();\n }\n this.$duration = $('');\n this.core.mediaControl.seekTime.$el.append(this.$duration);\n }\n return this;\n }\n}, {}, UICorePlugin);\nmodule.exports = DVRControls;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"events\":\"events\",\"ui_core_plugin\":\"ui_core_plugin\"}],36:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./dvr_controls');\n\n\n},{\"./dvr_controls\":35}],37:[function(require,module,exports){\n\"use strict\";\nvar ContainerPlugin = require('container_plugin');\nvar Events = require('events');\nvar GoogleAnalytics = function GoogleAnalytics(options) {\n $traceurRuntime.superCall(this, $GoogleAnalytics.prototype, \"constructor\", [options]);\n if (options.gaAccount) {\n this.embedScript();\n this.account = options.gaAccount;\n this.trackerName = options.gaTrackerName + \".\" || 'Clappr.';\n this.currentHDState = undefined;\n }\n};\nvar $GoogleAnalytics = GoogleAnalytics;\n($traceurRuntime.createClass)(GoogleAnalytics, {\n get name() {\n return 'google_analytics';\n },\n embedScript: function() {\n var $__0 = this;\n if (!window._gat) {\n var script = document.createElement('script');\n script.setAttribute(\"type\", \"text/javascript\");\n script.setAttribute(\"async\", \"async\");\n script.setAttribute(\"src\", \"http://www.google-analytics.com/ga.js\");\n script.onload = (function() {\n return $__0.addEventListeners();\n });\n document.body.appendChild(script);\n } else {\n this.addEventListeners();\n }\n },\n addEventListeners: function() {\n var $__0 = this;\n this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay);\n this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);\n this.listenTo(this.container, Events.CONTAINER_PAUSE, this.onPause);\n this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded);\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);\n this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded);\n this.listenTo(this.container, Events.CONTAINER_ERROR, this.onError);\n this.listenTo(this.container, Events.CONTAINER_PLAYBACKSTATE, this.onPlaybackChanged);\n this.listenTo(this.container, Events.CONTAINER_VOLUME, (function(event) {\n return $__0.onVolumeChanged(event);\n }));\n this.listenTo(this.container, Events.CONTAINER_SEEK, (function(event) {\n return $__0.onSeek(event);\n }));\n this.listenTo(this.container, Events.CONTAINER_FULL_SCREEN, this.onFullscreen);\n this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.onHD);\n this.listenTo(this.container.playback, Events.PLAYBACK_DVR, this.onDVR);\n _gaq.push([this.trackerName + '_setAccount', this.account]);\n },\n onPlay: function() {\n this.push([\"Video\", \"Play\", this.container.playback.src]);\n },\n onStop: function() {\n this.push([\"Video\", \"Stop\", this.container.playback.src]);\n },\n onEnded: function() {\n this.push([\"Video\", \"Ended\", this.container.playback.src]);\n },\n onBuffering: function() {\n this.push([\"Video\", \"Buffering\", this.container.playback.src]);\n },\n onBufferFull: function() {\n this.push([\"Video\", \"Bufferfull\", this.container.playback.src]);\n },\n onError: function() {\n this.push([\"Video\", \"Error\", this.container.playback.src]);\n },\n onHD: function() {\n var status = this.container.isHighDefinitionInUse() ? \"ON\" : \"OFF\";\n if (status !== this.currentHDState) {\n this.currentHDState = status;\n this.push([\"Video\", \"HD - \" + status, this.container.playback.src]);\n }\n },\n onPlaybackChanged: function() {\n var type = this.container.getPlaybackType();\n if (type !== null) {\n this.push([\"Video\", \"Playback Type - \" + type, this.container.playback.src]);\n }\n },\n onDVR: function() {\n var status = this.container.isHighDefinitionInUse();\n this.push([\"Interaction\", \"DVR - \" + status, this.container.playback.src]);\n },\n onPause: function() {\n this.push([\"Video\", \"Pause\", this.container.playback.src]);\n },\n onSeek: function() {\n this.push([\"Video\", \"Seek\", this.container.playback.src]);\n },\n onVolumeChanged: function() {\n this.push([\"Interaction\", \"Volume\", this.container.playback.src]);\n },\n onFullscreen: function() {\n this.push([\"Interaction\", \"Fullscreen\", this.container.playback.src]);\n },\n push: function(array) {\n var res = [this.trackerName + \"_trackEvent\"].concat(array);\n _gaq.push(res);\n }\n}, {}, ContainerPlugin);\nmodule.exports = GoogleAnalytics;\n\n\n},{\"container_plugin\":\"container_plugin\",\"events\":\"events\"}],38:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./google_analytics');\n\n\n},{\"./google_analytics\":37}],39:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./log');\n\n\n},{\"./log\":40}],40:[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nrequire('mousetrap');\nvar Log = function Log() {\n var $__0 = this;\n Mousetrap.bind(['ctrl+shift+d'], (function() {\n return $__0.onOff();\n }));\n this.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];\n};\n($traceurRuntime.createClass)(Log, {\n info: function(klass, message) {\n this.log(klass, 'info', message);\n },\n warn: function(klass, message) {\n this.log(klass, 'warn', message);\n },\n debug: function(klass, message) {\n this.log(klass, 'debug', message);\n },\n onOff: function() {\n window.DEBUG = !window.DEBUG;\n if (window.DEBUG) {\n console.log('log enabled');\n } else {\n console.log('log disabled');\n }\n },\n log: function(klass, level, message) {\n if (!window.DEBUG || _.contains(this.BLACKLIST, message))\n return;\n var color;\n if (level === 'warn') {\n color = '#FF8000';\n } else if (level === 'info') {\n color = '#006600';\n } else if (level === 'error') {\n color = '#FF0000';\n }\n console.log(\"%c [\" + klass + \"] [\" + level + \"] \" + message, 'color: ' + color);\n }\n}, {});\nLog.getInstance = function() {\n if (this._instance === undefined) {\n this._instance = new this();\n }\n return this._instance;\n};\nmodule.exports = Log;\n\n\n},{\"mousetrap\":4,\"underscore\":\"underscore\"}],41:[function(require,module,exports){\n(function (process){\n\"use strict\";\nvar UIContainerPlugin = require('ui_container_plugin');\nvar Styler = require('../../base/styler');\nvar JST = require('../../base/jst');\nvar Events = require('events');\nvar Mediator = require('mediator');\nvar PlayerInfo = require('player_info');\nvar $ = require('zepto');\nvar _ = require('underscore');\nvar PosterPlugin = function PosterPlugin(options) {\n $traceurRuntime.superCall(this, $PosterPlugin.prototype, \"constructor\", [options]);\n this.options = options;\n _.defaults(this.options, {disableControlsOnPoster: true});\n if (this.options.disableControlsOnPoster) {\n this.container.disableMediaControl();\n }\n this.render();\n};\nvar $PosterPlugin = PosterPlugin;\n($traceurRuntime.createClass)(PosterPlugin, {\n get name() {\n return 'poster';\n },\n get template() {\n return JST.poster;\n },\n get attributes() {\n return {\n 'class': 'player-poster',\n 'data-poster': ''\n };\n },\n get events() {\n return {'click': 'clicked'};\n },\n bindEvents: function() {\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferfull);\n this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);\n this.listenTo(this.container, Events.CONTAINER_ENDED, this.onStop);\n Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this);\n },\n stopListening: function() {\n $traceurRuntime.superCall(this, $PosterPlugin.prototype, \"stopListening\", []);\n Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this);\n },\n onBuffering: function() {\n this.hidePlayButton();\n },\n onBufferfull: function() {\n this.$el.hide();\n if (this.options.disableControlsOnPoster) {\n this.container.enableMediaControl();\n }\n },\n onStop: function() {\n this.$el.show();\n if (this.options.disableControlsOnPoster) {\n this.container.disableMediaControl();\n }\n if (!this.options.hidePlayButton) {\n this.showPlayButton();\n }\n },\n hidePlayButton: function() {\n this.$playButton.hide();\n },\n showPlayButton: function() {\n this.$playButton.show();\n this.updateSize();\n },\n clicked: function() {\n this.container.play();\n return false;\n },\n updateSize: function() {\n if (!this.$el)\n return;\n var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();\n this.$el.css({fontSize: height});\n if (this.$playWrapper.is(':visible')) {\n this.$playWrapper.css({marginTop: -(this.$playWrapper.height() / 2)});\n if (!this.options.hidePlayButton) {\n this.$playButton.show();\n }\n } else {\n this.$playButton.hide();\n }\n },\n render: function() {\n var $__0 = this;\n var style = Styler.getStyleFor(this.name);\n this.$el.html(this.template());\n this.$el.append(style);\n this.$playButton = this.$el.find('.poster-icon');\n this.$playWrapper = this.$el.find('.play-wrapper');\n if (this.options.poster !== undefined) {\n var imgEl = $('');\n imgEl.attr('src', this.options.poster);\n this.$el.prepend(imgEl);\n }\n this.container.$el.append(this.el);\n if (!!this.options.hidePlayButton) {\n this.hidePlayButton();\n }\n process.nextTick((function() {\n return $__0.updateSize();\n }));\n return this;\n }\n}, {}, UIContainerPlugin);\nmodule.exports = PosterPlugin;\n\n\n}).call(this,require('_process'))\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"_process\":2,\"events\":\"events\",\"mediator\":\"mediator\",\"player_info\":\"player_info\",\"ui_container_plugin\":\"ui_container_plugin\",\"underscore\":\"underscore\",\"zepto\":\"zepto\"}],42:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./spinner_three_bounce');\n\n\n},{\"./spinner_three_bounce\":43}],43:[function(require,module,exports){\n\"use strict\";\nvar UIContainerPlugin = require('ui_container_plugin');\nvar Styler = require('../../base/styler');\nvar JST = require('../../base/jst');\nvar Events = require('events');\nvar SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) {\n $traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, \"constructor\", [options]);\n this.template = JST.spinner_three_bounce;\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);\n this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);\n this.render();\n};\nvar $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin;\n($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, {\n get name() {\n return 'spinner';\n },\n get attributes() {\n return {\n 'data-spinner': '',\n 'class': 'spinner-three-bounce'\n };\n },\n onBuffering: function() {\n this.$el.show();\n },\n onBufferFull: function() {\n this.$el.hide();\n },\n onStop: function() {\n this.$el.hide();\n },\n render: function() {\n this.$el.html(this.template());\n var style = Styler.getStyleFor('spinner_three_bounce');\n this.container.$el.append(style);\n this.container.$el.append(this.$el);\n this.$el.hide();\n return this;\n }\n}, {}, UIContainerPlugin);\nmodule.exports = SpinnerThreeBouncePlugin;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"events\":\"events\",\"ui_container_plugin\":\"ui_container_plugin\"}],44:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./stats');\n\n\n},{\"./stats\":45}],45:[function(require,module,exports){\n\"use strict\";\nvar ContainerPlugin = require('container_plugin');\nvar $ = require(\"zepto\");\nvar Events = require('events');\nvar StatsPlugin = function StatsPlugin(options) {\n $traceurRuntime.superCall(this, $StatsPlugin.prototype, \"constructor\", [options]);\n this.setInitialAttrs();\n this.reportInterval = options.reportInterval || 5000;\n this.state = \"IDLE\";\n};\nvar $StatsPlugin = StatsPlugin;\n($traceurRuntime.createClass)(StatsPlugin, {\n get name() {\n return 'stats';\n },\n bindEvents: function() {\n this.listenTo(this.container.playback, Events.PLAYBACK_PLAY, this.onPlay);\n this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);\n this.listenTo(this.container, Events.CONTAINER_DESTROYED, this.onStop);\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);\n this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);\n this.listenTo(this.container, Events.CONTAINER_STATS_ADD, this.onStatsAdd);\n this.listenTo(this.container, Events.CONTAINER_BITRATE, this.onStatsAdd);\n this.listenTo(this.container.playback, Events.PLAYBACK_STATS_ADD, this.onStatsAdd);\n },\n setInitialAttrs: function() {\n this.firstPlay = true;\n this.startupTime = 0;\n this.rebufferingTime = 0;\n this.watchingTime = 0;\n this.rebuffers = 0;\n this.externalMetrics = {};\n },\n onPlay: function() {\n this.state = \"PLAYING\";\n this.watchingTimeInit = Date.now();\n if (!this.intervalId) {\n this.intervalId = setInterval(this.report.bind(this), this.reportInterval);\n }\n },\n onStop: function() {\n clearInterval(this.intervalId);\n this.intervalId = undefined;\n this.state = \"STOPPED\";\n },\n onBuffering: function() {\n if (this.firstPlay) {\n this.startupTimeInit = Date.now();\n } else {\n this.rebufferingTimeInit = Date.now();\n }\n this.state = \"BUFFERING\";\n this.rebuffers++;\n },\n onBufferFull: function() {\n if (this.firstPlay && !!this.startupTimeInit) {\n this.firstPlay = false;\n this.startupTime = Date.now() - this.startupTimeInit;\n this.watchingTimeInit = Date.now();\n } else if (!!this.rebufferingTimeInit) {\n this.rebufferingTime += this.getRebufferingTime();\n }\n this.rebufferingTimeInit = undefined;\n this.state = \"PLAYING\";\n },\n getRebufferingTime: function() {\n return Date.now() - this.rebufferingTimeInit;\n },\n getWatchingTime: function() {\n var totalTime = (Date.now() - this.watchingTimeInit);\n return totalTime - this.rebufferingTime;\n },\n isRebuffering: function() {\n return !!this.rebufferingTimeInit;\n },\n onStatsAdd: function(metric) {\n $.extend(this.externalMetrics, metric);\n },\n getStats: function() {\n var metrics = {\n startupTime: this.startupTime,\n rebuffers: this.rebuffers,\n rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime,\n watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime()\n };\n $.extend(metrics, this.externalMetrics);\n return metrics;\n },\n report: function() {\n this.container.statsReport(this.getStats());\n }\n}, {}, ContainerPlugin);\nmodule.exports = StatsPlugin;\n\n\n},{\"container_plugin\":\"container_plugin\",\"events\":\"events\",\"zepto\":\"zepto\"}],46:[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./watermark');\n\n\n},{\"./watermark\":47}],47:[function(require,module,exports){\n\"use strict\";\nvar UIContainerPlugin = require('ui_container_plugin');\nvar Styler = require('../../base/styler');\nvar JST = require('../../base/jst');\nvar Events = require('events');\nvar WaterMarkPlugin = function WaterMarkPlugin(options) {\n $traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, \"constructor\", [options]);\n this.template = JST[this.name];\n this.position = options.position || \"bottom-right\";\n if (options.watermark) {\n this.imageUrl = options.watermark;\n this.render();\n } else {\n this.$el.remove();\n }\n};\nvar $WaterMarkPlugin = WaterMarkPlugin;\n($traceurRuntime.createClass)(WaterMarkPlugin, {\n get name() {\n return 'watermark';\n },\n bindEvents: function() {\n this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay);\n this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);\n },\n onPlay: function() {\n if (!this.hidden)\n this.$el.show();\n },\n onStop: function() {\n this.$el.hide();\n },\n render: function() {\n this.$el.hide();\n var templateOptions = {\n position: this.position,\n imageUrl: this.imageUrl\n };\n this.$el.html(this.template(templateOptions));\n var style = Styler.getStyleFor(this.name);\n this.container.$el.append(style);\n this.container.$el.append(this.$el);\n return this;\n }\n}, {}, UIContainerPlugin);\nmodule.exports = WaterMarkPlugin;\n\n\n},{\"../../base/jst\":7,\"../../base/styler\":8,\"events\":\"events\",\"ui_container_plugin\":\"ui_container_plugin\"}],\"base_object\":[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nvar extend = require('./utils').extend;\nvar Events = require('events');\nvar pluginOptions = ['container'];\nvar BaseObject = function BaseObject(options) {\n this.uniqueId = _.uniqueId('o');\n options || (options = {});\n _.extend(this, _.pick(options, pluginOptions));\n};\n($traceurRuntime.createClass)(BaseObject, {}, {}, Events);\nBaseObject.extend = extend;\nmodule.exports = BaseObject;\n\n\n},{\"./utils\":9,\"events\":\"events\",\"underscore\":\"underscore\"}],\"browser\":[function(require,module,exports){\n\"use strict\";\nvar Browser = function Browser() {};\n($traceurRuntime.createClass)(Browser, {}, {});\nvar hasLocalstorage = function() {\n try {\n localStorage.setItem('clappr', 'clappr');\n localStorage.removeItem('clappr');\n return true;\n } catch (e) {\n return false;\n }\n};\nBrowser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1);\nBrowser.isChrome = !!(navigator.userAgent.match(/chrome/i));\nBrowser.isFirefox = !!(navigator.userAgent.match(/firefox/i));\nBrowser.isLegacyIE = !!(window.ActiveXObject);\nBrowser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\\d/i));\nBrowser.isIE11 = !!(navigator.userAgent.match(/trident.*rv:11/i));\nBrowser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent));\nBrowser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent));\nBrowser.isWiiU = !!(/WiiU/i.test(navigator.userAgent));\nBrowser.isPS4 = !!(/PlayStation 4/i.test(navigator.userAgent));\nBrowser.hasLocalstorage = hasLocalstorage();\nmodule.exports = Browser;\n\n\n},{}],\"container_plugin\":[function(require,module,exports){\n\"use strict\";\nvar BaseObject = require('base_object');\nvar ContainerPlugin = function ContainerPlugin(options) {\n $traceurRuntime.superCall(this, $ContainerPlugin.prototype, \"constructor\", [options]);\n this.bindEvents();\n};\nvar $ContainerPlugin = ContainerPlugin;\n($traceurRuntime.createClass)(ContainerPlugin, {\n enable: function() {\n this.bindEvents();\n },\n disable: function() {\n this.stopListening();\n },\n bindEvents: function() {},\n destroy: function() {\n this.stopListening();\n }\n}, {}, BaseObject);\nmodule.exports = ContainerPlugin;\n\n\n},{\"base_object\":\"base_object\"}],\"container\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./container');\n\n\n},{\"./container\":10}],\"core_plugin\":[function(require,module,exports){\n\"use strict\";\nvar BaseObject = require('base_object');\nvar CorePlugin = function CorePlugin(core) {\n $traceurRuntime.superCall(this, $CorePlugin.prototype, \"constructor\", [core]);\n this.core = core;\n};\nvar $CorePlugin = CorePlugin;\n($traceurRuntime.createClass)(CorePlugin, {\n getExternalInterface: function() {\n return {};\n },\n destroy: function() {}\n}, {}, BaseObject);\nmodule.exports = CorePlugin;\n\n\n},{\"base_object\":\"base_object\"}],\"core\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./core');\n\n\n},{\"./core\":13}],\"events\":[function(require,module,exports){\n\"use strict\";\nvar _ = require('underscore');\nvar Log = require('../plugins/log').getInstance();\nvar slice = Array.prototype.slice;\nvar Events = function Events() {};\n($traceurRuntime.createClass)(Events, {\n on: function(name, callback, context) {\n if (!eventsApi(this, 'on', name, [callback, context]) || !callback)\n return this;\n this._events || (this._events = {});\n var events = this._events[name] || (this._events[name] = []);\n events.push({\n callback: callback,\n context: context,\n ctx: context || this\n });\n return this;\n },\n once: function(name, callback, context) {\n if (!eventsApi(this, 'once', name, [callback, context]) || !callback)\n return this;\n var self = this;\n var once = _.once(function() {\n self.off(name, once);\n callback.apply(this, arguments);\n });\n once._callback = callback;\n return this.on(name, once, context);\n },\n off: function(name, callback, context) {\n var retain,\n ev,\n events,\n names,\n i,\n l,\n j,\n k;\n if (!this._events || !eventsApi(this, 'off', name, [callback, context]))\n return this;\n if (!name && !callback && !context) {\n this._events = void 0;\n return this;\n }\n names = name ? [name] : _.keys(this._events);\n for (i = 0, l = names.length; i < l; i++) {\n name = names[i];\n events = this._events[name];\n if (events) {\n this._events[name] = retain = [];\n if (callback || context) {\n for (j = 0, k = events.length; j < k; j++) {\n ev = events[j];\n if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) {\n retain.push(ev);\n }\n }\n }\n if (!retain.length)\n delete this._events[name];\n }\n }\n return this;\n },\n trigger: function(name) {\n var klass = arguments[arguments.length - 1];\n Log.info(klass, name);\n if (!this._events)\n return this;\n var args = slice.call(arguments, 1);\n if (!eventsApi(this, 'trigger', name, args))\n return this;\n var events = this._events[name];\n var allEvents = this._events.all;\n if (events)\n triggerEvents(events, args);\n if (allEvents)\n triggerEvents(allEvents, arguments);\n return this;\n },\n stopListening: function(obj, name, callback) {\n var listeningTo = this._listeningTo;\n if (!listeningTo)\n return this;\n var remove = !name && !callback;\n if (!callback && typeof name === 'object')\n callback = this;\n if (obj)\n (listeningTo = {})[obj._listenId] = obj;\n for (var id in listeningTo) {\n obj = listeningTo[id];\n obj.off(name, callback, this);\n if (remove || _.isEmpty(obj._events))\n delete this._listeningTo[id];\n }\n return this;\n }\n}, {});\nvar eventSplitter = /\\s+/;\nvar eventsApi = function(obj, action, name, rest) {\n if (!name)\n return true;\n if (typeof name === 'object') {\n for (var key in name) {\n obj[action].apply(obj, [key, name[key]].concat(rest));\n }\n return false;\n }\n if (eventSplitter.test(name)) {\n var names = name.split(eventSplitter);\n for (var i = 0,\n l = names.length; i < l; i++) {\n obj[action].apply(obj, [names[i]].concat(rest));\n }\n return false;\n }\n return true;\n};\nvar triggerEvents = function(events, args) {\n var ev,\n i = -1,\n l = events.length,\n a1 = args[0],\n a2 = args[1],\n a3 = args[2];\n switch (args.length) {\n case 0:\n while (++i < l)\n (ev = events[i]).callback.call(ev.ctx);\n return;\n case 1:\n while (++i < l)\n (ev = events[i]).callback.call(ev.ctx, a1);\n return;\n case 2:\n while (++i < l)\n (ev = events[i]).callback.call(ev.ctx, a1, a2);\n return;\n case 3:\n while (++i < l)\n (ev = events[i]).callback.call(ev.ctx, a1, a2, a3);\n return;\n default:\n while (++i < l)\n (ev = events[i]).callback.apply(ev.ctx, args);\n return;\n }\n};\nvar listenMethods = {\n listenTo: 'on',\n listenToOnce: 'once'\n};\n_.each(listenMethods, function(implementation, method) {\n Events.prototype[method] = function(obj, name, callback) {\n var listeningTo = this._listeningTo || (this._listeningTo = {});\n var id = obj._listenId || (obj._listenId = _.uniqueId('l'));\n listeningTo[id] = obj;\n if (!callback && typeof name === 'object')\n callback = this;\n obj[implementation](name, callback, this);\n return this;\n };\n});\nEvents.PLAYER_RESIZE = 'player:resize';\nEvents.PLAYBACK_PROGRESS = 'playback:progress';\nEvents.PLAYBACK_TIMEUPDATE = 'playback:timeupdate';\nEvents.PLAYBACK_READY = 'playback:ready';\nEvents.PLAYBACK_BUFFERING = 'playback:buffering';\nEvents.PLAYBACK_BUFFERFULL = 'playback:bufferfull';\nEvents.PLAYBACK_SETTINGSUPDATE = 'playback:settingsupdate';\nEvents.PLAYBACK_LOADEDMETADATA = 'playback:loadedmetadata';\nEvents.PLAYBACK_HIGHDEFINITIONUPDATE = 'playback:highdefinitionupdate';\nEvents.PLAYBACK_BITRATE = 'playback:bitrate';\nEvents.PLAYBACK_PLAYBACKSTATE = 'playback:playbackstate';\nEvents.PLAYBACK_DVR = 'playback:dvr';\nEvents.PLAYBACK_MEDIACONTROL_DISABLE = 'playback:mediacontrol:disable';\nEvents.PLAYBACK_MEDIACONTROL_ENABLE = 'playback:mediacontrol:enable';\nEvents.PLAYBACK_ENDED = 'playback:ended';\nEvents.PLAYBACK_PLAY = 'playback:play';\nEvents.PLAYBACK_ERROR = 'playback:error';\nEvents.PLAYBACK_STATS_ADD = 'playback:stats:add';\nEvents.CONTAINER_PLAYBACKSTATE = 'container:playbackstate';\nEvents.CONTAINER_PLAYBACKDVRSTATECHANGED = 'container:dvr';\nEvents.CONTAINER_BITRATE = 'container:bitrate';\nEvents.CONTAINER_STATS_REPORT = 'container:stats:report';\nEvents.CONTAINER_DESTROYED = 'container:destroyed';\nEvents.CONTAINER_READY = 'container:ready';\nEvents.CONTAINER_ERROR = 'container:error';\nEvents.CONTAINER_LOADEDMETADATA = 'container:loadedmetadata';\nEvents.CONTAINER_TIMEUPDATE = 'container:timeupdate';\nEvents.CONTAINER_PROGRESS = 'container:progress';\nEvents.CONTAINER_PLAY = 'container:play';\nEvents.CONTAINER_STOP = 'container:stop';\nEvents.CONTAINER_PAUSE = 'container:pause';\nEvents.CONTAINER_ENDED = 'container:ended';\nEvents.CONTAINER_CLICK = 'container:click';\nEvents.CONTAINER_SEEK = 'container:seek';\nEvents.CONTAINER_VOLUME = 'container:volume';\nEvents.CONTAINER_FULLSCREEN = 'container:fullscreen';\nEvents.CONTAINER_STATE_BUFFERING = 'container:state:buffering';\nEvents.CONTAINER_STATE_BUFFERFULL = 'container:state:bufferfull';\nEvents.CONTAINER_SETTINGSUPDATE = 'container:settingsupdate';\nEvents.CONTAINER_HIGHDEFINITIONUPDATE = 'container:highdefinitionupdate';\nEvents.CONTAINER_MEDIACONTROL_DISABLE = 'container:mediacontrol:disable';\nEvents.CONTAINER_MEDIACONTROL_ENABLE = 'container:mediacontrol:enable';\nEvents.CONTAINER_STATS_ADD = 'container:stats:add';\nEvents.MEDIACONTROL_RENDERED = 'mediacontrol:rendered';\nEvents.MEDIACONTROL_FULLSCREEN = 'mediacontrol:fullscreen';\nEvents.MEDIACONTROL_SHOW = 'mediacontrol:show';\nEvents.MEDIACONTROL_HIDE = 'mediacontrol:hide';\nEvents.MEDIACONTROL_MOUSEMOVE_SEEKBAR = 'mediacontrol:mousemove:seekbar';\nEvents.MEDIACONTROL_MOUSELEAVE_SEEKBAR = 'mediacontrol:mouseleave:seekbar';\nEvents.MEDIACONTROL_PLAYING = 'mediacontrol:playing';\nEvents.MEDIACONTROL_NOTPLAYING = 'mediacontrol:notplaying';\nEvents.MEDIACONTROL_CONTAINERCHANGED = 'mediacontrol:containerchanged';\nmodule.exports = Events;\n\n\n},{\"../plugins/log\":39,\"underscore\":\"underscore\"}],\"flash\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./flash');\n\n\n},{\"./flash\":24}],\"hls\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./hls');\n\n\n},{\"./hls\":25}],\"html5_audio\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./html5_audio');\n\n\n},{\"./html5_audio\":26}],\"html5_video\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./html5_video');\n\n\n},{\"./html5_video\":27}],\"html_img\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./html_img');\n\n\n},{\"./html_img\":28}],\"media_control\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./media_control');\n\n\n},{\"./media_control\":20}],\"mediator\":[function(require,module,exports){\n\"use strict\";\nvar Events = require('events');\nvar events = new Events();\nvar Mediator = function Mediator() {};\n($traceurRuntime.createClass)(Mediator, {}, {});\nMediator.on = function(name, callback, context) {\n events.on(name, callback, context);\n return;\n};\nMediator.once = function(name, callback, context) {\n events.once(name, callback, context);\n return;\n};\nMediator.off = function(name, callback, context) {\n events.off(name, callback, context);\n return;\n};\nMediator.trigger = function(name, opts) {\n events.trigger(name, opts);\n return;\n};\nMediator.stopListening = function(obj, name, callback) {\n events.stopListening(obj, name, callback);\n return;\n};\nmodule.exports = Mediator;\n\n\n},{\"events\":\"events\"}],\"playback\":[function(require,module,exports){\n\"use strict\";\nvar UIObject = require('ui_object');\nvar Playback = function Playback(options) {\n $traceurRuntime.superCall(this, $Playback.prototype, \"constructor\", [options]);\n this.settings = {};\n};\nvar $Playback = Playback;\n($traceurRuntime.createClass)(Playback, {\n play: function() {},\n pause: function() {},\n stop: function() {},\n seek: function(time) {},\n getDuration: function() {\n return 0;\n },\n isPlaying: function() {\n return false;\n },\n getPlaybackType: function() {\n return 'no_op';\n },\n isHighDefinitionInUse: function() {\n return false;\n },\n volume: function(value) {},\n destroy: function() {\n this.$el.remove();\n }\n}, {}, UIObject);\nPlayback.canPlay = (function(source) {\n return false;\n});\nmodule.exports = Playback;\n\n\n},{\"ui_object\":\"ui_object\"}],\"player_info\":[function(require,module,exports){\n\"use strict\";\nvar PlayerInfo = {\n options: {},\n playbackPlugins: [],\n currentSize: {\n width: 0,\n height: 0\n }\n};\nmodule.exports = PlayerInfo;\n\n\n},{}],\"poster\":[function(require,module,exports){\n\"use strict\";\nmodule.exports = require('./poster');\n\n\n},{\"./poster\":41}],\"ui_container_plugin\":[function(require,module,exports){\n\"use strict\";\nvar UIObject = require('ui_object');\nvar UIContainerPlugin = function UIContainerPlugin(options) {\n $traceurRuntime.superCall(this, $UIContainerPlugin.prototype, \"constructor\", [options]);\n this.enabled = true;\n this.bindEvents();\n};\nvar $UIContainerPlugin = UIContainerPlugin;\n($traceurRuntime.createClass)(UIContainerPlugin, {\n enable: function() {\n this.bindEvents();\n this.$el.show();\n this.enabled = true;\n },\n disable: function() {\n this.stopListening();\n this.$el.hide();\n this.enabled = false;\n },\n bindEvents: function() {},\n destroy: function() {\n this.remove();\n }\n}, {}, UIObject);\nmodule.exports = UIContainerPlugin;\n\n\n},{\"ui_object\":\"ui_object\"}],\"ui_core_plugin\":[function(require,module,exports){\n\"use strict\";\nvar UIObject = require('ui_object');\nvar UICorePlugin = function UICorePlugin(core) {\n $traceurRuntime.superCall(this, $UICorePlugin.prototype, \"constructor\", [core]);\n this.core = core;\n this.enabled = true;\n this.bindEvents();\n this.render();\n};\nvar $UICorePlugin = UICorePlugin;\n($traceurRuntime.createClass)(UICorePlugin, {\n bindEvents: function() {},\n getExternalInterface: function() {\n return {};\n },\n enable: function() {\n this.bindEvents();\n this.$el.show();\n this.enabled = true;\n },\n disable: function() {\n this.stopListening();\n this.$el.hide();\n this.enabled = false;\n },\n destroy: function() {\n this.remove();\n },\n render: function() {\n this.$el.html(this.template());\n this.$el.append(this.styler.getStyleFor(this.name));\n this.core.$el.append(this.el);\n return this;\n }\n}, {}, UIObject);\nmodule.exports = UICorePlugin;\n\n\n},{\"ui_object\":\"ui_object\"}],\"ui_object\":[function(require,module,exports){\n\"use strict\";\nvar $ = require('zepto');\nvar _ = require('underscore');\nvar extend = require('./utils').extend;\nvar BaseObject = require('base_object');\nvar delegateEventSplitter = /^(\\S+)\\s*(.*)$/;\nvar UIObject = function UIObject(options) {\n $traceurRuntime.superCall(this, $UIObject.prototype, \"constructor\", [options]);\n this.cid = _.uniqueId('c');\n this._ensureElement();\n this.delegateEvents();\n};\nvar $UIObject = UIObject;\n($traceurRuntime.createClass)(UIObject, {\n get tagName() {\n return 'div';\n },\n $: function(selector) {\n return this.$el.find(selector);\n },\n render: function() {\n return this;\n },\n remove: function() {\n this.$el.remove();\n this.stopListening();\n return this;\n },\n setElement: function(element, delegate) {\n if (this.$el)\n this.undelegateEvents();\n this.$el = element instanceof $ ? element : $(element);\n this.el = this.$el[0];\n if (delegate !== false)\n this.delegateEvents();\n return this;\n },\n delegateEvents: function(events) {\n if (!(events || (events = _.result(this, 'events'))))\n return this;\n this.undelegateEvents();\n for (var key in events) {\n var method = events[key];\n if (!_.isFunction(method))\n method = this[events[key]];\n if (!method)\n continue;\n var match = key.match(delegateEventSplitter);\n var eventName = match[1],\n selector = match[2];\n method = _.bind(method, this);\n eventName += '.delegateEvents' + this.cid;\n if (selector === '') {\n this.$el.on(eventName, method);\n } else {\n this.$el.on(eventName, selector, method);\n }\n }\n return this;\n },\n undelegateEvents: function() {\n this.$el.off('.delegateEvents' + this.cid);\n return this;\n },\n _ensureElement: function() {\n if (!this.el) {\n var attrs = _.extend({}, _.result(this, 'attributes'));\n if (this.id)\n attrs.id = _.result(this, 'id');\n if (this.className)\n attrs['class'] = _.result(this, 'className');\n var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs);\n this.setElement($el, false);\n } else {\n this.setElement(_.result(this, 'el'), false);\n }\n }\n}, {}, BaseObject);\nUIObject.extend = extend;\nmodule.exports = UIObject;\n\n\n},{\"./utils\":9,\"base_object\":\"base_object\",\"underscore\":\"underscore\",\"zepto\":\"zepto\"}],\"underscore\":[function(require,module,exports){\n// Underscore.js 1.7.0\n// http://underscorejs.org\n// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Underscore may be freely distributed under the MIT license.\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `exports` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n var\n push = ArrayProto.push,\n slice = ArrayProto.slice,\n concat = ArrayProto.concat,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind;\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) {\n if (obj instanceof _) return obj;\n if (!(this instanceof _)) return new _(obj);\n this._wrapped = obj;\n };\n\n // Export the Underscore object for **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root._ = _;\n }\n\n // Current version.\n _.VERSION = '1.7.0';\n\n // Internal function that returns an efficient (for current engines) version\n // of the passed-in callback, to be repeatedly applied in other Underscore\n // functions.\n var createCallback = function(func, context, argCount) {\n if (context === void 0) return func;\n switch (argCount == null ? 3 : argCount) {\n case 1: return function(value) {\n return func.call(context, value);\n };\n case 2: return function(value, other) {\n return func.call(context, value, other);\n };\n case 3: return function(value, index, collection) {\n return func.call(context, value, index, collection);\n };\n case 4: return function(accumulator, value, index, collection) {\n return func.call(context, accumulator, value, index, collection);\n };\n }\n return function() {\n return func.apply(context, arguments);\n };\n };\n\n // A mostly-internal function to generate callbacks that can be applied\n // to each element in a collection, returning the desired result — either\n // identity, an arbitrary callback, a property matcher, or a property accessor.\n _.iteratee = function(value, context, argCount) {\n if (value == null) return _.identity;\n if (_.isFunction(value)) return createCallback(value, context, argCount);\n if (_.isObject(value)) return _.matches(value);\n return _.property(value);\n };\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles raw objects in addition to array-likes. Treats all\n // sparse array-likes as if they were dense.\n _.each = _.forEach = function(obj, iteratee, context) {\n if (obj == null) return obj;\n iteratee = createCallback(iteratee, context);\n var i, length = obj.length;\n if (length === +length) {\n for (i = 0; i < length; i++) {\n iteratee(obj[i], i, obj);\n }\n } else {\n var keys = _.keys(obj);\n for (i = 0, length = keys.length; i < length; i++) {\n iteratee(obj[keys[i]], keys[i], obj);\n }\n }\n return obj;\n };\n\n // Return the results of applying the iteratee to each element.\n _.map = _.collect = function(obj, iteratee, context) {\n if (obj == null) return [];\n iteratee = _.iteratee(iteratee, context);\n var keys = obj.length !== +obj.length && _.keys(obj),\n length = (keys || obj).length,\n results = Array(length),\n currentKey;\n for (var index = 0; index < length; index++) {\n currentKey = keys ? keys[index] : index;\n results[index] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n var reduceError = 'Reduce of empty array with no initial value';\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`.\n _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {\n if (obj == null) obj = [];\n iteratee = createCallback(iteratee, context, 4);\n var keys = obj.length !== +obj.length && _.keys(obj),\n length = (keys || obj).length,\n index = 0, currentKey;\n if (arguments.length < 3) {\n if (!length) throw new TypeError(reduceError);\n memo = obj[keys ? keys[index++] : index++];\n }\n for (; index < length; index++) {\n currentKey = keys ? keys[index] : index;\n memo = iteratee(memo, obj[currentKey], currentKey, obj);\n }\n return memo;\n };\n\n // The right-associative version of reduce, also known as `foldr`.\n _.reduceRight = _.foldr = function(obj, iteratee, memo, context) {\n if (obj == null) obj = [];\n iteratee = createCallback(iteratee, context, 4);\n var keys = obj.length !== + obj.length && _.keys(obj),\n index = (keys || obj).length,\n currentKey;\n if (arguments.length < 3) {\n if (!index) throw new TypeError(reduceError);\n memo = obj[keys ? keys[--index] : --index];\n }\n while (index--) {\n currentKey = keys ? keys[index] : index;\n memo = iteratee(memo, obj[currentKey], currentKey, obj);\n }\n return memo;\n };\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, predicate, context) {\n var result;\n predicate = _.iteratee(predicate, context);\n _.some(obj, function(value, index, list) {\n if (predicate(value, index, list)) {\n result = value;\n return true;\n }\n });\n return result;\n };\n\n // Return all the elements that pass a truth test.\n // Aliased as `select`.\n _.filter = _.select = function(obj, predicate, context) {\n var results = [];\n if (obj == null) return results;\n predicate = _.iteratee(predicate, context);\n _.each(obj, function(value, index, list) {\n if (predicate(value, index, list)) results.push(value);\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, predicate, context) {\n return _.filter(obj, _.negate(_.iteratee(predicate)), context);\n };\n\n // Determine whether all of the elements match a truth test.\n // Aliased as `all`.\n _.every = _.all = function(obj, predicate, context) {\n if (obj == null) return true;\n predicate = _.iteratee(predicate, context);\n var keys = obj.length !== +obj.length && _.keys(obj),\n length = (keys || obj).length,\n index, currentKey;\n for (index = 0; index < length; index++) {\n currentKey = keys ? keys[index] : index;\n if (!predicate(obj[currentKey], currentKey, obj)) return false;\n }\n return true;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Aliased as `any`.\n _.some = _.any = function(obj, predicate, context) {\n if (obj == null) return false;\n predicate = _.iteratee(predicate, context);\n var keys = obj.length !== +obj.length && _.keys(obj),\n length = (keys || obj).length,\n index, currentKey;\n for (index = 0; index < length; index++) {\n currentKey = keys ? keys[index] : index;\n if (predicate(obj[currentKey], currentKey, obj)) return true;\n }\n return false;\n };\n\n // Determine if the array or object contains a given value (using `===`).\n // Aliased as `include`.\n _.contains = _.include = function(obj, target) {\n if (obj == null) return false;\n if (obj.length !== +obj.length) obj = _.values(obj);\n return _.indexOf(obj, target) >= 0;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n var isFunc = _.isFunction(method);\n return _.map(obj, function(value) {\n return (isFunc ? method : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, _.property(key));\n };\n\n // Convenience version of a common use case of `filter`: selecting only objects\n // containing specific `key:value` pairs.\n _.where = function(obj, attrs) {\n return _.filter(obj, _.matches(attrs));\n };\n\n // Convenience version of a common use case of `find`: getting the first object\n // containing specific `key:value` pairs.\n _.findWhere = function(obj, attrs) {\n return _.find(obj, _.matches(attrs));\n };\n\n // Return the maximum element (or element-based computation).\n _.max = function(obj, iteratee, context) {\n var result = -Infinity, lastComputed = -Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = obj.length === +obj.length ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value > result) {\n result = value;\n }\n }\n } else {\n iteratee = _.iteratee(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed > lastComputed || computed === -Infinity && result === -Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iteratee, context) {\n var result = Infinity, lastComputed = Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = obj.length === +obj.length ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value < result) {\n result = value;\n }\n }\n } else {\n iteratee = _.iteratee(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed < lastComputed || computed === Infinity && result === Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Shuffle a collection, using the modern version of the\n // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).\n _.shuffle = function(obj) {\n var set = obj && obj.length === +obj.length ? obj : _.values(obj);\n var length = set.length;\n var shuffled = Array(length);\n for (var index = 0, rand; index < length; index++) {\n rand = _.random(0, index);\n if (rand !== index) shuffled[index] = shuffled[rand];\n shuffled[rand] = set[index];\n }\n return shuffled;\n };\n\n // Sample **n** random values from a collection.\n // If **n** is not specified, returns a single random element.\n // The internal `guard` argument allows it to work with `map`.\n _.sample = function(obj, n, guard) {\n if (n == null || guard) {\n if (obj.length !== +obj.length) obj = _.values(obj);\n return obj[_.random(obj.length - 1)];\n }\n return _.shuffle(obj).slice(0, Math.max(0, n));\n };\n\n // Sort the object's values by a criterion produced by an iteratee.\n _.sortBy = function(obj, iteratee, context) {\n iteratee = _.iteratee(iteratee, context);\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value: value,\n index: index,\n criteria: iteratee(value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria;\n var b = right.criteria;\n if (a !== b) {\n if (a > b || a === void 0) return 1;\n if (a < b || b === void 0) return -1;\n }\n return left.index - right.index;\n }), 'value');\n };\n\n // An internal function used for aggregate \"group by\" operations.\n var group = function(behavior) {\n return function(obj, iteratee, context) {\n var result = {};\n iteratee = _.iteratee(iteratee, context);\n _.each(obj, function(value, index) {\n var key = iteratee(value, index, obj);\n behavior(result, value, key);\n });\n return result;\n };\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key].push(value); else result[key] = [value];\n });\n\n // Indexes the object's values by a criterion, similar to `groupBy`, but for\n // when you know that your index values will be unique.\n _.indexBy = group(function(result, value, key) {\n result[key] = value;\n });\n\n // Counts instances of an object that group by a certain criterion. Pass\n // either a string attribute to count by, or a function that returns the\n // criterion.\n _.countBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key]++; else result[key] = 1;\n });\n\n // Use a comparator function to figure out the smallest index at which\n // an object should be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iteratee, context) {\n iteratee = _.iteratee(iteratee, context, 1);\n var value = iteratee(obj);\n var low = 0, high = array.length;\n while (low < high) {\n var mid = low + high >>> 1;\n if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;\n }\n return low;\n };\n\n // Safely create a real, live array from anything iterable.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (obj.length === +obj.length) return _.map(obj, _.identity);\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n if (obj == null) return 0;\n return obj.length === +obj.length ? obj.length : _.keys(obj).length;\n };\n\n // Split a collection into two arrays: one whose elements all satisfy the given\n // predicate, and one whose elements all do not satisfy the predicate.\n _.partition = function(obj, predicate, context) {\n predicate = _.iteratee(predicate, context);\n var pass = [], fail = [];\n _.each(obj, function(value, key, obj) {\n (predicate(value, key, obj) ? pass : fail).push(value);\n });\n return [pass, fail];\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[0];\n if (n < 0) return [];\n return slice.call(array, 0, n);\n };\n\n // Returns everything but the last entry of the array. Especially useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N. The **guard** check allows it to work with\n // `_.map`.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array. The **guard** check allows it to work with `_.map`.\n _.last = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[array.length - 1];\n return slice.call(array, Math.max(array.length - n, 0));\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.\n // Especially useful on the arguments object. Passing an **n** will return\n // the rest N values in the array. The **guard**\n // check allows it to work with `_.map`.\n _.rest = _.tail = _.drop = function(array, n, guard) {\n return slice.call(array, n == null || guard ? 1 : n);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, _.identity);\n };\n\n // Internal implementation of a recursive `flatten` function.\n var flatten = function(input, shallow, strict, output) {\n if (shallow && _.every(input, _.isArray)) {\n return concat.apply(output, input);\n }\n for (var i = 0, length = input.length; i < length; i++) {\n var value = input[i];\n if (!_.isArray(value) && !_.isArguments(value)) {\n if (!strict) output.push(value);\n } else if (shallow) {\n push.apply(output, value);\n } else {\n flatten(value, shallow, strict, output);\n }\n }\n return output;\n };\n\n // Flatten out an array, either recursively (by default), or just one level.\n _.flatten = function(array, shallow) {\n return flatten(array, shallow, false, []);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iteratee, context) {\n if (array == null) return [];\n if (!_.isBoolean(isSorted)) {\n context = iteratee;\n iteratee = isSorted;\n isSorted = false;\n }\n if (iteratee != null) iteratee = _.iteratee(iteratee, context);\n var result = [];\n var seen = [];\n for (var i = 0, length = array.length; i < length; i++) {\n var value = array[i];\n if (isSorted) {\n if (!i || seen !== value) result.push(value);\n seen = value;\n } else if (iteratee) {\n var computed = iteratee(value, i, array);\n if (_.indexOf(seen, computed) < 0) {\n seen.push(computed);\n result.push(value);\n }\n } else if (_.indexOf(result, value) < 0) {\n result.push(value);\n }\n }\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(flatten(arguments, true, true, []));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays.\n _.intersection = function(array) {\n if (array == null) return [];\n var result = [];\n var argsLength = arguments.length;\n for (var i = 0, length = array.length; i < length; i++) {\n var item = array[i];\n if (_.contains(result, item)) continue;\n for (var j = 1; j < argsLength; j++) {\n if (!_.contains(arguments[j], item)) break;\n }\n if (j === argsLength) result.push(item);\n }\n return result;\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = flatten(slice.call(arguments, 1), true, true, []);\n return _.filter(array, function(value){\n return !_.contains(rest, value);\n });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function(array) {\n if (array == null) return [];\n var length = _.max(arguments, 'length').length;\n var results = Array(length);\n for (var i = 0; i < length; i++) {\n results[i] = _.pluck(arguments, i);\n }\n return results;\n };\n\n // Converts lists into objects. Pass either a single array of `[key, value]`\n // pairs, or two parallel arrays of the same length -- one of keys, and one of\n // the corresponding values.\n _.object = function(list, values) {\n if (list == null) return {};\n var result = {};\n for (var i = 0, length = list.length; i < length; i++) {\n if (values) {\n result[list[i]] = values[i];\n } else {\n result[list[i][0]] = list[i][1];\n }\n }\n return result;\n };\n\n // Return the position of the first occurrence of an item in an array,\n // or -1 if the item is not included in the array.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = function(array, item, isSorted) {\n if (array == null) return -1;\n var i = 0, length = array.length;\n if (isSorted) {\n if (typeof isSorted == 'number') {\n i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;\n } else {\n i = _.sortedIndex(array, item);\n return array[i] === item ? i : -1;\n }\n }\n for (; i < length; i++) if (array[i] === item) return i;\n return -1;\n };\n\n _.lastIndexOf = function(array, item, from) {\n if (array == null) return -1;\n var idx = array.length;\n if (typeof from == 'number') {\n idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);\n }\n while (--idx >= 0) if (array[idx] === item) return idx;\n return -1;\n };\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (arguments.length <= 1) {\n stop = start || 0;\n start = 0;\n }\n step = step || 1;\n\n var length = Math.max(Math.ceil((stop - start) / step), 0);\n var range = Array(length);\n\n for (var idx = 0; idx < length; idx++, start += step) {\n range[idx] = start;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Reusable constructor function for prototype setting.\n var Ctor = function(){};\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if\n // available.\n _.bind = function(func, context) {\n var args, bound;\n if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');\n args = slice.call(arguments, 2);\n bound = function() {\n if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));\n Ctor.prototype = func.prototype;\n var self = new Ctor;\n Ctor.prototype = null;\n var result = func.apply(self, args.concat(slice.call(arguments)));\n if (_.isObject(result)) return result;\n return self;\n };\n return bound;\n };\n\n // Partially apply a function by creating a version that has had some of its\n // arguments pre-filled, without changing its dynamic `this` context. _ acts\n // as a placeholder, allowing any combination of arguments to be pre-filled.\n _.partial = function(func) {\n var boundArgs = slice.call(arguments, 1);\n return function() {\n var position = 0;\n var args = boundArgs.slice();\n for (var i = 0, length = args.length; i < length; i++) {\n if (args[i] === _) args[i] = arguments[position++];\n }\n while (position < arguments.length) args.push(arguments[position++]);\n return func.apply(this, args);\n };\n };\n\n // Bind a number of an object's methods to that object. Remaining arguments\n // are the method names to be bound. Useful for ensuring that all callbacks\n // defined on an object belong to it.\n _.bindAll = function(obj) {\n var i, length = arguments.length, key;\n if (length <= 1) throw new Error('bindAll must be passed function names');\n for (i = 1; i < length; i++) {\n key = arguments[i];\n obj[key] = _.bind(obj[key], obj);\n }\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memoize = function(key) {\n var cache = memoize.cache;\n var address = hasher ? hasher.apply(this, arguments) : key;\n if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);\n return cache[address];\n };\n memoize.cache = {};\n return memoize;\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){\n return func.apply(null, args);\n }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = function(func) {\n return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));\n };\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time. Normally, the throttled function will run\n // as much as it can, without ever going more than once per `wait` duration;\n // but if you'd like to disable the execution on the leading edge, pass\n // `{leading: false}`. To disable execution on the trailing edge, ditto.\n _.throttle = function(func, wait, options) {\n var context, args, result;\n var timeout = null;\n var previous = 0;\n if (!options) options = {};\n var later = function() {\n previous = options.leading === false ? 0 : _.now();\n timeout = null;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n };\n return function() {\n var now = _.now();\n if (!previous && options.leading === false) previous = now;\n var remaining = wait - (now - previous);\n context = this;\n args = arguments;\n if (remaining <= 0 || remaining > wait) {\n clearTimeout(timeout);\n timeout = null;\n previous = now;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(later, remaining);\n }\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout, args, context, timestamp, result;\n\n var later = function() {\n var last = _.now() - timestamp;\n\n if (last < wait && last > 0) {\n timeout = setTimeout(later, wait - last);\n } else {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n }\n }\n };\n\n return function() {\n context = this;\n args = arguments;\n timestamp = _.now();\n var callNow = immediate && !timeout;\n if (!timeout) timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n context = args = null;\n }\n\n return result;\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return _.partial(wrapper, func);\n };\n\n // Returns a negated version of the passed-in predicate.\n _.negate = function(predicate) {\n return function() {\n return !predicate.apply(this, arguments);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var args = arguments;\n var start = args.length - 1;\n return function() {\n var i = start;\n var result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n };\n\n // Returns a function that will only be executed after being called N times.\n _.after = function(times, func) {\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n };\n\n // Returns a function that will only be executed before being called N times.\n _.before = function(times, func) {\n var memo;\n return function() {\n if (--times > 0) {\n memo = func.apply(this, arguments);\n } else {\n func = null;\n }\n return memo;\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = _.partial(_.before, 2);\n\n // Object Functions\n // ----------------\n\n // Retrieve the names of an object's properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = function(obj) {\n if (!_.isObject(obj)) return [];\n if (nativeKeys) return nativeKeys(obj);\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys.push(key);\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var values = Array(length);\n for (var i = 0; i < length; i++) {\n values[i] = obj[keys[i]];\n }\n return values;\n };\n\n // Convert an object into a list of `[key, value]` pairs.\n _.pairs = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var pairs = Array(length);\n for (var i = 0; i < length; i++) {\n pairs[i] = [keys[i], obj[keys[i]]];\n }\n return pairs;\n };\n\n // Invert the keys and values of an object. The values must be serializable.\n _.invert = function(obj) {\n var result = {};\n var keys = _.keys(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n result[obj[keys[i]]] = keys[i];\n }\n return result;\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = function(obj) {\n if (!_.isObject(obj)) return obj;\n var source, prop;\n for (var i = 1, length = arguments.length; i < length; i++) {\n source = arguments[i];\n for (prop in source) {\n if (hasOwnProperty.call(source, prop)) {\n obj[prop] = source[prop];\n }\n }\n }\n return obj;\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(obj, iteratee, context) {\n var result = {}, key;\n if (obj == null) return result;\n if (_.isFunction(iteratee)) {\n iteratee = createCallback(iteratee, context);\n for (key in obj) {\n var value = obj[key];\n if (iteratee(value, key, obj)) result[key] = value;\n }\n } else {\n var keys = concat.apply([], slice.call(arguments, 1));\n obj = new Object(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n key = keys[i];\n if (key in obj) result[key] = obj[key];\n }\n }\n return result;\n };\n\n // Return a copy of the object without the blacklisted properties.\n _.omit = function(obj, iteratee, context) {\n if (_.isFunction(iteratee)) {\n iteratee = _.negate(iteratee);\n } else {\n var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);\n iteratee = function(value, key) {\n return !_.contains(keys, key);\n };\n }\n return _.pick(obj, iteratee, context);\n };\n\n // Fill in a given object with default properties.\n _.defaults = function(obj) {\n if (!_.isObject(obj)) return obj;\n for (var i = 1, length = arguments.length; i < length; i++) {\n var source = arguments[i];\n for (var prop in source) {\n if (obj[prop] === void 0) obj[prop] = source[prop];\n }\n }\n return obj;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Internal recursive comparison function for `isEqual`.\n var eq = function(a, b, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) return a !== 0 || 1 / a === 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a instanceof _) a = a._wrapped;\n if (b instanceof _) b = b._wrapped;\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case '[object RegExp]':\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return '' + a === '' + b;\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN\n if (+a !== +a) return +b !== +b;\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n }\n if (typeof a != 'object' || typeof b != 'object') return false;\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) return bStack[length] === b;\n }\n // Objects with different constructors are not equivalent, but `Object`s\n // from different frames are.\n var aCtor = a.constructor, bCtor = b.constructor;\n if (\n aCtor !== bCtor &&\n // Handle Object.create(x) cases\n 'constructor' in a && 'constructor' in b &&\n !(_.isFunction(aCtor) && aCtor instanceof aCtor &&\n _.isFunction(bCtor) && bCtor instanceof bCtor)\n ) {\n return false;\n }\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n var size, result;\n // Recursively compare objects and arrays.\n if (className === '[object Array]') {\n // Compare array lengths to determine if a deep comparison is necessary.\n size = a.length;\n result = size === b.length;\n if (result) {\n // Deep compare the contents, ignoring non-numeric properties.\n while (size--) {\n if (!(result = eq(a[size], b[size], aStack, bStack))) break;\n }\n }\n } else {\n // Deep compare objects.\n var keys = _.keys(a), key;\n size = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n result = _.keys(b).length === size;\n if (result) {\n while (size--) {\n // Deep compare each member\n key = keys[size];\n if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;\n }\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return result;\n };\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b, [], []);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;\n for (var key in obj) if (_.has(obj, key)) return false;\n return true;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.\n _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {\n _['is' + name] = function(obj) {\n return toString.call(obj) === '[object ' + name + ']';\n };\n });\n\n // Define a fallback version of the method in browsers (ahem, IE), where\n // there isn't any inspectable \"Arguments\" type.\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return _.has(obj, 'callee');\n };\n }\n\n // Optimize `isFunction` if appropriate. Work around an IE 11 bug.\n if (typeof /./ !== 'function') {\n _.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n }\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return isFinite(obj) && !isNaN(parseFloat(obj));\n };\n\n // Is the given value `NaN`? (NaN is the only number which does not equal itself).\n _.isNaN = function(obj) {\n return _.isNumber(obj) && obj !== +obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) === '[object Boolean]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Shortcut function for checking if an object has a given property directly\n // on itself (in other words, not on a prototype).\n _.has = function(obj, key) {\n return obj != null && hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iteratees.\n _.identity = function(value) {\n return value;\n };\n\n _.constant = function(value) {\n return function() {\n return value;\n };\n };\n\n _.noop = function(){};\n\n _.property = function(key) {\n return function(obj) {\n return obj[key];\n };\n };\n\n // Returns a predicate for checking whether an object has a given set of `key:value` pairs.\n _.matches = function(attrs) {\n var pairs = _.pairs(attrs), length = pairs.length;\n return function(obj) {\n if (obj == null) return !length;\n obj = new Object(obj);\n for (var i = 0; i < length; i++) {\n var pair = pairs[i], key = pair[0];\n if (pair[1] !== obj[key] || !(key in obj)) return false;\n }\n return true;\n };\n };\n\n // Run a function **n** times.\n _.times = function(n, iteratee, context) {\n var accum = Array(Math.max(0, n));\n iteratee = createCallback(iteratee, context, 1);\n for (var i = 0; i < n; i++) accum[i] = iteratee(i);\n return accum;\n };\n\n // Return a random integer between min and max (inclusive).\n _.random = function(min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n };\n\n // A (possibly faster) way to get the current timestamp as an integer.\n _.now = Date.now || function() {\n return new Date().getTime();\n };\n\n // List of HTML entities for escaping.\n var escapeMap = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '`': '&#x60;'\n };\n var unescapeMap = _.invert(escapeMap);\n\n // Functions for escaping and unescaping strings to/from HTML interpolation.\n var createEscaper = function(map) {\n var escaper = function(match) {\n return map[match];\n };\n // Regexes for identifying a key that needs to be escaped\n var source = '(?:' + _.keys(map).join('|') + ')';\n var testRegexp = RegExp(source);\n var replaceRegexp = RegExp(source, 'g');\n return function(string) {\n string = string == null ? '' : '' + string;\n return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;\n };\n };\n _.escape = createEscaper(escapeMap);\n _.unescape = createEscaper(unescapeMap);\n\n // If the value of the named `property` is a function then invoke it with the\n // `object` as context; otherwise, return it.\n _.result = function(object, property) {\n if (object == null) return void 0;\n var value = object[property];\n return _.isFunction(value) ? object[property]() : value;\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = ++idCounter + '';\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /(.)^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n \"'\": \"'\",\n '\\\\': '\\\\',\n '\\r': 'r',\n '\\n': 'n',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n var escaper = /\\\\|'|\\r|\\n|\\u2028|\\u2029/g;\n\n var escapeChar = function(match) {\n return '\\\\' + escapes[match];\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n // NB: `oldSettings` only exists for backwards compatibility.\n _.template = function(text, settings, oldSettings) {\n if (!settings && oldSettings) settings = oldSettings;\n settings = _.defaults({}, settings, _.templateSettings);\n\n // Combine delimiters into one regular expression via alternation.\n var matcher = RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n // Compile the template source, escaping string literals appropriately.\n var index = 0;\n var source = \"__p+='\";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset).replace(escaper, escapeChar);\n index = offset + match.length;\n\n if (escape) {\n source += \"'+\\n((__t=(\" + escape + \"))==null?'':_.escape(__t))+\\n'\";\n } else if (interpolate) {\n source += \"'+\\n((__t=(\" + interpolate + \"))==null?'':__t)+\\n'\";\n } else if (evaluate) {\n source += \"';\\n\" + evaluate + \"\\n__p+='\";\n }\n\n // Adobe VMs need the match returned to produce the correct offest.\n return match;\n });\n source += \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __t,__p='',__j=Array.prototype.join,\" +\n \"print=function(){__p+=__j.call(arguments,'');};\\n\" +\n source + 'return __p;\\n';\n\n try {\n var render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled source as a convenience for precompilation.\n var argument = settings.variable || 'obj';\n template.source = 'function(' + argument + '){\\n' + source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function. Start chaining a wrapped Underscore object.\n _.chain = function(obj) {\n var instance = _(obj);\n instance._chain = true;\n return instance;\n };\n\n // OOP\n // ---------------\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n\n // Helper function to continue chaining intermediate results.\n var result = function(obj) {\n return this._chain ? _(obj).chain() : obj;\n };\n\n // Add your own custom functions to the Underscore object.\n _.mixin = function(obj) {\n _.each(_.functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return result.call(this, func.apply(_, args));\n };\n });\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n var obj = this._wrapped;\n method.apply(obj, arguments);\n if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];\n return result.call(this, obj);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n _.each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n return result.call(this, method.apply(this._wrapped, arguments));\n };\n });\n\n // Extracts the result from a wrapped and chained object.\n _.prototype.value = function() {\n return this._wrapped;\n };\n\n // AMD registration happens at the end for compatibility with AMD loaders\n // that may not enforce next-turn semantics on modules. Even though general\n // practice for AMD registration is to be anonymous, underscore registers\n // as a named module because, like jQuery, it is a base library that is\n // popular enough to be bundled in a third party lib, but not be part of\n // an AMD load request. Those cases could generate an error when an\n // anonymous define() is called outside of a loader request.\n if (typeof define === 'function' && define.amd) {\n define('underscore', [], function() {\n return _;\n });\n }\n}.call(this));\n\n},{}],\"zepto\":[function(require,module,exports){\n/* Zepto v1.1.4-76-g2bd5d7a - zepto event ajax callbacks deferred touch selector - zeptojs.com/license */\nvar Zepto=function(){function D(t){return null==t?String(t):j[S.call(t)]||\"object\"}function L(t){return\"function\"==D(t)}function k(t){return null!=t&&t==t.window}function Z(t){return null!=t&&t.nodeType==t.DOCUMENT_NODE}function $(t){return\"object\"==D(t)}function F(t){return $(t)&&!k(t)&&Object.getPrototypeOf(t)==Object.prototype}function R(t){return\"number\"==typeof t.length}function q(t){return s.call(t,function(t){return null!=t})}function W(t){return t.length>0?n.fn.concat.apply([],t):t}function z(t){return t.replace(/::/g,\"/\").replace(/([A-Z]+)([A-Z][a-z])/g,\"$1_$2\").replace(/([a-z\\d])([A-Z])/g,\"$1_$2\").replace(/_/g,\"-\").toLowerCase()}function H(t){return t in c?c[t]:c[t]=new RegExp(\"(^|\\\\s)\"+t+\"(\\\\s|$)\")}function _(t,e){return\"number\"!=typeof e||l[z(t)]?e:e+\"px\"}function I(t){var e,n;return f[t]||(e=u.createElement(t),u.body.appendChild(e),n=getComputedStyle(e,\"\").getPropertyValue(\"display\"),e.parentNode.removeChild(e),\"none\"==n&&(n=\"block\"),f[t]=n),f[t]}function U(t){return\"children\"in t?a.call(t.children):n.map(t.childNodes,function(t){return 1==t.nodeType?t:void 0})}function X(t,e){var n,i=t?t.length:0;for(n=0;i>n;n++)this[n]=t[n];this.length=i,this.selector=e||\"\"}function B(n,i,r){for(e in i)r&&(F(i[e])||A(i[e]))?(F(i[e])&&!F(n[e])&&(n[e]={}),A(i[e])&&!A(n[e])&&(n[e]=[]),B(n[e],i[e],r)):i[e]!==t&&(n[e]=i[e])}function V(t,e){return null==e?n(t):n(t).filter(e)}function Y(t,e,n,i){return L(e)?e.call(t,n,i):e}function J(t,e,n){null==n?t.removeAttribute(e):t.setAttribute(e,n)}function G(e,n){var i=e.className||\"\",r=i&&i.baseVal!==t;return n===t?r?i.baseVal:i:void(r?i.baseVal=n:e.className=n)}function K(t){try{return t?\"true\"==t||(\"false\"==t?!1:\"null\"==t?null:+t+\"\"==t?+t:/^[\\[\\{]/.test(t)?n.parseJSON(t):t):t}catch(e){return t}}function Q(t,e){e(t);for(var n=0,i=t.childNodes.length;i>n;n++)Q(t.childNodes[n],e)}var t,e,n,i,N,P,r=[],o=r.concat,s=r.filter,a=r.slice,u=window.document,f={},c={},l={\"column-count\":1,columns:1,\"font-weight\":1,\"line-height\":1,opacity:1,\"z-index\":1,zoom:1},h=/^\\s*<(\\w+|!)[^>]*>/,p=/^<(\\w+)\\s*\\/?>(?:<\\/\\1>|)$/,d=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:]+)[^>]*)\\/>/gi,m=/^(?:body|html)$/i,g=/([A-Z])/g,v=[\"val\",\"css\",\"html\",\"text\",\"data\",\"width\",\"height\",\"offset\"],y=[\"after\",\"prepend\",\"before\",\"append\"],w=u.createElement(\"table\"),x=u.createElement(\"tr\"),b={tr:u.createElement(\"tbody\"),tbody:w,thead:w,tfoot:w,td:x,th:x,\"*\":u.createElement(\"div\")},E=/complete|loaded|interactive/,T=/^[\\w-]*$/,j={},S=j.toString,C={},O=u.createElement(\"div\"),M={tabindex:\"tabIndex\",readonly:\"readOnly\",\"for\":\"htmlFor\",\"class\":\"className\",maxlength:\"maxLength\",cellspacing:\"cellSpacing\",cellpadding:\"cellPadding\",rowspan:\"rowSpan\",colspan:\"colSpan\",usemap:\"useMap\",frameborder:\"frameBorder\",contenteditable:\"contentEditable\"},A=Array.isArray||function(t){return t instanceof Array};return C.matches=function(t,e){if(!e||!t||1!==t.nodeType)return!1;var n=t.webkitMatchesSelector||t.mozMatchesSelector||t.oMatchesSelector||t.matchesSelector;if(n)return n.call(t,e);var i,r=t.parentNode,o=!r;return o&&(r=O).appendChild(t),i=~C.qsa(r,e).indexOf(t),o&&O.removeChild(t),i},N=function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():\"\"})},P=function(t){return s.call(t,function(e,n){return t.indexOf(e)==n})},C.fragment=function(e,i,r){var o,s,f;return p.test(e)&&(o=n(u.createElement(RegExp.$1))),o||(e.replace&&(e=e.replace(d,\"<$1>\")),i===t&&(i=h.test(e)&&RegExp.$1),i in b||(i=\"*\"),f=b[i],f.innerHTML=\"\"+e,o=n.each(a.call(f.childNodes),function(){f.removeChild(this)})),F(r)&&(s=n(o),n.each(r,function(t,e){v.indexOf(t)>-1?s[t](e):s.attr(t,e)})),o},C.Z=function(t,e){return new X(t,e)},C.isZ=function(t){return t instanceof C.Z},C.init=function(e,i){var r;if(!e)return C.Z();if(\"string\"==typeof e)if(e=e.trim(),\"<\"==e[0]&&h.test(e))r=C.fragment(e,RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}else{if(L(e))return n(u).ready(e);if(C.isZ(e))return e;if(A(e))r=q(e);else if($(e))r=[e],e=null;else if(h.test(e))r=C.fragment(e.trim(),RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}}return C.Z(r,e)},n=function(t,e){return C.init(t,e)},n.extend=function(t){var e,n=a.call(arguments,1);return\"boolean\"==typeof t&&(e=t,t=n.shift()),n.forEach(function(n){B(t,n,e)}),t},C.qsa=function(t,e){var n,i=\"#\"==e[0],r=!i&&\".\"==e[0],o=i||r?e.slice(1):e,s=T.test(o);return t.getElementById&&s&&i?(n=t.getElementById(o))?[n]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:a.call(s&&!i&&t.getElementsByClassName?r?t.getElementsByClassName(o):t.getElementsByTagName(e):t.querySelectorAll(e))},n.contains=u.documentElement.contains?function(t,e){return t!==e&&t.contains(e)}:function(t,e){for(;e&&(e=e.parentNode);)if(e===t)return!0;return!1},n.type=D,n.isFunction=L,n.isWindow=k,n.isArray=A,n.isPlainObject=F,n.isEmptyObject=function(t){var e;for(e in t)return!1;return!0},n.inArray=function(t,e,n){return r.indexOf.call(e,t,n)},n.camelCase=N,n.trim=function(t){return null==t?\"\":String.prototype.trim.call(t)},n.uuid=0,n.support={},n.expr={},n.noop=function(){},n.map=function(t,e){var n,r,o,i=[];if(R(t))for(r=0;r=0?e:e+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){null!=this.parentNode&&this.parentNode.removeChild(this)})},each:function(t){return r.every.call(this,function(e,n){return t.call(e,n,e)!==!1}),this},filter:function(t){return L(t)?this.not(this.not(t)):n(s.call(this,function(e){return C.matches(e,t)}))},add:function(t,e){return n(P(this.concat(n(t,e))))},is:function(t){return this.length>0&&C.matches(this[0],t)},not:function(e){var i=[];if(L(e)&&e.call!==t)this.each(function(t){e.call(this,t)||i.push(this)});else{var r=\"string\"==typeof e?this.filter(e):R(e)&&L(e.item)?a.call(e):n(e);this.forEach(function(t){r.indexOf(t)<0&&i.push(t)})}return n(i)},has:function(t){return this.filter(function(){return $(t)?n.contains(this,t):n(this).find(t).size()})},eq:function(t){return-1===t?this.slice(t):this.slice(t,+t+1)},first:function(){var t=this[0];return t&&!$(t)?t:n(t)},last:function(){var t=this[this.length-1];return t&&!$(t)?t:n(t)},find:function(t){var e,i=this;return e=t?\"object\"==typeof t?n(t).filter(function(){var t=this;return r.some.call(i,function(e){return n.contains(e,t)})}):1==this.length?n(C.qsa(this[0],t)):this.map(function(){return C.qsa(this,t)}):n()},closest:function(t,e){var i=this[0],r=!1;for(\"object\"==typeof t&&(r=n(t));i&&!(r?r.indexOf(i)>=0:C.matches(i,t));)i=i!==e&&!Z(i)&&i.parentNode;return n(i)},parents:function(t){for(var e=[],i=this;i.length>0;)i=n.map(i,function(t){return(t=t.parentNode)&&!Z(t)&&e.indexOf(t)<0?(e.push(t),t):void 0});return V(e,t)},parent:function(t){return V(P(this.pluck(\"parentNode\")),t)},children:function(t){return V(this.map(function(){return U(this)}),t)},contents:function(){return this.map(function(){return this.contentDocument||a.call(this.childNodes)})},siblings:function(t){return V(this.map(function(t,e){return s.call(U(e.parentNode),function(t){return t!==e})}),t)},empty:function(){return this.each(function(){this.innerHTML=\"\"})},pluck:function(t){return n.map(this,function(e){return e[t]})},show:function(){return this.each(function(){\"none\"==this.style.display&&(this.style.display=\"\"),\"none\"==getComputedStyle(this,\"\").getPropertyValue(\"display\")&&(this.style.display=I(this.nodeName))})},replaceWith:function(t){return this.before(t).remove()},wrap:function(t){var e=L(t);if(this[0]&&!e)var i=n(t).get(0),r=i.parentNode||this.length>1;return this.each(function(o){n(this).wrapAll(e?t.call(this,o):r?i.cloneNode(!0):i)})},wrapAll:function(t){if(this[0]){n(this[0]).before(t=n(t));for(var e;(e=t.children()).length;)t=e.first();n(t).append(this)}return this},wrapInner:function(t){var e=L(t);return this.each(function(i){var r=n(this),o=r.contents(),s=e?t.call(this,i):t;o.length?o.wrapAll(s):r.append(s)})},unwrap:function(){return this.parent().each(function(){n(this).replaceWith(n(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css(\"display\",\"none\")},toggle:function(e){return this.each(function(){var i=n(this);(e===t?\"none\"==i.css(\"display\"):e)?i.show():i.hide()})},prev:function(t){return n(this.pluck(\"previousElementSibling\")).filter(t||\"*\")},next:function(t){return n(this.pluck(\"nextElementSibling\")).filter(t||\"*\")},html:function(t){return 0 in arguments?this.each(function(e){var i=this.innerHTML;n(this).empty().append(Y(this,t,e,i))}):0 in this?this[0].innerHTML:null},text:function(t){return 0 in arguments?this.each(function(e){var n=Y(this,t,e,this.textContent);this.textContent=null==n?\"\":\"\"+n}):0 in this?this[0].textContent:null},attr:function(n,i){var r;return\"string\"!=typeof n||1 in arguments?this.each(function(t){if(1===this.nodeType)if($(n))for(e in n)J(this,e,n[e]);else J(this,n,Y(this,i,t,this.getAttribute(n)))}):this.length&&1===this[0].nodeType?!(r=this[0].getAttribute(n))&&n in this[0]?this[0][n]:r:t},removeAttr:function(t){return this.each(function(){1===this.nodeType&&t.split(\" \").forEach(function(t){J(this,t)},this)})},prop:function(t,e){return t=M[t]||t,1 in arguments?this.each(function(n){this[t]=Y(this,e,n,this[t])}):this[0]&&this[0][t]},data:function(e,n){var i=\"data-\"+e.replace(g,\"-$1\").toLowerCase(),r=1 in arguments?this.attr(i,n):this.attr(i);return null!==r?K(r):t},val:function(t){return 0 in arguments?this.each(function(e){this.value=Y(this,t,e,this.value)}):this[0]&&(this[0].multiple?n(this[0]).find(\"option\").filter(function(){return this.selected}).pluck(\"value\"):this[0].value)},offset:function(t){if(t)return this.each(function(e){var i=n(this),r=Y(this,t,e,i.offset()),o=i.offsetParent().offset(),s={top:r.top-o.top,left:r.left-o.left};\"static\"==i.css(\"position\")&&(s.position=\"relative\"),i.css(s)});if(!this.length)return null;var e=this[0].getBoundingClientRect();return{left:e.left+window.pageXOffset,top:e.top+window.pageYOffset,width:Math.round(e.width),height:Math.round(e.height)}},css:function(t,i){if(arguments.length<2){var r,o=this[0];if(!o)return;if(r=getComputedStyle(o,\"\"),\"string\"==typeof t)return o.style[N(t)]||r.getPropertyValue(t);if(A(t)){var s={};return n.each(t,function(t,e){s[e]=o.style[N(e)]||r.getPropertyValue(e)}),s}}var a=\"\";if(\"string\"==D(t))i||0===i?a=z(t)+\":\"+_(t,i):this.each(function(){this.style.removeProperty(z(t))});else for(e in t)t[e]||0===t[e]?a+=z(e)+\":\"+_(e,t[e])+\";\":this.each(function(){this.style.removeProperty(z(e))});return this.each(function(){this.style.cssText+=\";\"+a})},index:function(t){return t?this.indexOf(n(t)[0]):this.parent().children().indexOf(this[0])},hasClass:function(t){return t?r.some.call(this,function(t){return this.test(G(t))},H(t)):!1},addClass:function(t){return t?this.each(function(e){if(\"className\"in this){i=[];var r=G(this),o=Y(this,t,e,r);o.split(/\\s+/g).forEach(function(t){n(this).hasClass(t)||i.push(t)},this),i.length&&G(this,r+(r?\" \":\"\")+i.join(\" \"))}}):this},removeClass:function(e){return this.each(function(n){if(\"className\"in this){if(e===t)return G(this,\"\");i=G(this),Y(this,e,n,i).split(/\\s+/g).forEach(function(t){i=i.replace(H(t),\" \")}),G(this,i.trim())}})},toggleClass:function(e,i){return e?this.each(function(r){var o=n(this),s=Y(this,e,r,G(this));s.split(/\\s+/g).forEach(function(e){(i===t?!o.hasClass(e):i)?o.addClass(e):o.removeClass(e)})}):this},scrollTop:function(e){if(this.length){var n=\"scrollTop\"in this[0];return e===t?n?this[0].scrollTop:this[0].pageYOffset:this.each(n?function(){this.scrollTop=e}:function(){this.scrollTo(this.scrollX,e)})}},scrollLeft:function(e){if(this.length){var n=\"scrollLeft\"in this[0];return e===t?n?this[0].scrollLeft:this[0].pageXOffset:this.each(n?function(){this.scrollLeft=e}:function(){this.scrollTo(e,this.scrollY)})}},position:function(){if(this.length){var t=this[0],e=this.offsetParent(),i=this.offset(),r=m.test(e[0].nodeName)?{top:0,left:0}:e.offset();return i.top-=parseFloat(n(t).css(\"margin-top\"))||0,i.left-=parseFloat(n(t).css(\"margin-left\"))||0,r.top+=parseFloat(n(e[0]).css(\"border-top-width\"))||0,r.left+=parseFloat(n(e[0]).css(\"border-left-width\"))||0,{top:i.top-r.top,left:i.left-r.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||u.body;t&&!m.test(t.nodeName)&&\"static\"==n(t).css(\"position\");)t=t.offsetParent;return t})}},n.fn.detach=n.fn.remove,[\"width\",\"height\"].forEach(function(e){var i=e.replace(/./,function(t){return t[0].toUpperCase()});n.fn[e]=function(r){var o,s=this[0];return r===t?k(s)?s[\"inner\"+i]:Z(s)?s.documentElement[\"scroll\"+i]:(o=this.offset())&&o[e]:this.each(function(t){s=n(this),s.css(e,Y(this,r,t,s[e]()))})}}),y.forEach(function(t,e){var i=e%2;n.fn[t]=function(){var t,o,r=n.map(arguments,function(e){return t=D(e),\"object\"==t||\"array\"==t||null==e?e:C.fragment(e)}),s=this.length>1;return r.length<1?this:this.each(function(t,a){o=i?a:a.parentNode,a=0==e?a.nextSibling:1==e?a.firstChild:2==e?a:null;var f=n.contains(u.documentElement,o);r.forEach(function(t){if(s)t=t.cloneNode(!0);else if(!o)return n(t).remove();o.insertBefore(t,a),f&&Q(t,function(t){null==t.nodeName||\"SCRIPT\"!==t.nodeName.toUpperCase()||t.type&&\"text/javascript\"!==t.type||t.src||window.eval.call(window,t.innerHTML)})})})},n.fn[i?t+\"To\":\"insert\"+(e?\"Before\":\"After\")]=function(e){return n(e)[t](this),this}}),C.Z.prototype=X.prototype=n.fn,C.uniq=P,C.deserializeValue=K,n.zepto=C,n}();window.Zepto=Zepto,void 0===window.$&&(window.$=Zepto),function(t){function l(t){return t._zid||(t._zid=e++)}function h(t,e,n,i){if(e=p(e),e.ns)var r=d(e.ns);return(s[l(t)]||[]).filter(function(t){return!(!t||e.e&&t.e!=e.e||e.ns&&!r.test(t.ns)||n&&l(t.fn)!==l(n)||i&&t.sel!=i)})}function p(t){var e=(\"\"+t).split(\".\");return{e:e[0],ns:e.slice(1).sort().join(\" \")}}function d(t){return new RegExp(\"(?:^| )\"+t.replace(\" \",\" .* ?\")+\"(?: |$)\")}function m(t,e){return t.del&&!u&&t.e in f||!!e}function g(t){return c[t]||u&&f[t]||t}function v(e,i,r,o,a,u,f){var h=l(e),d=s[h]||(s[h]=[]);i.split(/\\s/).forEach(function(i){if(\"ready\"==i)return t(document).ready(r);var s=p(i);s.fn=r,s.sel=a,s.e in c&&(r=function(e){var n=e.relatedTarget;return!n||n!==this&&!t.contains(this,n)?s.fn.apply(this,arguments):void 0}),s.del=u;var l=u||r;s.proxy=function(t){if(t=T(t),!t.isImmediatePropagationStopped()){t.data=o;var i=l.apply(e,t._args==n?[t]:[t].concat(t._args));return i===!1&&(t.preventDefault(),t.stopPropagation()),i}},s.i=d.length,d.push(s),\"addEventListener\"in e&&e.addEventListener(g(s.e),s.proxy,m(s,f))})}function y(t,e,n,i,r){var o=l(t);(e||\"\").split(/\\s/).forEach(function(e){h(t,e,n,i).forEach(function(e){delete s[o][e.i],\"removeEventListener\"in t&&t.removeEventListener(g(e.e),e.proxy,m(e,r))})})}function T(e,i){return(i||!e.isDefaultPrevented)&&(i||(i=e),t.each(E,function(t,n){var r=i[t];e[t]=function(){return this[n]=w,r&&r.apply(i,arguments)},e[n]=x}),(i.defaultPrevented!==n?i.defaultPrevented:\"returnValue\"in i?i.returnValue===!1:i.getPreventDefault&&i.getPreventDefault())&&(e.isDefaultPrevented=w)),e}function j(t){var e,i={originalEvent:t};for(e in t)b.test(e)||t[e]===n||(i[e]=t[e]);return T(i,t)}var n,e=1,i=Array.prototype.slice,r=t.isFunction,o=function(t){return\"string\"==typeof t},s={},a={},u=\"onfocusin\"in window,f={focus:\"focusin\",blur:\"focusout\"},c={mouseenter:\"mouseover\",mouseleave:\"mouseout\"};a.click=a.mousedown=a.mouseup=a.mousemove=\"MouseEvents\",t.event={add:v,remove:y},t.proxy=function(e,n){var s=2 in arguments&&i.call(arguments,2);if(r(e)){var a=function(){return e.apply(n,s?s.concat(i.call(arguments)):arguments)};return a._zid=l(e),a}if(o(n))return s?(s.unshift(e[n],e),t.proxy.apply(null,s)):t.proxy(e[n],e);throw new TypeError(\"expected function\")},t.fn.bind=function(t,e,n){return this.on(t,e,n)},t.fn.unbind=function(t,e){return this.off(t,e)},t.fn.one=function(t,e,n,i){return this.on(t,e,n,i,1)};var w=function(){return!0},x=function(){return!1},b=/^([A-Z]|returnValue$|layer[XY]$)/,E={preventDefault:\"isDefaultPrevented\",stopImmediatePropagation:\"isImmediatePropagationStopped\",stopPropagation:\"isPropagationStopped\"};t.fn.delegate=function(t,e,n){return this.on(e,t,n)},t.fn.undelegate=function(t,e,n){return this.off(e,t,n)},t.fn.live=function(e,n){return t(document.body).delegate(this.selector,e,n),this},t.fn.die=function(e,n){return t(document.body).undelegate(this.selector,e,n),this},t.fn.on=function(e,s,a,u,f){var c,l,h=this;return e&&!o(e)?(t.each(e,function(t,e){h.on(t,s,a,e,f)}),h):(o(s)||r(u)||u===!1||(u=a,a=s,s=n),(u===n||a===!1)&&(u=a,a=n),u===!1&&(u=x),h.each(function(n,r){f&&(c=function(t){return y(r,t.type,u),u.apply(this,arguments)}),s&&(l=function(e){var n,o=t(e.target).closest(s,r).get(0);return o&&o!==r?(n=t.extend(j(e),{currentTarget:o,liveFired:r}),(c||u).apply(o,[n].concat(i.call(arguments,1)))):void 0}),v(r,e,u,a,s,l||c)}))},t.fn.off=function(e,i,s){var a=this;return e&&!o(e)?(t.each(e,function(t,e){a.off(t,i,e)}),a):(o(i)||r(s)||s===!1||(s=i,i=n),s===!1&&(s=x),a.each(function(){y(this,e,s,i)}))},t.fn.trigger=function(e,n){return e=o(e)||t.isPlainObject(e)?t.Event(e):T(e),e._args=n,this.each(function(){e.type in f&&\"function\"==typeof this[e.type]?this[e.type]():\"dispatchEvent\"in this?this.dispatchEvent(e):t(this).triggerHandler(e,n)})},t.fn.triggerHandler=function(e,n){var i,r;return this.each(function(s,a){i=j(o(e)?t.Event(e):e),i._args=n,i.target=a,t.each(h(a,e.type||e),function(t,e){return r=e.proxy(i),i.isImmediatePropagationStopped()?!1:void 0})}),r},\"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error\".split(\" \").forEach(function(e){t.fn[e]=function(t){return 0 in arguments?this.bind(e,t):this.trigger(e)}}),t.Event=function(t,e){o(t)||(e=t,t=e.type);var n=document.createEvent(a[t]||\"Events\"),i=!0;if(e)for(var r in e)\"bubbles\"==r?i=!!e[r]:n[r]=e[r];return n.initEvent(t,i,!0),T(n)}}(Zepto),function(t){function h(e,n,i){var r=t.Event(n);return t(e).trigger(r,i),!r.isDefaultPrevented()}function p(t,e,i,r){return t.global?h(e||n,i,r):void 0}function d(e){e.global&&0===t.active++&&p(e,null,\"ajaxStart\")}function m(e){e.global&&!--t.active&&p(e,null,\"ajaxStop\")}function g(t,e){var n=e.context;return e.beforeSend.call(n,t,e)===!1||p(e,n,\"ajaxBeforeSend\",[t,e])===!1?!1:void p(e,n,\"ajaxSend\",[t,e])}function v(t,e,n,i){var r=n.context,o=\"success\";n.success.call(r,t,o,e),i&&i.resolveWith(r,[t,o,e]),p(n,r,\"ajaxSuccess\",[e,n,t]),w(o,e,n)}function y(t,e,n,i,r){var o=i.context;i.error.call(o,n,e,t),r&&r.rejectWith(o,[n,e,t]),p(i,o,\"ajaxError\",[n,i,t||e]),w(e,n,i)}function w(t,e,n){var i=n.context;n.complete.call(i,e,t),p(n,i,\"ajaxComplete\",[e,n]),m(n)}function x(){}function b(t){return t&&(t=t.split(\";\",2)[0]),t&&(t==f?\"html\":t==u?\"json\":s.test(t)?\"script\":a.test(t)&&\"xml\")||\"text\"}function E(t,e){return\"\"==e?t:(t+\"&\"+e).replace(/[&?]{1,2}/,\"?\")}function T(e){e.processData&&e.data&&\"string\"!=t.type(e.data)&&(e.data=t.param(e.data,e.traditional)),!e.data||e.type&&\"GET\"!=e.type.toUpperCase()||(e.url=E(e.url,e.data),e.data=void 0)}function j(e,n,i,r){return t.isFunction(n)&&(r=i,i=n,n=void 0),t.isFunction(i)||(r=i,i=void 0),{url:e,data:n,success:i,dataType:r}}function C(e,n,i,r){var o,s=t.isArray(n),a=t.isPlainObject(n);t.each(n,function(n,u){o=t.type(u),r&&(n=i?r:r+\"[\"+(a||\"object\"==o||\"array\"==o?n:\"\")+\"]\"),!r&&s?e.add(u.name,u.value):\"array\"==o||!i&&\"object\"==o?C(e,u,i,n):e.add(n,u)})}var i,r,e=0,n=window.document,o=/)<[^<]*)*<\\/script>/gi,s=/^(?:text|application)\\/javascript/i,a=/^(?:text|application)\\/xml/i,u=\"application/json\",f=\"text/html\",c=/^\\s*$/,l=n.createElement(\"a\");l.href=window.location.href,t.active=0,t.ajaxJSONP=function(i,r){if(!(\"type\"in i))return t.ajax(i);var f,h,o=i.jsonpCallback,s=(t.isFunction(o)?o():o)||\"jsonp\"+ ++e,a=n.createElement(\"script\"),u=window[s],c=function(e){t(a).triggerHandler(\"error\",e||\"abort\")},l={abort:c};return r&&r.promise(l),t(a).on(\"load error\",function(e,n){clearTimeout(h),t(a).off().remove(),\"error\"!=e.type&&f?v(f[0],l,i,r):y(null,n||\"error\",l,i,r),window[s]=u,f&&t.isFunction(u)&&u(f[0]),u=f=void 0}),g(l,i)===!1?(c(\"abort\"),l):(window[s]=function(){f=arguments},a.src=i.url.replace(/\\?(.+)=\\?/,\"?$1=\"+s),n.head.appendChild(a),i.timeout>0&&(h=setTimeout(function(){c(\"timeout\")},i.timeout)),l)},t.ajaxSettings={type:\"GET\",beforeSend:x,success:x,error:x,complete:x,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:\"text/javascript, application/javascript, application/x-javascript\",json:u,xml:\"application/xml, text/xml\",html:f,text:\"text/plain\"},crossDomain:!1,timeout:0,processData:!0,cache:!0},t.ajax=function(e){var a,u,o=t.extend({},e||{}),s=t.Deferred&&t.Deferred();for(i in t.ajaxSettings)void 0===o[i]&&(o[i]=t.ajaxSettings[i]);d(o),o.crossDomain||(a=n.createElement(\"a\"),a.href=o.url,a.href=a.href,o.crossDomain=l.protocol+\"//\"+l.host!=a.protocol+\"//\"+a.host),o.url||(o.url=window.location.toString()),(u=o.url.indexOf(\"#\"))>-1&&(o.url=o.url.slice(0,u)),T(o);var f=o.dataType,h=/\\?.+=\\?/.test(o.url);if(h&&(f=\"jsonp\"),o.cache!==!1&&(e&&e.cache===!0||\"script\"!=f&&\"jsonp\"!=f)||(o.url=E(o.url,\"_=\"+Date.now())),\"jsonp\"==f)return h||(o.url=E(o.url,o.jsonp?o.jsonp+\"=?\":o.jsonp===!1?\"\":\"callback=?\")),t.ajaxJSONP(o,s);var N,p=o.accepts[f],m={},w=function(t,e){m[t.toLowerCase()]=[t,e]},j=/^([\\w-]+:)\\/\\//.test(o.url)?RegExp.$1:window.location.protocol,S=o.xhr(),C=S.setRequestHeader;if(s&&s.promise(S),o.crossDomain||w(\"X-Requested-With\",\"XMLHttpRequest\"),w(\"Accept\",p||\"*/*\"),(p=o.mimeType||p)&&(p.indexOf(\",\")>-1&&(p=p.split(\",\",2)[0]),S.overrideMimeType&&S.overrideMimeType(p)),(o.contentType||o.contentType!==!1&&o.data&&\"GET\"!=o.type.toUpperCase())&&w(\"Content-Type\",o.contentType||\"application/x-www-form-urlencoded\"),o.headers)for(r in o.headers)w(r,o.headers[r]);if(S.setRequestHeader=w,S.onreadystatechange=function(){if(4==S.readyState){S.onreadystatechange=x,clearTimeout(N);var e,n=!1;if(S.status>=200&&S.status<300||304==S.status||0==S.status&&\"file:\"==j){f=f||b(o.mimeType||S.getResponseHeader(\"content-type\")),e=S.responseText;try{\"script\"==f?(1,eval)(e):\"xml\"==f?e=S.responseXML:\"json\"==f&&(e=c.test(e)?null:t.parseJSON(e))}catch(i){n=i}n?y(n,\"parsererror\",S,o,s):v(e,S,o,s)}else y(S.statusText||null,S.status?\"error\":\"abort\",S,o,s)}},g(S,o)===!1)return S.abort(),y(null,\"abort\",S,o,s),S;if(o.xhrFields)for(r in o.xhrFields)S[r]=o.xhrFields[r];var P=\"async\"in o?o.async:!0;S.open(o.type,o.url,P,o.username,o.password);for(r in m)C.apply(S,m[r]);return o.timeout>0&&(N=setTimeout(function(){S.onreadystatechange=x,S.abort(),y(null,\"timeout\",S,o,s)},o.timeout)),S.send(o.data?o.data:null),S},t.get=function(){return t.ajax(j.apply(null,arguments))},t.post=function(){var e=j.apply(null,arguments);return e.type=\"POST\",t.ajax(e)},t.getJSON=function(){var e=j.apply(null,arguments);return e.dataType=\"json\",t.ajax(e)},t.fn.load=function(e,n,i){if(!this.length)return this;var a,r=this,s=e.split(/\\s/),u=j(e,n,i),f=u.success;return s.length>1&&(u.url=s[0],a=s[1]),u.success=function(e){r.html(a?t(\"
\").html(e.replace(o,\"\")).find(a):e),f&&f.apply(r,arguments)},t.ajax(u),this};var S=encodeURIComponent;t.param=function(e,n){var i=[];return i.add=function(e,n){t.isFunction(n)&&(n=n()),null==n&&(n=\"\"),this.push(S(e)+\"=\"+S(n))},C(i,e,n),i.join(\"&\").replace(/%20/g,\"+\")}}(Zepto),function(t){t.Callbacks=function(e){e=t.extend({},e);var n,i,r,o,s,a,u=[],f=!e.once&&[],c=function(t){for(n=e.memory&&t,i=!0,a=o||0,o=0,s=u.length,r=!0;u&&s>a;++a)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}r=!1,u&&(f?f.length&&c(f.shift()):n?u.length=0:l.disable())},l={add:function(){if(u){var i=u.length,a=function(n){t.each(n,function(t,n){\"function\"==typeof n?e.unique&&l.has(n)||u.push(n):n&&n.length&&\"string\"!=typeof n&&a(n)})};a(arguments),r?s=u.length:n&&(o=i,c(n))}return this},remove:function(){return u&&t.each(arguments,function(e,n){for(var i;(i=t.inArray(n,u,i))>-1;)u.splice(i,1),r&&(s>=i&&--s,a>=i&&--a)}),this},has:function(e){return!(!u||!(e?t.inArray(e,u)>-1:u.length))},empty:function(){return s=u.length=0,this},disable:function(){return u=f=n=void 0,this},disabled:function(){return!u},lock:function(){return f=void 0,n||l.disable(),this},locked:function(){return!f},fireWith:function(t,e){return!u||i&&!f||(e=e||[],e=[t,e.slice?e.slice():e],r?f.push(e):c(e)),this},fire:function(){return l.fireWith(this,arguments)},fired:function(){return!!i}};return l}}(Zepto),function(t){function n(e){var i=[[\"resolve\",\"done\",t.Callbacks({once:1,memory:1}),\"resolved\"],[\"reject\",\"fail\",t.Callbacks({once:1,memory:1}),\"rejected\"],[\"notify\",\"progress\",t.Callbacks({memory:1})]],r=\"pending\",o={state:function(){return r},always:function(){return s.done(arguments).fail(arguments),this},then:function(){var e=arguments;return n(function(n){t.each(i,function(i,r){var a=t.isFunction(e[i])&&e[i];s[r[1]](function(){var e=a&&a.apply(this,arguments);if(e&&t.isFunction(e.promise))e.promise().done(n.resolve).fail(n.reject).progress(n.notify);else{var i=this===o?n.promise():this,s=a?[e]:arguments;n[r[0]+\"With\"](i,s)}})}),e=null}).promise()},promise:function(e){return null!=e?t.extend(e,o):o}},s={};return t.each(i,function(t,e){var n=e[2],a=e[3];o[e[1]]=n.add,a&&n.add(function(){r=a},i[1^t][2].disable,i[2][2].lock),s[e[0]]=function(){return s[e[0]+\"With\"](this===s?o:this,arguments),this},s[e[0]+\"With\"]=n.fireWith}),o.promise(s),e&&e.call(s,s),s}var e=Array.prototype.slice;t.when=function(i){var f,c,l,r=e.call(arguments),o=r.length,s=0,a=1!==o||i&&t.isFunction(i.promise)?o:0,u=1===a?i:n(),h=function(t,n,i){return function(r){n[t]=this,i[t]=arguments.length>1?e.call(arguments):r,i===f?u.notifyWith(n,i):--a||u.resolveWith(n,i)}};if(o>1)for(f=new Array(o),c=new Array(o),l=new Array(o);o>s;++s)r[s]&&t.isFunction(r[s].promise)?r[s].promise().done(h(s,l,r)).fail(u.reject).progress(h(s,c,f)):--a;return a||u.resolveWith(l,r),u.promise()},t.Deferred=n}(Zepto),function(t){function u(t,e,n,i){return Math.abs(t-e)>=Math.abs(n-i)?t-e>0?\"Left\":\"Right\":n-i>0?\"Up\":\"Down\"}function f(){o=null,e.last&&(e.el.trigger(\"longTap\"),e={})}function c(){o&&clearTimeout(o),o=null}function l(){n&&clearTimeout(n),i&&clearTimeout(i),r&&clearTimeout(r),o&&clearTimeout(o),n=i=r=o=null,e={}}function h(t){return(\"touch\"==t.pointerType||t.pointerType==t.MSPOINTER_TYPE_TOUCH)&&t.isPrimary}function p(t,e){return t.type==\"pointer\"+e||t.type.toLowerCase()==\"mspointer\"+e}var n,i,r,o,a,e={},s=750;t(document).ready(function(){var d,m,y,w,g=0,v=0;\"MSGesture\"in window&&(a=new MSGesture,a.target=document.body),t(document).bind(\"MSGestureEnd\",function(t){var n=t.velocityX>1?\"Right\":t.velocityX<-1?\"Left\":t.velocityY>1?\"Down\":t.velocityY<-1?\"Up\":null;n&&(e.el.trigger(\"swipe\"),e.el.trigger(\"swipe\"+n))}).on(\"touchstart MSPointerDown pointerdown\",function(i){(!(w=p(i,\"down\"))||h(i))&&(y=w?i:i.touches[0],i.touches&&1===i.touches.length&&e.x2&&(e.x2=void 0,e.y2=void 0),d=Date.now(),m=d-(e.last||d),e.el=t(\"tagName\"in y.target?y.target:y.target.parentNode),n&&clearTimeout(n),e.x1=y.pageX,e.y1=y.pageY,m>0&&250>=m&&(e.isDoubleTap=!0),e.last=d,o=setTimeout(f,s),a&&w&&a.addPointer(i.pointerId))}).on(\"touchmove MSPointerMove pointermove\",function(t){(!(w=p(t,\"move\"))||h(t))&&(y=w?t:t.touches[0],c(),e.x2=y.pageX,e.y2=y.pageY,g+=Math.abs(e.x1-e.x2),v+=Math.abs(e.y1-e.y2))}).on(\"touchend MSPointerUp pointerup\",function(o){(!(w=p(o,\"up\"))||h(o))&&(c(),e.x2&&Math.abs(e.x1-e.x2)>30||e.y2&&Math.abs(e.y1-e.y2)>30?r=setTimeout(function(){e.el.trigger(\"swipe\"),e.el.trigger(\"swipe\"+u(e.x1,e.x2,e.y1,e.y2)),e={}},0):\"last\"in e&&(30>g&&30>v?i=setTimeout(function(){var i=t.Event(\"tap\");i.cancelTouch=l,e.el.trigger(i),e.isDoubleTap?(e.el&&e.el.trigger(\"doubleTap\"),e={}):n=setTimeout(function(){n=null,e.el&&e.el.trigger(\"singleTap\"),e={}},250)},0):e={}),g=v=0)}).on(\"touchcancel MSPointerCancel pointercancel\",l),t(window).on(\"scroll\",l)}),[\"swipe\",\"swipeLeft\",\"swipeRight\",\"swipeUp\",\"swipeDown\",\"doubleTap\",\"tap\",\"singleTap\",\"longTap\"].forEach(function(e){t.fn[e]=function(t){return this.on(e,t)}})}(Zepto),function(t){function r(e){return e=t(e),!(!e.width()&&!e.height())&&\"none\"!==e.css(\"display\")}function f(t,e){t=t.replace(/=#\\]/g,'=\"#\"]');var n,i,r=s.exec(t);if(r&&r[2]in o&&(n=o[r[2]],i=r[3],t=r[1],i)){var a=Number(i);i=isNaN(a)?i.replace(/^[\"']|[\"']$/g,\"\"):a}return e(t,n,i)}var e=t.zepto,n=e.qsa,i=e.matches,o=t.expr[\":\"]={visible:function(){return r(this)?this:void 0},hidden:function(){return r(this)?void 0:this},selected:function(){return this.selected?this:void 0},checked:function(){return this.checked?this:void 0},parent:function(){return this.parentNode},first:function(t){return 0===t?this:void 0},last:function(t,e){return t===e.length-1?this:void 0},eq:function(t,e,n){return t===n?this:void 0},contains:function(e,n,i){return t(this).text().indexOf(i)>-1?this:void 0},has:function(t,n,i){return e.qsa(this,i).length?this:void 0}},s=new RegExp(\"(.*):(\\\\w+)(?:\\\\(([^)]+)\\\\))?$\\\\s*\"),a=/^\\s*>/,u=\"Zepto\"+ +new Date;e.qsa=function(i,r){return f(r,function(o,s,f){try{var c;!o&&s?o=\"*\":a.test(o)&&(c=t(i).addClass(u),o=\".\"+u+\" \"+o);var l=n(i,o)}catch(h){throw console.error(\"error performing selector: %o\",r),h}finally{c&&c.removeClass(u)}return s?e.uniq(t.map(l,function(t,e){return s.call(t,e,l,f)})):l})},e.matches=function(t,e){return f(e,function(e,n,r){return!(e&&!i(t,e)||n&&n.call(t,null,r)!==t)})}}(Zepto);\nmodule.exports = Zepto;\n\n},{}]},{},[3,1])\n\n\n//# sourceMappingURL=clappr.map"}}},{"rowIdx":46,"cells":{"target":{"kind":"string","value":"client/src/components/dashboard/Profile/Preferences/Career.js"},"feat_repo_name":{"kind":"string","value":"FCC-Alumni/alumni-network"},"text":{"kind":"string","value":"import { connectScreenSize } from 'react-screen-size';\nimport { Dropdown } from 'semantic-ui-react';\nimport FormField from './common/FormField';\nimport { Container as InnerContainer } from './common/RepoContainer';\nimport { isEqual } from 'lodash';\nimport { mapScreenSizeToProps } from '../../../Navbar';\nimport MessageBox from '../../common/MessageBox';\nimport RadioButton from './common/RadioButton';\nimport React from 'react';\nimport Ribbon from './common/RibbonHeader';\nimport styled from 'styled-components';\nimport surveyOptions from '../../../../assets/dropdowns/devSurvey';\nimport { TransitionContainer } from '../../../../styles/style-utils';\n\nconst Error = styled.div`\n margin-top: 10px !important;\n`;\n\nconst OuterTransitionContainer = styled(TransitionContainer)`\n ${ props => props.bigBottomMargin &&\n 'margin-bottom: 60px !important' }`;\n\nconst ClearButton = ({ onClick }) => (\n \n {'Clear Form'}\n
\n);\n\nclass Career extends React.Component {\n shouldComponentUpdate(nextProps) {\n return !isEqual(this.props, nextProps);\n }\n render() {\n const {\n bigBottomMargin,\n clearForm,\n company,\n errors,\n handleInputChange,\n handleRadioChange,\n handleTenureChange,\n hasBeenEmployed,\n jobSearch,\n saveSection,\n screen: { isMobile },\n showCareer,\n showPopUp,\n tenure,\n toggle,\n working,\n } = this.props;\n return (\n
\n toggle('showCareer')}\n saveSection={saveSection}\n showPopUp={showPopUp}\n showSave={showCareer} />\n \n \n { errors.career &&\n \n {errors.career}\n }\n \n
\n \n \n \n
\n \n
\n \n \n
\n \n \n
\n \n
\n \n \n \n
\n {hasBeenEmployed === 'yes' &&\n \n }\n
\n \n \n \n \n
\n
\n \n \n
\n \n
\n
\n \n
\n );\n }\n}\n\nexport default connectScreenSize(mapScreenSizeToProps)(Career);\n"}}},{"rowIdx":47,"cells":{"target":{"kind":"string","value":"ajax/libs/webshim/1.14.4-RC4/dev/shims/es6.js"},"feat_repo_name":{"kind":"string","value":"jasonpang/cdnjs"},"text":{"kind":"string","value":"// ES6-shim 0.8.0 (c) 2013 Paul Miller (paulmillr.com)\n// ES6-shim may be freely distributed under the MIT license.\n// For more details and documentation:\n// https://github.com/paulmillr/es6-shim/\nwebshim.register('es6', function($, webshim, window, document, undefined){\n\n\t'use strict';\n\n\tvar isCallableWithoutNew = function(func) {\n\t\ttry { func(); }\n\t\tcatch (e) { return false; }\n\t\treturn true;\n\t};\n\n\tvar supportsSubclassing = function(C, f) {\n\t\t/* jshint proto:true */\n\t\ttry {\n\t\t\tvar Sub = function() { C.apply(this, arguments); };\n\t\t\tif (!Sub.__proto__) { return false; /* skip test on IE < 11 */ }\n\t\t\tObject.setPrototypeOf(Sub, C);\n\t\t\tSub.prototype = Object.create(C.prototype, {\n\t\t\t\tconstructor: { value: C }\n\t\t\t});\n\t\t\treturn f(Sub);\n\t\t} catch (e) {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tvar arePropertyDescriptorsSupported = function() {\n\t\ttry {\n\t\t\tObject.defineProperty({}, 'x', {});\n\t\t\treturn true;\n\t\t} catch (e) { /* this is IE 8. */\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tvar startsWithRejectsRegex = function() {\n\t\tvar rejectsRegex = false;\n\t\tif (String.prototype.startsWith) {\n\t\t\ttry {\n\t\t\t\t'/a/'.startsWith(/a/);\n\t\t\t} catch (e) { /* this is spec compliant */\n\t\t\t\trejectsRegex = true;\n\t\t\t}\n\t\t}\n\t\treturn rejectsRegex;\n\t};\n\n\t/*jshint evil: true */\n\tvar getGlobal = new Function('return this;');\n\t/*jshint evil: false */\n\n\tvar main = function() {\n\t\tvar globals = getGlobal();\n\t\tvar global_isFinite = globals.isFinite;\n\t\tvar supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported();\n\t\tvar startsWithIsCompliant = startsWithRejectsRegex();\n\t\tvar _slice = Array.prototype.slice;\n\t\tvar _indexOf = String.prototype.indexOf;\n\t\tvar _toString = Object.prototype.toString;\n\t\tvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\t\tvar ArrayIterator; // make our implementation private\n\n\t\t// Define configurable, writable and non-enumerable props\n\t\t// if they don’t exist.\n\t\tvar defineProperties = function(object, map) {\n\t\t\tObject.keys(map).forEach(function(name) {\n\t\t\t\tvar method = map[name];\n\t\t\t\tif (name in object) return;\n\t\t\t\tif (supportsDescriptors) {\n\t\t\t\t\tObject.defineProperty(object, name, {\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tenumerable: false,\n\t\t\t\t\t\twritable: true,\n\t\t\t\t\t\tvalue: method\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tobject[name] = method;\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\n\t\t// Simple shim for Object.create on ES3 browsers\n\t\t// (unlike real shim, no attempt to support `prototype === null`)\n\t\tvar create = Object.create || function(prototype, properties) {\n\t\t\tfunction Type() {}\n\t\t\tType.prototype = prototype;\n\t\t\tvar object = new Type();\n\t\t\tif (typeof properties !== \"undefined\") {\n\t\t\t\tdefineProperties(object, properties);\n\t\t\t}\n\t\t\treturn object;\n\t\t};\n\n\t\t// This is a private name in the es6 spec, equal to '[Symbol.iterator]'\n\t\t// we're going to use an arbitrary _-prefixed name to make our shims\n\t\t// work properly with each other, even though we don't have full Iterator\n\t\t// support. That is, `Array.from(map.keys())` will work, but we don't\n\t\t// pretend to export a \"real\" Iterator interface.\n\t\tvar $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) ||\n\t\t\t'_es6shim_iterator_';\n\t\t// Firefox ships a partial implementation using the name @@iterator.\n\t\t// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14\n\t\t// So use that name if we detect it.\n\t\tif (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') {\n\t\t\t$iterator$ = '@@iterator';\n\t\t}\n\t\tvar addIterator = function(prototype, impl) {\n\t\t\tif (!impl) { impl = function iterator() { return this; }; }\n\t\t\tvar o = {};\n\t\t\to[$iterator$] = impl;\n\t\t\tdefineProperties(prototype, o);\n\t\t};\n\n\t\t// taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js\n\t\t// can be replaced with require('is-arguments') if we ever use a build process instead\n\t\tvar isArguments = function isArguments(value) {\n\t\t\tvar str = _toString.call(value);\n\t\t\tvar result = str === '[object Arguments]';\n\t\t\tif (!result) {\n\t\t\t\tresult = str !== '[object Array]' &&\n\t\t\t\t\tvalue !== null &&\n\t\t\t\t\ttypeof value === 'object' &&\n\t\t\t\t\ttypeof value.length === 'number' &&\n\t\t\t\t\tvalue.length >= 0 &&\n\t\t\t\t\t_toString.call(value.callee) === '[object Function]';\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\n\t\tvar emulateES6construct = function(o) {\n\t\t\tif (!ES.TypeIsObject(o)) throw new TypeError('bad object');\n\t\t\t// es5 approximation to es6 subclass semantics: in es6, 'new Foo'\n\t\t\t// would invoke Foo.@@create to allocation/initialize the new object.\n\t\t\t// In es5 we just get the plain object. So if we detect an\n\t\t\t// uninitialized object, invoke o.constructor.@@create\n\t\t\tif (!o._es6construct) {\n\t\t\t\tif (o.constructor && ES.IsCallable(o.constructor['@@create'])) {\n\t\t\t\t\to = o.constructor['@@create'](o);\n\t\t\t\t}\n\t\t\t\tdefineProperties(o, { _es6construct: true });\n\t\t\t}\n\t\t\treturn o;\n\t\t};\n\n\t\tvar ES = {\n\t\t\tCheckObjectCoercible: function(x, optMessage) {\n\t\t\t\t/* jshint eqnull:true */\n\t\t\t\tif (x == null)\n\t\t\t\t\tthrow new TypeError(optMessage || ('Cannot call method on ' + x));\n\t\t\t\treturn x;\n\t\t\t},\n\n\t\t\tTypeIsObject: function(x) {\n\t\t\t\t/* jshint eqnull:true */\n\t\t\t\t// this is expensive when it returns false; use this function\n\t\t\t\t// when you expect it to return true in the common case.\n\t\t\t\treturn x != null && Object(x) === x;\n\t\t\t},\n\n\t\t\tToObject: function(o, optMessage) {\n\t\t\t\treturn Object(ES.CheckObjectCoercible(o, optMessage));\n\t\t\t},\n\n\t\t\tIsCallable: function(x) {\n\t\t\t\treturn typeof x === 'function' &&\n\t\t\t\t\t// some versions of IE say that typeof /abc/ === 'function'\n\t\t\t\t\t_toString.call(x) === '[object Function]';\n\t\t\t},\n\n\t\t\tToInt32: function(x) {\n\t\t\t\treturn x >> 0;\n\t\t\t},\n\n\t\t\tToUint32: function(x) {\n\t\t\t\treturn x >>> 0;\n\t\t\t},\n\n\t\t\tToInteger: function(value) {\n\t\t\t\tvar number = +value;\n\t\t\t\tif (Number.isNaN(number)) return 0;\n\t\t\t\tif (number === 0 || !Number.isFinite(number)) return number;\n\t\t\t\treturn Math.sign(number) * Math.floor(Math.abs(number));\n\t\t\t},\n\n\t\t\tToLength: function(value) {\n\t\t\t\tvar len = ES.ToInteger(value);\n\t\t\t\tif (len <= 0) return 0; // includes converting -0 to +0\n\t\t\t\tif (len > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER;\n\t\t\t\treturn len;\n\t\t\t},\n\n\t\t\tSameValue: function(a, b) {\n\t\t\t\tif (a === b) {\n\t\t\t\t\t// 0 === -0, but they are not identical.\n\t\t\t\t\tif (a === 0) return 1 / a === 1 / b;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn Number.isNaN(a) && Number.isNaN(b);\n\t\t\t},\n\n\t\t\tSameValueZero: function(a, b) {\n\t\t\t\t// same as SameValue except for SameValueZero(+0, -0) == true\n\t\t\t\treturn (a === b) || (Number.isNaN(a) && Number.isNaN(b));\n\t\t\t},\n\n\t\t\tIsIterable: function(o) {\n\t\t\t\treturn ES.TypeIsObject(o) &&\n\t\t\t\t\t(o[$iterator$] !== undefined || isArguments(o));\n\t\t\t},\n\n\t\t\tGetIterator: function(o) {\n\t\t\t\tif (isArguments(o)) {\n\t\t\t\t\t// special case support for `arguments`\n\t\t\t\t\treturn new ArrayIterator(o, \"value\");\n\t\t\t\t}\n\t\t\t\tvar it = o[$iterator$]();\n\t\t\t\tif (!ES.TypeIsObject(it)) {\n\t\t\t\t\tthrow new TypeError('bad iterator');\n\t\t\t\t}\n\t\t\t\treturn it;\n\t\t\t},\n\n\t\t\tIteratorNext: function(it) {\n\t\t\t\tvar result = (arguments.length > 1) ? it.next(arguments[1]) : it.next();\n\t\t\t\tif (!ES.TypeIsObject(result)) {\n\t\t\t\t\tthrow new TypeError('bad iterator');\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t},\n\n\t\t\tConstruct: function(C, args) {\n\t\t\t\t// CreateFromConstructor\n\t\t\t\tvar obj;\n\t\t\t\tif (ES.IsCallable(C['@@create'])) {\n\t\t\t\t\tobj = C['@@create']();\n\t\t\t\t} else {\n\t\t\t\t\t// OrdinaryCreateFromConstructor\n\t\t\t\t\tobj = create(C.prototype || null);\n\t\t\t\t}\n\t\t\t\t// Mark that we've used the es6 construct path\n\t\t\t\t// (see emulateES6construct)\n\t\t\t\tdefineProperties(obj, { _es6construct: true });\n\t\t\t\t// Call the constructor.\n\t\t\t\tvar result = C.apply(obj, args);\n\t\t\t\treturn ES.TypeIsObject(result) ? result : obj;\n\t\t\t}\n\t\t};\n\n\t\tvar numberConversion = (function () {\n\t\t\t// from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266\n\t\t\t// with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200\n\n\t\t\tfunction roundToEven(n) {\n\t\t\t\tvar w = Math.floor(n), f = n - w;\n\t\t\t\tif (f < 0.5) {\n\t\t\t\t\treturn w;\n\t\t\t\t}\n\t\t\t\tif (f > 0.5) {\n\t\t\t\t\treturn w + 1;\n\t\t\t\t}\n\t\t\t\treturn w % 2 ? w + 1 : w;\n\t\t\t}\n\n\t\t\tfunction packIEEE754(v, ebits, fbits) {\n\t\t\t\tvar bias = (1 << (ebits - 1)) - 1,\n\t\t\t\t\ts, e, f, ln,\n\t\t\t\t\ti, bits, str, bytes;\n\n\t\t\t\t// Compute sign, exponent, fraction\n\t\t\t\tif (v !== v) {\n\t\t\t\t\t// NaN\n\t\t\t\t\t// http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping\n\t\t\t\t\te = (1 << ebits) - 1;\n\t\t\t\t\tf = Math.pow(2, fbits - 1);\n\t\t\t\t\ts = 0;\n\t\t\t\t} else if (v === Infinity || v === -Infinity) {\n\t\t\t\t\te = (1 << ebits) - 1;\n\t\t\t\t\tf = 0;\n\t\t\t\t\ts = (v < 0) ? 1 : 0;\n\t\t\t\t} else if (v === 0) {\n\t\t\t\t\te = 0;\n\t\t\t\t\tf = 0;\n\t\t\t\t\ts = (1 / v === -Infinity) ? 1 : 0;\n\t\t\t\t} else {\n\t\t\t\t\ts = v < 0;\n\t\t\t\t\tv = Math.abs(v);\n\n\t\t\t\t\tif (v >= Math.pow(2, 1 - bias)) {\n\t\t\t\t\t\te = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023);\n\t\t\t\t\t\tf = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits));\n\t\t\t\t\t\tif (f / Math.pow(2, fbits) >= 2) {\n\t\t\t\t\t\t\te = e + 1;\n\t\t\t\t\t\t\tf = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (e > bias) {\n\t\t\t\t\t\t\t// Overflow\n\t\t\t\t\t\t\te = (1 << ebits) - 1;\n\t\t\t\t\t\t\tf = 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Normal\n\t\t\t\t\t\t\te = e + bias;\n\t\t\t\t\t\t\tf = f - Math.pow(2, fbits);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Subnormal\n\t\t\t\t\t\te = 0;\n\t\t\t\t\t\tf = roundToEven(v / Math.pow(2, 1 - bias - fbits));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Pack sign, exponent, fraction\n\t\t\t\tbits = [];\n\t\t\t\tfor (i = fbits; i; i -= 1) {\n\t\t\t\t\tbits.push(f % 2 ? 1 : 0);\n\t\t\t\t\tf = Math.floor(f / 2);\n\t\t\t\t}\n\t\t\t\tfor (i = ebits; i; i -= 1) {\n\t\t\t\t\tbits.push(e % 2 ? 1 : 0);\n\t\t\t\t\te = Math.floor(e / 2);\n\t\t\t\t}\n\t\t\t\tbits.push(s ? 1 : 0);\n\t\t\t\tbits.reverse();\n\t\t\t\tstr = bits.join('');\n\n\t\t\t\t// Bits to bytes\n\t\t\t\tbytes = [];\n\t\t\t\twhile (str.length) {\n\t\t\t\t\tbytes.push(parseInt(str.substring(0, 8), 2));\n\t\t\t\t\tstr = str.substring(8);\n\t\t\t\t}\n\t\t\t\treturn bytes;\n\t\t\t}\n\n\t\t\tfunction unpackIEEE754(bytes, ebits, fbits) {\n\t\t\t\t// Bytes to bits\n\t\t\t\tvar bits = [], i, j, b, str,\n\t\t\t\t\tbias, s, e, f;\n\n\t\t\t\tfor (i = bytes.length; i; i -= 1) {\n\t\t\t\t\tb = bytes[i - 1];\n\t\t\t\t\tfor (j = 8; j; j -= 1) {\n\t\t\t\t\t\tbits.push(b % 2 ? 1 : 0);\n\t\t\t\t\t\tb = b >> 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbits.reverse();\n\t\t\t\tstr = bits.join('');\n\n\t\t\t\t// Unpack sign, exponent, fraction\n\t\t\t\tbias = (1 << (ebits - 1)) - 1;\n\t\t\t\ts = parseInt(str.substring(0, 1), 2) ? -1 : 1;\n\t\t\t\te = parseInt(str.substring(1, 1 + ebits), 2);\n\t\t\t\tf = parseInt(str.substring(1 + ebits), 2);\n\n\t\t\t\t// Produce number\n\t\t\t\tif (e === (1 << ebits) - 1) {\n\t\t\t\t\treturn f !== 0 ? NaN : s * Infinity;\n\t\t\t\t} else if (e > 0) {\n\t\t\t\t\t// Normalized\n\t\t\t\t\treturn s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));\n\t\t\t\t} else if (f !== 0) {\n\t\t\t\t\t// Denormalized\n\t\t\t\t\treturn s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits));\n\t\t\t\t} else {\n\t\t\t\t\treturn s < 0 ? -0 : 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction unpackFloat64(b) { return unpackIEEE754(b, 11, 52); }\n\t\t\tfunction packFloat64(v) { return packIEEE754(v, 11, 52); }\n\t\t\tfunction unpackFloat32(b) { return unpackIEEE754(b, 8, 23); }\n\t\t\tfunction packFloat32(v) { return packIEEE754(v, 8, 23); }\n\n\t\t\tvar conversions = {\n\t\t\t\ttoFloat32: function (num) { return unpackFloat32(packFloat32(num)); }\n\t\t\t};\n\t\t\tif (typeof Float32Array !== 'undefined') {\n\t\t\t\tvar float32array = new Float32Array(1);\n\t\t\t\tconversions.toFloat32 = function (num) {\n\t\t\t\t\tfloat32array[0] = num;\n\t\t\t\t\treturn float32array[0];\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn conversions;\n\t\t}());\n\n\t\tdefineProperties(String, {\n\t\t\tfromCodePoint: function() {\n\t\t\t\tvar points = _slice.call(arguments, 0, arguments.length);\n\t\t\t\tvar result = [];\n\t\t\t\tvar next;\n\t\t\t\tfor (var i = 0, length = points.length; i < length; i++) {\n\t\t\t\t\tnext = Number(points[i]);\n\t\t\t\t\tif (!ES.SameValue(next, ES.ToInteger(next)) ||\n\t\t\t\t\t\tnext < 0 || next > 0x10FFFF) {\n\t\t\t\t\t\tthrow new RangeError('Invalid code point ' + next);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (next < 0x10000) {\n\t\t\t\t\t\tresult.push(String.fromCharCode(next));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnext -= 0x10000;\n\t\t\t\t\t\tresult.push(String.fromCharCode((next >> 10) + 0xD800));\n\t\t\t\t\t\tresult.push(String.fromCharCode((next % 0x400) + 0xDC00));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result.join('');\n\t\t\t},\n\n\t\t\traw: function(callSite) { // raw.length===1\n\t\t\t\tvar substitutions = _slice.call(arguments, 1, arguments.length);\n\t\t\t\tvar cooked = ES.ToObject(callSite, 'bad callSite');\n\t\t\t\tvar rawValue = cooked.raw;\n\t\t\t\tvar raw = ES.ToObject(rawValue, 'bad raw value');\n\t\t\t\tvar len = Object.keys(raw).length;\n\t\t\t\tvar literalsegments = ES.ToLength(len);\n\t\t\t\tif (literalsegments === 0) {\n\t\t\t\t\treturn '';\n\t\t\t\t}\n\n\t\t\t\tvar stringElements = [];\n\t\t\t\tvar nextIndex = 0;\n\t\t\t\tvar nextKey, next, nextSeg, nextSub;\n\t\t\t\twhile (nextIndex < literalsegments) {\n\t\t\t\t\tnextKey = String(nextIndex);\n\t\t\t\t\tnext = raw[nextKey];\n\t\t\t\t\tnextSeg = String(next);\n\t\t\t\t\tstringElements.push(nextSeg);\n\t\t\t\t\tif (nextIndex + 1 >= literalsegments) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tnext = substitutions[nextKey];\n\t\t\t\t\tif (next === undefined) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tnextSub = String(next);\n\t\t\t\t\tstringElements.push(nextSub);\n\t\t\t\t\tnextIndex++;\n\t\t\t\t}\n\t\t\t\treturn stringElements.join('');\n\t\t\t}\n\t\t});\n\n\t\tvar StringShims = {\n\t\t\t// Fast repeat, uses the `Exponentiation by squaring` algorithm.\n\t\t\t// Perf: http://jsperf.com/string-repeat2/2\n\t\t\trepeat: (function() {\n\t\t\t\tvar repeat = function(s, times) {\n\t\t\t\t\tif (times < 1) return '';\n\t\t\t\t\tif (times % 2) return repeat(s, times - 1) + s;\n\t\t\t\t\tvar half = repeat(s, times / 2);\n\t\t\t\t\treturn half + half;\n\t\t\t\t};\n\n\t\t\t\treturn function(times) {\n\t\t\t\t\tvar thisStr = String(ES.CheckObjectCoercible(this));\n\t\t\t\t\ttimes = ES.ToInteger(times);\n\t\t\t\t\tif (times < 0 || times === Infinity) {\n\t\t\t\t\t\tthrow new RangeError('Invalid String#repeat value');\n\t\t\t\t\t}\n\t\t\t\t\treturn repeat(thisStr, times);\n\t\t\t\t};\n\t\t\t})(),\n\n\t\t\tstartsWith: function(searchStr) {\n\t\t\t\tvar thisStr = String(ES.CheckObjectCoercible(this));\n\t\t\t\tif (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method \"startsWith\" with a regex');\n\t\t\t\tsearchStr = String(searchStr);\n\t\t\t\tvar startArg = arguments.length > 1 ? arguments[1] : undefined;\n\t\t\t\tvar start = Math.max(ES.ToInteger(startArg), 0);\n\t\t\t\treturn thisStr.slice(start, start + searchStr.length) === searchStr;\n\t\t\t},\n\n\t\t\tendsWith: function(searchStr) {\n\t\t\t\tvar thisStr = String(ES.CheckObjectCoercible(this));\n\t\t\t\tif (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method \"endsWith\" with a regex');\n\t\t\t\tsearchStr = String(searchStr);\n\t\t\t\tvar thisLen = thisStr.length;\n\t\t\t\tvar posArg = arguments.length > 1 ? arguments[1] : undefined;\n\t\t\t\tvar pos = posArg === undefined ? thisLen : ES.ToInteger(posArg);\n\t\t\t\tvar end = Math.min(Math.max(pos, 0), thisLen);\n\t\t\t\treturn thisStr.slice(end - searchStr.length, end) === searchStr;\n\t\t\t},\n\n\t\t\tcontains: function(searchString) {\n\t\t\t\tvar position = arguments.length > 1 ? arguments[1] : undefined;\n\t\t\t\t// Somehow this trick makes method 100% compat with the spec.\n\t\t\t\treturn _indexOf.call(this, searchString, position) !== -1;\n\t\t\t},\n\n\t\t\tcodePointAt: function(pos) {\n\t\t\t\tvar thisStr = String(ES.CheckObjectCoercible(this));\n\t\t\t\tvar position = ES.ToInteger(pos);\n\t\t\t\tvar length = thisStr.length;\n\t\t\t\tif (position < 0 || position >= length) return undefined;\n\t\t\t\tvar first = thisStr.charCodeAt(position);\n\t\t\t\tvar isEnd = (position + 1 === length);\n\t\t\t\tif (first < 0xD800 || first > 0xDBFF || isEnd) return first;\n\t\t\t\tvar second = thisStr.charCodeAt(position + 1);\n\t\t\t\tif (second < 0xDC00 || second > 0xDFFF) return first;\n\t\t\t\treturn ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000;\n\t\t\t}\n\t\t};\n\t\tdefineProperties(String.prototype, StringShims);\n\n\t\tvar hasStringTrimBug = '\\u0085'.trim().length !== 1;\n\t\tif (hasStringTrimBug) {\n\t\t\tvar originalStringTrim = String.prototype.trim;\n\t\t\tdelete String.prototype.trim;\n\t\t\t// whitespace from: http://es5.github.io/#x15.5.4.20\n\t\t\t// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324\n\t\t\tvar ws = [\n\t\t\t\t'\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003',\n\t\t\t\t'\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028',\n\t\t\t\t'\\u2029\\uFEFF'\n\t\t\t].join('');\n\t\t\tvar trimBeginRegexp = new RegExp('^[' + ws + '][' + ws + ']*');\n\t\t\tvar trimEndRegexp = new RegExp('[' + ws + '][' + ws + ']*$');\n\t\t\tdefineProperties(String.prototype, {\n\t\t\t\ttrim: function() {\n\t\t\t\t\tif (this === undefined || this === null) {\n\t\t\t\t\t\tthrow new TypeError(\"can't convert \" + this + \" to object\");\n\t\t\t\t\t}\n\t\t\t\t\treturn String(this)\n\t\t\t\t\t\t.replace(trimBeginRegexp, \"\")\n\t\t\t\t\t\t.replace(trimEndRegexp, \"\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator\n\t\tvar StringIterator = function(s) {\n\t\t\tthis._s = String(ES.CheckObjectCoercible(s));\n\t\t\tthis._i = 0;\n\t\t};\n\t\tStringIterator.prototype.next = function() {\n\t\t\tvar s = this._s, i = this._i;\n\t\t\tif (s === undefined || i >= s.length) {\n\t\t\t\tthis._s = undefined;\n\t\t\t\treturn { value: undefined, done: true };\n\t\t\t}\n\t\t\tvar first = s.charCodeAt(i), second, len;\n\t\t\tif (first < 0xD800 || first > 0xDBFF || (i+1) == s.length) {\n\t\t\t\tlen = 1;\n\t\t\t} else {\n\t\t\t\tsecond = s.charCodeAt(i+1);\n\t\t\t\tlen = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2;\n\t\t\t}\n\t\t\tthis._i = i + len;\n\t\t\treturn { value: s.substr(i, len), done: false };\n\t\t};\n\t\taddIterator(StringIterator.prototype);\n\t\taddIterator(String.prototype, function() {\n\t\t\treturn new StringIterator(this);\n\t\t});\n\n\t\tif (!startsWithIsCompliant) {\n\t\t\t// Firefox has a noncompliant startsWith implementation\n\t\t\tString.prototype.startsWith = StringShims.startsWith;\n\t\t\tString.prototype.endsWith = StringShims.endsWith;\n\t\t}\n\n\t\tdefineProperties(Array, {\n\t\t\tfrom: function(iterable) {\n\t\t\t\tvar mapFn = arguments.length > 1 ? arguments[1] : undefined;\n\t\t\t\tvar thisArg = arguments.length > 2 ? arguments[2] : undefined;\n\n\t\t\t\tvar list = ES.ToObject(iterable, 'bad iterable');\n\t\t\t\tif (mapFn !== undefined && !ES.IsCallable(mapFn)) {\n\t\t\t\t\tthrow new TypeError('Array.from: when provided, the second argument must be a function');\n\t\t\t\t}\n\n\t\t\t\tvar usingIterator = ES.IsIterable(list);\n\t\t\t\t// does the spec really mean that Arrays should use ArrayIterator?\n\t\t\t\t// https://bugs.ecmascript.org/show_bug.cgi?id=2416\n\t\t\t\t//if (Array.isArray(list)) { usingIterator=false; }\n\t\t\t\tvar length = usingIterator ? 0 : ES.ToLength(list.length);\n\t\t\t\tvar result = ES.IsCallable(this) ? Object(usingIterator ? new this() : new this(length)) : new Array(length);\n\t\t\t\tvar it = usingIterator ? ES.GetIterator(list) : null;\n\t\t\t\tvar value;\n\n\t\t\t\tfor (var i = 0; usingIterator || (i < length); i++) {\n\t\t\t\t\tif (usingIterator) {\n\t\t\t\t\t\tvalue = ES.IteratorNext(it);\n\t\t\t\t\t\tif (value.done) {\n\t\t\t\t\t\t\tlength = i;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalue = value.value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalue = list[i];\n\t\t\t\t\t}\n\t\t\t\t\tif (mapFn) {\n\t\t\t\t\t\tresult[i] = thisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult[i] = value;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresult.length = length;\n\t\t\t\treturn result;\n\t\t\t},\n\n\t\t\tof: function() {\n\t\t\t\treturn Array.from(arguments);\n\t\t\t}\n\t\t});\n\n\t\t// Our ArrayIterator is private; see\n\t\t// https://github.com/paulmillr/es6-shim/issues/252\n\t\tArrayIterator = function(array, kind) {\n\t\t\tthis.i = 0;\n\t\t\tthis.array = array;\n\t\t\tthis.kind = kind;\n\t\t};\n\n\t\tdefineProperties(ArrayIterator.prototype, {\n\t\t\tnext: function() {\n\t\t\t\tvar i = this.i, array = this.array;\n\t\t\t\tif (i === undefined || this.kind === undefined) {\n\t\t\t\t\tthrow new TypeError('Not an ArrayIterator');\n\t\t\t\t}\n\t\t\t\tif (array!==undefined) {\n\t\t\t\t\tvar len = ES.ToLength(array.length);\n\t\t\t\t\tfor (; i < len; i++) {\n\t\t\t\t\t\tvar kind = this.kind;\n\t\t\t\t\t\tvar retval;\n\t\t\t\t\t\tif (kind === \"key\") {\n\t\t\t\t\t\t\tretval = i;\n\t\t\t\t\t\t} else if (kind === \"value\") {\n\t\t\t\t\t\t\tretval = array[i];\n\t\t\t\t\t\t} else if (kind === \"entry\") {\n\t\t\t\t\t\t\tretval = [i, array[i]];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.i = i + 1;\n\t\t\t\t\t\treturn { value: retval, done: false };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.array = undefined;\n\t\t\t\treturn { value: undefined, done: true };\n\t\t\t}\n\t\t});\n\t\taddIterator(ArrayIterator.prototype);\n\n\t\tdefineProperties(Array.prototype, {\n\t\t\tcopyWithin: function(target, start) {\n\t\t\t\tvar end = arguments[2]; // copyWithin.length must be 2\n\t\t\t\tvar o = ES.ToObject(this);\n\t\t\t\tvar len = ES.ToLength(o.length);\n\t\t\t\ttarget = ES.ToInteger(target);\n\t\t\t\tstart = ES.ToInteger(start);\n\t\t\t\tvar to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len);\n\t\t\t\tvar from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);\n\t\t\t\tend = (end===undefined) ? len : ES.ToInteger(end);\n\t\t\t\tvar fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);\n\t\t\t\tvar count = Math.min(fin - from, len - to);\n\t\t\t\tvar direction = 1;\n\t\t\t\tif (from < to && to < (from + count)) {\n\t\t\t\t\tdirection = -1;\n\t\t\t\t\tfrom += count - 1;\n\t\t\t\t\tto += count - 1;\n\t\t\t\t}\n\t\t\t\twhile (count > 0) {\n\t\t\t\t\tif (_hasOwnProperty.call(o, from)) {\n\t\t\t\t\t\to[to] = o[from];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelete o[from];\n\t\t\t\t\t}\n\t\t\t\t\tfrom += direction;\n\t\t\t\t\tto += direction;\n\t\t\t\t\tcount -= 1;\n\t\t\t\t}\n\t\t\t\treturn o;\n\t\t\t},\n\n\t\t\tfill: function(value) {\n\t\t\t\tvar start = arguments[1], end = arguments[2]; // fill.length===1\n\t\t\t\tvar O = ES.ToObject(this);\n\t\t\t\tvar len = ES.ToLength(O.length);\n\t\t\t\tstart = ES.ToInteger(start===undefined ? 0 : start);\n\t\t\t\tend = ES.ToInteger(end===undefined ? len : end);\n\n\t\t\t\tvar relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);\n\n\t\t\t\tfor (var i = relativeStart; i < len && i < end; ++i) {\n\t\t\t\t\tO[i] = value;\n\t\t\t\t}\n\t\t\t\treturn O;\n\t\t\t},\n\n\t\t\tfind: function(predicate) {\n\t\t\t\tvar list = ES.ToObject(this);\n\t\t\t\tvar length = ES.ToLength(list.length);\n\t\t\t\tif (!ES.IsCallable(predicate)) {\n\t\t\t\t\tthrow new TypeError('Array#find: predicate must be a function');\n\t\t\t\t}\n\t\t\t\tvar thisArg = arguments[1];\n\t\t\t\tfor (var i = 0, value; i < length; i++) {\n\t\t\t\t\tif (i in list) {\n\t\t\t\t\t\tvalue = list[i];\n\t\t\t\t\t\tif (predicate.call(thisArg, value, i, list)) return value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t},\n\n\t\t\tfindIndex: function(predicate) {\n\t\t\t\tvar list = ES.ToObject(this);\n\t\t\t\tvar length = ES.ToLength(list.length);\n\t\t\t\tif (!ES.IsCallable(predicate)) {\n\t\t\t\t\tthrow new TypeError('Array#findIndex: predicate must be a function');\n\t\t\t\t}\n\t\t\t\tvar thisArg = arguments[1];\n\t\t\t\tfor (var i = 0; i < length; i++) {\n\t\t\t\t\tif (i in list) {\n\t\t\t\t\t\tif (predicate.call(thisArg, list[i], i, list)) return i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn -1;\n\t\t\t},\n\n\t\t\tkeys: function() {\n\t\t\t\treturn new ArrayIterator(this, \"key\");\n\t\t\t},\n\n\t\t\tvalues: function() {\n\t\t\t\treturn new ArrayIterator(this, \"value\");\n\t\t\t},\n\n\t\t\tentries: function() {\n\t\t\t\treturn new ArrayIterator(this, \"entry\");\n\t\t\t}\n\t\t});\n\t\taddIterator(Array.prototype, function() { return this.values(); });\n\t\t// Chrome defines keys/values/entries on Array, but doesn't give us\n\t\t// any way to identify its iterator. So add our own shimmed field.\n\t\tif (Object.getPrototypeOf) {\n\t\t\taddIterator(Object.getPrototypeOf([].values()));\n\t\t}\n\n\t\tvar maxSafeInteger = Math.pow(2, 53) - 1;\n\t\tdefineProperties(Number, {\n\t\t\tMAX_SAFE_INTEGER: maxSafeInteger,\n\t\t\tMIN_SAFE_INTEGER: -maxSafeInteger,\n\t\t\tEPSILON: 2.220446049250313e-16,\n\n\t\t\tparseInt: globals.parseInt,\n\t\t\tparseFloat: globals.parseFloat,\n\n\t\t\tisFinite: function(value) {\n\t\t\t\treturn typeof value === 'number' && global_isFinite(value);\n\t\t\t},\n\n\t\t\tisInteger: function(value) {\n\t\t\t\treturn typeof value === 'number' &&\n\t\t\t\t\t!Number.isNaN(value) &&\n\t\t\t\t\tNumber.isFinite(value) &&\n\t\t\t\t\tES.ToInteger(value) === value;\n\t\t\t},\n\n\t\t\tisSafeInteger: function(value) {\n\t\t\t\treturn Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;\n\t\t\t},\n\n\t\t\tisNaN: function(value) {\n\t\t\t\t// NaN !== NaN, but they are identical.\n\t\t\t\t// NaNs are the only non-reflexive value, i.e., if x !== x,\n\t\t\t\t// then x is NaN.\n\t\t\t\t// isNaN is broken: it converts its argument to number, so\n\t\t\t\t// isNaN('foo') => true\n\t\t\t\treturn value !== value;\n\t\t\t}\n\n\t\t});\n\n\t\tif (supportsDescriptors) {\n\t\t\tdefineProperties(Object, {\n\t\t\t\tgetPropertyDescriptor: function(subject, name) {\n\t\t\t\t\tvar pd = Object.getOwnPropertyDescriptor(subject, name);\n\t\t\t\t\tvar proto = Object.getPrototypeOf(subject);\n\t\t\t\t\twhile (pd === undefined && proto !== null) {\n\t\t\t\t\t\tpd = Object.getOwnPropertyDescriptor(proto, name);\n\t\t\t\t\t\tproto = Object.getPrototypeOf(proto);\n\t\t\t\t\t}\n\t\t\t\t\treturn pd;\n\t\t\t\t},\n\n\t\t\t\tgetPropertyNames: function(subject) {\n\t\t\t\t\tvar result = Object.getOwnPropertyNames(subject);\n\t\t\t\t\tvar proto = Object.getPrototypeOf(subject);\n\n\t\t\t\t\tvar addProperty = function(property) {\n\t\t\t\t\t\tif (result.indexOf(property) === -1) {\n\t\t\t\t\t\t\tresult.push(property);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\twhile (proto !== null) {\n\t\t\t\t\t\tObject.getOwnPropertyNames(proto).forEach(addProperty);\n\t\t\t\t\t\tproto = Object.getPrototypeOf(proto);\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tdefineProperties(Object, {\n\t\t\t\t// 19.1.3.1\n\t\t\t\tassign: function(target, source) {\n\t\t\t\t\tif (!ES.TypeIsObject(target)) {\n\t\t\t\t\t\tthrow new TypeError('target must be an object');\n\t\t\t\t\t}\n\t\t\t\t\treturn Array.prototype.reduce.call(arguments, function(target, source) {\n\t\t\t\t\t\tif (!ES.TypeIsObject(source)) {\n\t\t\t\t\t\t\tthrow new TypeError('source must be an object');\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn Object.keys(source).reduce(function(target, key) {\n\t\t\t\t\t\t\ttarget[key] = source[key];\n\t\t\t\t\t\t\treturn target;\n\t\t\t\t\t\t}, target);\n\t\t\t\t\t});\n\t\t\t\t},\n\n\t\t\t\tgetOwnPropertyKeys: function(subject) {\n\t\t\t\t\treturn Object.keys(subject);\n\t\t\t\t},\n\n\t\t\t\tis: function(a, b) {\n\t\t\t\t\treturn ES.SameValue(a, b);\n\t\t\t\t},\n\n\t\t\t\t// 19.1.3.9\n\t\t\t\t// shim from https://gist.github.com/WebReflection/5593554\n\t\t\t\tsetPrototypeOf: (function(Object, magic) {\n\t\t\t\t\tvar set;\n\n\t\t\t\t\tvar checkArgs = function(O, proto) {\n\t\t\t\t\t\tif (!ES.TypeIsObject(O)) {\n\t\t\t\t\t\t\tthrow new TypeError('cannot set prototype on a non-object');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(proto===null || ES.TypeIsObject(proto))) {\n\t\t\t\t\t\t\tthrow new TypeError('can only set prototype to an object or null'+proto);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tvar setPrototypeOf = function(O, proto) {\n\t\t\t\t\t\tcheckArgs(O, proto);\n\t\t\t\t\t\tset.call(O, proto);\n\t\t\t\t\t\treturn O;\n\t\t\t\t\t};\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// this works already in Firefox and Safari\n\t\t\t\t\t\tset = Object.getOwnPropertyDescriptor(Object.prototype, magic).set;\n\t\t\t\t\t\tset.call({}, null);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (Object.prototype !== {}[magic]) {\n\t\t\t\t\t\t\t// IE < 11 cannot be shimmed\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// probably Chrome or some old Mobile stock browser\n\t\t\t\t\t\tset = function(proto) {\n\t\t\t\t\t\t\tthis[magic] = proto;\n\t\t\t\t\t\t};\n\t\t\t\t\t\t// please note that this will **not** work\n\t\t\t\t\t\t// in those browsers that do not inherit\n\t\t\t\t\t\t// __proto__ by mistake from Object.prototype\n\t\t\t\t\t\t// in these cases we should probably throw an error\n\t\t\t\t\t\t// or at least be informed about the issue\n\t\t\t\t\t\tsetPrototypeOf.polyfill = setPrototypeOf(\n\t\t\t\t\t\t\tsetPrototypeOf({}, null),\n\t\t\t\t\t\t\tObject.prototype\n\t\t\t\t\t\t) instanceof Object;\n\t\t\t\t\t\t// setPrototypeOf.polyfill === true means it works as meant\n\t\t\t\t\t\t// setPrototypeOf.polyfill === false means it's not 100% reliable\n\t\t\t\t\t\t// setPrototypeOf.polyfill === undefined\n\t\t\t\t\t\t// or\n\t\t\t\t\t\t// setPrototypeOf.polyfill == null means it's not a polyfill\n\t\t\t\t\t\t// which means it works as expected\n\t\t\t\t\t\t// we can even delete Object.prototype.__proto__;\n\t\t\t\t\t}\n\t\t\t\t\treturn setPrototypeOf;\n\t\t\t\t})(Object, '__proto__')\n\t\t\t});\n\t\t}\n\n\t\t// Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work,\n\t\t// but Object.create(null) does.\n\t\tif (Object.setPrototypeOf && Object.getPrototypeOf &&\n\t\t\tObject.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null &&\n\t\t\tObject.getPrototypeOf(Object.create(null)) === null) {\n\t\t\t(function() {\n\t\t\t\tvar FAKENULL = Object.create(null);\n\t\t\t\tvar gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf;\n\t\t\t\tObject.getPrototypeOf = function(o) {\n\t\t\t\t\tvar result = gpo(o);\n\t\t\t\t\treturn result === FAKENULL ? null : result;\n\t\t\t\t};\n\t\t\t\tObject.setPrototypeOf = function(o, p) {\n\t\t\t\t\tif (p === null) { p = FAKENULL; }\n\t\t\t\t\treturn spo(o, p);\n\t\t\t\t};\n\t\t\t\tObject.setPrototypeOf.polyfill = false;\n\t\t\t})();\n\t\t}\n\n\t\ttry {\n\t\t\tObject.keys('foo');\n\t\t} catch (e) {\n\t\t\tvar originalObjectKeys = Object.keys;\n\t\t\tObject.keys = function (obj) {\n\t\t\t\treturn originalObjectKeys(ES.ToObject(obj));\n\t\t\t};\n\t\t}\n\n\t\tvar MathShims = {\n\t\t\tacosh: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (Number.isNaN(value) || value < 1) return NaN;\n\t\t\t\tif (value === 1) return 0;\n\t\t\t\tif (value === Infinity) return value;\n\t\t\t\treturn Math.log(value + Math.sqrt(value * value - 1));\n\t\t\t},\n\n\t\t\tasinh: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (value === 0 || !global_isFinite(value)) {\n\t\t\t\t\treturn value;\n\t\t\t\t}\n\t\t\t\treturn value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1));\n\t\t\t},\n\n\t\t\tatanh: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (Number.isNaN(value) || value < -1 || value > 1) {\n\t\t\t\t\treturn NaN;\n\t\t\t\t}\n\t\t\t\tif (value === -1) return -Infinity;\n\t\t\t\tif (value === 1) return Infinity;\n\t\t\t\tif (value === 0) return value;\n\t\t\t\treturn 0.5 * Math.log((1 + value) / (1 - value));\n\t\t\t},\n\n\t\t\tcbrt: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (value === 0) return value;\n\t\t\t\tvar negate = value < 0, result;\n\t\t\t\tif (negate) value = -value;\n\t\t\t\tresult = Math.pow(value, 1/3);\n\t\t\t\treturn negate ? -result : result;\n\t\t\t},\n\n\t\t\tclz32: function(value) {\n\t\t\t\t// See https://bugs.ecmascript.org/show_bug.cgi?id=2465\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (Number.isNaN(value)) return NaN;\n\t\t\t\tvar number = ES.ToUint32(value);\n\t\t\t\tif (number === 0) {\n\t\t\t\t\treturn 32;\n\t\t\t\t}\n\t\t\t\treturn 32 - (number).toString(2).length;\n\t\t\t},\n\n\t\t\tcosh: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (value === 0) return 1; // +0 or -0\n\t\t\t\tif (Number.isNaN(value)) return NaN;\n\t\t\t\tif (!global_isFinite(value)) return Infinity;\n\t\t\t\tif (value < 0) value = -value;\n\t\t\t\tif (value > 21) return Math.exp(value) / 2;\n\t\t\t\treturn (Math.exp(value) + Math.exp(-value)) / 2;\n\t\t\t},\n\n\t\t\texpm1: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (value === -Infinity) return -1;\n\t\t\t\tif (!global_isFinite(value) || value === 0) return value;\n\t\t\t\treturn Math.exp(value) - 1;\n\t\t\t},\n\n\t\t\thypot: function(x, y) {\n\t\t\t\tvar anyNaN = false;\n\t\t\t\tvar allZero = true;\n\t\t\t\tvar anyInfinity = false;\n\t\t\t\tvar numbers = [];\n\t\t\t\tArray.prototype.every.call(arguments, function(arg) {\n\t\t\t\t\tvar num = Number(arg);\n\t\t\t\t\tif (Number.isNaN(num)) anyNaN = true;\n\t\t\t\t\telse if (num === Infinity || num === -Infinity) anyInfinity = true;\n\t\t\t\t\telse if (num !== 0) allZero = false;\n\t\t\t\t\tif (anyInfinity) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t} else if (!anyNaN) {\n\t\t\t\t\t\tnumbers.push(Math.abs(num));\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tif (anyInfinity) return Infinity;\n\t\t\t\tif (anyNaN) return NaN;\n\t\t\t\tif (allZero) return 0;\n\n\t\t\t\tnumbers.sort(function (a, b) { return b - a; });\n\t\t\t\tvar largest = numbers[0];\n\t\t\t\tvar divided = numbers.map(function (number) { return number / largest; });\n\t\t\t\tvar sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0);\n\t\t\t\treturn largest * Math.sqrt(sum);\n\t\t\t},\n\n\t\t\tlog2: function(value) {\n\t\t\t\treturn Math.log(value) * Math.LOG2E;\n\t\t\t},\n\n\t\t\tlog10: function(value) {\n\t\t\t\treturn Math.log(value) * Math.LOG10E;\n\t\t\t},\n\n\t\t\tlog1p: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (value < -1 || Number.isNaN(value)) return NaN;\n\t\t\t\tif (value === 0 || value === Infinity) return value;\n\t\t\t\tif (value === -1) return -Infinity;\n\t\t\t\tvar result = 0;\n\t\t\t\tvar n = 50;\n\n\t\t\t\tif (value < 0 || value > 1) return Math.log(1 + value);\n\t\t\t\tfor (var i = 1; i < n; i++) {\n\t\t\t\t\tif ((i % 2) === 0) {\n\t\t\t\t\t\tresult -= Math.pow(value, i) / i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult += Math.pow(value, i) / i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\n\t\t\tsign: function(value) {\n\t\t\t\tvar number = +value;\n\t\t\t\tif (number === 0) return number;\n\t\t\t\tif (Number.isNaN(number)) return number;\n\t\t\t\treturn number < 0 ? -1 : 1;\n\t\t\t},\n\n\t\t\tsinh: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (!global_isFinite(value) || value === 0) return value;\n\t\t\t\treturn (Math.exp(value) - Math.exp(-value)) / 2;\n\t\t\t},\n\n\t\t\ttanh: function(value) {\n\t\t\t\tvalue = Number(value);\n\t\t\t\tif (Number.isNaN(value) || value === 0) return value;\n\t\t\t\tif (value === Infinity) return 1;\n\t\t\t\tif (value === -Infinity) return -1;\n\t\t\t\treturn (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value));\n\t\t\t},\n\n\t\t\ttrunc: function(value) {\n\t\t\t\tvar number = Number(value);\n\t\t\t\treturn number < 0 ? -Math.floor(-number) : Math.floor(number);\n\t\t\t},\n\n\t\t\timul: function(x, y) {\n\t\t\t\t// taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul\n\t\t\t\tvar ah = (x >>> 16) & 0xffff;\n\t\t\t\tvar al = x & 0xffff;\n\t\t\t\tvar bh = (y >>> 16) & 0xffff;\n\t\t\t\tvar bl = y & 0xffff;\n\t\t\t\t// the shift by 0 fixes the sign on the high part\n\t\t\t\t// the final |0 converts the unsigned value into a signed value\n\t\t\t\treturn ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);\n\t\t\t},\n\n\t\t\tfround: function(x) {\n\t\t\t\tif (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) {\n\t\t\t\t\treturn x;\n\t\t\t\t}\n\t\t\t\tvar num = Number(x);\n\t\t\t\treturn numberConversion.toFloat32(num);\n\t\t\t}\n\t\t};\n\t\tdefineProperties(Math, MathShims);\n\n\t\tif (Math.imul(0xffffffff, 5) !== -5) {\n\t\t\t// Safari 6.1, at least, reports \"0\" for this value\n\t\t\tMath.imul = MathShims.imul;\n\t\t}\n\n\t\t// Promises\n\t\t// Simplest possible implementation; use a 3rd-party library if you\n\t\t// want the best possible speed and/or long stack traces.\n\t\tvar PromiseShim = (function() {\n\n\t\t\tvar Promise, Promise$prototype;\n\n\t\t\tES.IsPromise = function(promise) {\n\t\t\t\tif (!ES.TypeIsObject(promise)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (!promise._promiseConstructor) {\n\t\t\t\t\t// _promiseConstructor is a bit more unique than _status, so we'll\n\t\t\t\t\t// check that instead of the [[PromiseStatus]] internal field.\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (promise._status === undefined) {\n\t\t\t\t\treturn false; // uninitialized\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\t// \"PromiseCapability\" in the spec is what most promise implementations\n\t\t\t// call a \"deferred\".\n\t\t\tvar PromiseCapability = function(C) {\n\t\t\t\tif (!ES.IsCallable(C)) {\n\t\t\t\t\tthrow new TypeError('bad promise constructor');\n\t\t\t\t}\n\t\t\t\tvar capability = this;\n\t\t\t\tvar resolver = function(resolve, reject) {\n\t\t\t\t\tcapability.resolve = resolve;\n\t\t\t\t\tcapability.reject = reject;\n\t\t\t\t};\n\t\t\t\tcapability.promise = ES.Construct(C, [resolver]);\n\t\t\t\t// see https://bugs.ecmascript.org/show_bug.cgi?id=2478\n\t\t\t\tif (!capability.promise._es6construct) {\n\t\t\t\t\tthrow new TypeError('bad promise constructor');\n\t\t\t\t}\n\t\t\t\tif (!(ES.IsCallable(capability.resolve) &&\n\t\t\t\t\tES.IsCallable(capability.reject))) {\n\t\t\t\t\tthrow new TypeError('bad promise constructor');\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// find an appropriate setImmediate-alike\n\t\t\tvar setTimeout = globals.setTimeout;\n\t\t\tvar makeZeroTimeout;\n\t\t\tif (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) {\n\t\t\t\tmakeZeroTimeout = function() {\n\t\t\t\t\t// from http://dbaron.org/log/20100309-faster-timeouts\n\t\t\t\t\tvar timeouts = [];\n\t\t\t\t\tvar messageName = \"zero-timeout-message\";\n\t\t\t\t\tvar setZeroTimeout = function(fn) {\n\t\t\t\t\t\ttimeouts.push(fn);\n\t\t\t\t\t\twindow.postMessage(messageName, \"*\");\n\t\t\t\t\t};\n\t\t\t\t\tvar handleMessage = function(event) {\n\t\t\t\t\t\tif (event.source == window && event.data == messageName) {\n\t\t\t\t\t\t\tevent.stopPropagation();\n\t\t\t\t\t\t\tif (timeouts.length === 0) { return; }\n\t\t\t\t\t\t\tvar fn = timeouts.shift();\n\t\t\t\t\t\t\tfn();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\twindow.addEventListener(\"message\", handleMessage, true);\n\t\t\t\t\treturn setZeroTimeout;\n\t\t\t\t};\n\t\t\t}\n\t\t\tvar makePromiseAsap = function() {\n\t\t\t\t// An efficient task-scheduler based on a pre-existing Promise\n\t\t\t\t// implementation, which we can use even if we override the\n\t\t\t\t// global Promise below (in order to workaround bugs)\n\t\t\t\t// https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671\n\t\t\t\tvar P = globals.Promise;\n\t\t\t\treturn P && P.resolve && function(task) {\n\t\t\t\t\treturn P.resolve().then(task);\n\t\t\t\t};\n\t\t\t};\n\t\t\tvar enqueue = ES.IsCallable(globals.setImmediate) ?\n\t\t\t\tglobals.setImmediate.bind(globals) :\n\t\t\t\ttypeof process === 'object' && process.nextTick ? process.nextTick :\n\t\t\t\t\tmakePromiseAsap() ||\n\t\t\t\t\t\t(ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() :\n\t\t\t\t\t\t\tfunction(task) { setTimeout(task, 0); }); // fallback\n\n\t\t\tvar triggerPromiseReactions = function(reactions, x) {\n\t\t\t\treactions.forEach(function(reaction) {\n\t\t\t\t\tenqueue(function() {\n\t\t\t\t\t\t// PromiseReactionTask\n\t\t\t\t\t\tvar handler = reaction.handler;\n\t\t\t\t\t\tvar capability = reaction.capability;\n\t\t\t\t\t\tvar resolve = capability.resolve;\n\t\t\t\t\t\tvar reject = capability.reject;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tvar result = handler(x);\n\t\t\t\t\t\t\tif (result === capability.promise) {\n\t\t\t\t\t\t\t\tthrow new TypeError('self resolution');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvar updateResult =\n\t\t\t\t\t\t\t\tupdatePromiseFromPotentialThenable(result, capability);\n\t\t\t\t\t\t\tif (!updateResult) {\n\t\t\t\t\t\t\t\tresolve(result);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\treject(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tvar updatePromiseFromPotentialThenable = function(x, capability) {\n\t\t\t\tif (!ES.TypeIsObject(x)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tvar resolve = capability.resolve;\n\t\t\t\tvar reject = capability.reject;\n\t\t\t\ttry {\n\t\t\t\t\tvar then = x.then; // only one invocation of accessor\n\t\t\t\t\tif (!ES.IsCallable(then)) { return false; }\n\t\t\t\t\tthen.call(x, resolve, reject);\n\t\t\t\t} catch(e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\tvar promiseResolutionHandler = function(promise, onFulfilled, onRejected){\n\t\t\t\treturn function(x) {\n\t\t\t\t\tif (x === promise) {\n\t\t\t\t\t\treturn onRejected(new TypeError('self resolution'));\n\t\t\t\t\t}\n\t\t\t\t\tvar C = promise._promiseConstructor;\n\t\t\t\t\tvar capability = new PromiseCapability(C);\n\t\t\t\t\tvar updateResult = updatePromiseFromPotentialThenable(x, capability);\n\t\t\t\t\tif (updateResult) {\n\t\t\t\t\t\treturn capability.promise.then(onFulfilled, onRejected);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn onFulfilled(x);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tPromise = function(resolver) {\n\t\t\t\tvar promise = this;\n\t\t\t\tpromise = emulateES6construct(promise);\n\t\t\t\tif (!promise._promiseConstructor) {\n\t\t\t\t\t// we use _promiseConstructor as a stand-in for the internal\n\t\t\t\t\t// [[PromiseStatus]] field; it's a little more unique.\n\t\t\t\t\tthrow new TypeError('bad promise');\n\t\t\t\t}\n\t\t\t\tif (promise._status !== undefined) {\n\t\t\t\t\tthrow new TypeError('promise already initialized');\n\t\t\t\t}\n\t\t\t\t// see https://bugs.ecmascript.org/show_bug.cgi?id=2482\n\t\t\t\tif (!ES.IsCallable(resolver)) {\n\t\t\t\t\tthrow new TypeError('not a valid resolver');\n\t\t\t\t}\n\t\t\t\tpromise._status = 'unresolved';\n\t\t\t\tpromise._resolveReactions = [];\n\t\t\t\tpromise._rejectReactions = [];\n\n\t\t\t\tvar resolve = function(resolution) {\n\t\t\t\t\tif (promise._status !== 'unresolved') { return; }\n\t\t\t\t\tvar reactions = promise._resolveReactions;\n\t\t\t\t\tpromise._result = resolution;\n\t\t\t\t\tpromise._resolveReactions = undefined;\n\t\t\t\t\tpromise._rejectReactions = undefined;\n\t\t\t\t\tpromise._status = 'has-resolution';\n\t\t\t\t\ttriggerPromiseReactions(reactions, resolution);\n\t\t\t\t};\n\t\t\t\tvar reject = function(reason) {\n\t\t\t\t\tif (promise._status !== 'unresolved') { return; }\n\t\t\t\t\tvar reactions = promise._rejectReactions;\n\t\t\t\t\tpromise._result = reason;\n\t\t\t\t\tpromise._resolveReactions = undefined;\n\t\t\t\t\tpromise._rejectReactions = undefined;\n\t\t\t\t\tpromise._status = 'has-rejection';\n\t\t\t\t\ttriggerPromiseReactions(reactions, reason);\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tresolver(resolve, reject);\n\t\t\t\t} catch (e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t\treturn promise;\n\t\t\t};\n\t\t\tPromise$prototype = Promise.prototype;\n\t\t\tdefineProperties(Promise, {\n\t\t\t\t'@@create': function(obj) {\n\t\t\t\t\tvar constructor = this;\n\t\t\t\t\t// AllocatePromise\n\t\t\t\t\t// The `obj` parameter is a hack we use for es5\n\t\t\t\t\t// compatibility.\n\t\t\t\t\tvar prototype = constructor.prototype || Promise$prototype;\n\t\t\t\t\tobj = obj || create(prototype);\n\t\t\t\t\tdefineProperties(obj, {\n\t\t\t\t\t\t_status: undefined,\n\t\t\t\t\t\t_result: undefined,\n\t\t\t\t\t\t_resolveReactions: undefined,\n\t\t\t\t\t\t_rejectReactions: undefined,\n\t\t\t\t\t\t_promiseConstructor: undefined\n\t\t\t\t\t});\n\t\t\t\t\tobj._promiseConstructor = constructor;\n\t\t\t\t\treturn obj;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tvar _promiseAllResolver = function(index, values, capability, remaining) {\n\t\t\t\tvar done = false;\n\t\t\t\treturn function(x) {\n\t\t\t\t\tif (done) { return; } // protect against being called multiple times\n\t\t\t\t\tdone = true;\n\t\t\t\t\tvalues[index] = x;\n\t\t\t\t\tif ((--remaining.count) === 0) {\n\t\t\t\t\t\tvar resolve = capability.resolve;\n\t\t\t\t\t\tresolve(values); // call w/ this===undefined\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tPromise.all = function(iterable) {\n\t\t\t\tvar C = this;\n\t\t\t\tvar capability = new PromiseCapability(C);\n\t\t\t\tvar resolve = capability.resolve;\n\t\t\t\tvar reject = capability.reject;\n\t\t\t\ttry {\n\t\t\t\t\tif (!ES.IsIterable(iterable)) {\n\t\t\t\t\t\tthrow new TypeError('bad iterable');\n\t\t\t\t\t}\n\t\t\t\t\tvar it = ES.GetIterator(iterable);\n\t\t\t\t\tvar values = [], remaining = { count: 1 };\n\t\t\t\t\tfor (var index = 0; ; index++) {\n\t\t\t\t\t\tvar next = ES.IteratorNext(it);\n\t\t\t\t\t\tif (next.done) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar nextPromise = C.resolve(next.value);\n\t\t\t\t\t\tvar resolveElement = _promiseAllResolver(\n\t\t\t\t\t\t\tindex, values, capability, remaining\n\t\t\t\t\t\t);\n\t\t\t\t\t\tremaining.count++;\n\t\t\t\t\t\tnextPromise.then(resolveElement, capability.reject);\n\t\t\t\t\t}\n\t\t\t\t\tif ((--remaining.count) === 0) {\n\t\t\t\t\t\tresolve(values); // call w/ this===undefined\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t\treturn capability.promise;\n\t\t\t};\n\n\t\t\tPromise.race = function(iterable) {\n\t\t\t\tvar C = this;\n\t\t\t\tvar capability = new PromiseCapability(C);\n\t\t\t\tvar resolve = capability.resolve;\n\t\t\t\tvar reject = capability.reject;\n\t\t\t\ttry {\n\t\t\t\t\tif (!ES.IsIterable(iterable)) {\n\t\t\t\t\t\tthrow new TypeError('bad iterable');\n\t\t\t\t\t}\n\t\t\t\t\tvar it = ES.GetIterator(iterable);\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tvar next = ES.IteratorNext(it);\n\t\t\t\t\t\tif (next.done) {\n\t\t\t\t\t\t\t// If iterable has no items, resulting promise will never\n\t\t\t\t\t\t\t// resolve; see:\n\t\t\t\t\t\t\t// https://github.com/domenic/promises-unwrapping/issues/75\n\t\t\t\t\t\t\t// https://bugs.ecmascript.org/show_bug.cgi?id=2515\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar nextPromise = C.resolve(next.value);\n\t\t\t\t\t\tnextPromise.then(resolve, reject);\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t\treturn capability.promise;\n\t\t\t};\n\n\t\t\tPromise.reject = function(reason) {\n\t\t\t\tvar C = this;\n\t\t\t\tvar capability = new PromiseCapability(C);\n\t\t\t\tvar reject = capability.reject;\n\t\t\t\treject(reason); // call with this===undefined\n\t\t\t\treturn capability.promise;\n\t\t\t};\n\n\t\t\tPromise.resolve = function(v) {\n\t\t\t\tvar C = this;\n\t\t\t\tif (ES.IsPromise(v)) {\n\t\t\t\t\tvar constructor = v._promiseConstructor;\n\t\t\t\t\tif (constructor === C) { return v; }\n\t\t\t\t}\n\t\t\t\tvar capability = new PromiseCapability(C);\n\t\t\t\tvar resolve = capability.resolve;\n\t\t\t\tresolve(v); // call with this===undefined\n\t\t\t\treturn capability.promise;\n\t\t\t};\n\n\t\t\tPromise.prototype['catch'] = function( onRejected ) {\n\t\t\t\treturn this.then(undefined, onRejected);\n\t\t\t};\n\n\t\t\tPromise.prototype.then = function( onFulfilled, onRejected ) {\n\t\t\t\tvar promise = this;\n\t\t\t\tif (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); }\n\t\t\t\t// this.constructor not this._promiseConstructor; see\n\t\t\t\t// https://bugs.ecmascript.org/show_bug.cgi?id=2513\n\t\t\t\tvar C = this.constructor;\n\t\t\t\tvar capability = new PromiseCapability(C);\n\t\t\t\tif (!ES.IsCallable(onRejected)) {\n\t\t\t\t\tonRejected = function(e) { throw e; };\n\t\t\t\t}\n\t\t\t\tif (!ES.IsCallable(onFulfilled)) {\n\t\t\t\t\tonFulfilled = function(x) { return x; };\n\t\t\t\t}\n\t\t\t\tvar resolutionHandler =\n\t\t\t\t\tpromiseResolutionHandler(promise, onFulfilled, onRejected);\n\t\t\t\tvar resolveReaction =\n\t\t\t\t{ capability: capability, handler: resolutionHandler };\n\t\t\t\tvar rejectReaction =\n\t\t\t\t{ capability: capability, handler: onRejected };\n\t\t\t\tswitch (promise._status) {\n\t\t\t\t\tcase 'unresolved':\n\t\t\t\t\t\tpromise._resolveReactions.push(resolveReaction);\n\t\t\t\t\t\tpromise._rejectReactions.push(rejectReaction);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'has-resolution':\n\t\t\t\t\t\ttriggerPromiseReactions([resolveReaction], promise._result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'has-rejection':\n\t\t\t\t\t\ttriggerPromiseReactions([rejectReaction], promise._result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new TypeError('unexpected');\n\t\t\t\t}\n\t\t\t\treturn capability.promise;\n\t\t\t};\n\n\t\t\treturn Promise;\n\t\t})();\n\t\t// export the Promise constructor.\n\t\tdefineProperties(globals, { Promise: PromiseShim });\n\t\t// In Chrome 33 (and thereabouts) Promise is defined, but the\n\t\t// implementation is buggy in a number of ways. Let's check subclassing\n\t\t// support to see if we have a buggy implementation.\n\t\tvar promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function(S) {\n\t\t\treturn S.resolve(42) instanceof S;\n\t\t});\n\t\tvar promiseIgnoresNonFunctionThenCallbacks = (function () {\n\t\t\ttry {\n\t\t\t\tglobals.Promise.reject(42).then(null, 5).then(null, function () {});\n\t\t\t\treturn true;\n\t\t\t} catch (ex) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}());\n\t\tif (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks) {\n\t\t\tglobals.Promise = PromiseShim;\n\t\t}\n\n\t\t// Map and Set require a true ES5 environment\n\t\tif (supportsDescriptors) {\n\n\t\t\tvar fastkey = function fastkey(key) {\n\t\t\t\tvar type = typeof key;\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\treturn '$' + key;\n\t\t\t\t} else if (type === 'number') {\n\t\t\t\t\t// note that -0 will get coerced to \"0\" when used as a property key\n\t\t\t\t\treturn key;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t};\n\n\t\t\tvar emptyObject = function emptyObject() {\n\t\t\t\t// accomodate some older not-quite-ES5 browsers\n\t\t\t\treturn Object.create ? Object.create(null) : {};\n\t\t\t};\n\n\t\t\tvar collectionShims = {\n\t\t\t\tMap: (function() {\n\n\t\t\t\t\tvar empty = {};\n\n\t\t\t\t\tfunction MapEntry(key, value) {\n\t\t\t\t\t\tthis.key = key;\n\t\t\t\t\t\tthis.value = value;\n\t\t\t\t\t\tthis.next = null;\n\t\t\t\t\t\tthis.prev = null;\n\t\t\t\t\t}\n\n\t\t\t\t\tMapEntry.prototype.isRemoved = function() {\n\t\t\t\t\t\treturn this.key === empty;\n\t\t\t\t\t};\n\n\t\t\t\t\tfunction MapIterator(map, kind) {\n\t\t\t\t\t\tthis.head = map._head;\n\t\t\t\t\t\tthis.i = this.head;\n\t\t\t\t\t\tthis.kind = kind;\n\t\t\t\t\t}\n\n\t\t\t\t\tMapIterator.prototype = {\n\t\t\t\t\t\tnext: function() {\n\t\t\t\t\t\t\tvar i = this.i, kind = this.kind, head = this.head, result;\n\t\t\t\t\t\t\tif (this.i === undefined) {\n\t\t\t\t\t\t\t\treturn { value: undefined, done: true };\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twhile (i.isRemoved() && i !== head) {\n\t\t\t\t\t\t\t\t// back up off of removed entries\n\t\t\t\t\t\t\t\ti = i.prev;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// advance to next unreturned element.\n\t\t\t\t\t\t\twhile (i.next !== head) {\n\t\t\t\t\t\t\t\ti = i.next;\n\t\t\t\t\t\t\t\tif (!i.isRemoved()) {\n\t\t\t\t\t\t\t\t\tif (kind === \"key\") {\n\t\t\t\t\t\t\t\t\t\tresult = i.key;\n\t\t\t\t\t\t\t\t\t} else if (kind === \"value\") {\n\t\t\t\t\t\t\t\t\t\tresult = i.value;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tresult = [i.key, i.value];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.i = i;\n\t\t\t\t\t\t\t\t\treturn { value: result, done: false };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// once the iterator is done, it is done forever.\n\t\t\t\t\t\t\tthis.i = undefined;\n\t\t\t\t\t\t\treturn { value: undefined, done: true };\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\taddIterator(MapIterator.prototype);\n\n\t\t\t\t\tfunction Map() {\n\t\t\t\t\t\tvar map = this;\n\t\t\t\t\t\tmap = emulateES6construct(map);\n\t\t\t\t\t\tif (!map._es6map) {\n\t\t\t\t\t\t\tthrow new TypeError('bad map');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar head = new MapEntry(null, null);\n\t\t\t\t\t\t// circular doubly-linked list.\n\t\t\t\t\t\thead.next = head.prev = head;\n\n\t\t\t\t\t\tdefineProperties(map, {\n\t\t\t\t\t\t\t'_head': head,\n\t\t\t\t\t\t\t'_storage': emptyObject(),\n\t\t\t\t\t\t\t'_size': 0\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Optionally initialize map from iterable\n\t\t\t\t\t\tvar iterable = arguments[0];\n\t\t\t\t\t\tif (iterable !== undefined && iterable !== null) {\n\t\t\t\t\t\t\tvar it = ES.GetIterator(iterable);\n\t\t\t\t\t\t\tvar adder = map.set;\n\t\t\t\t\t\t\tif (!ES.IsCallable(adder)) { throw new TypeError('bad map'); }\n\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\tvar next = ES.IteratorNext(it);\n\t\t\t\t\t\t\t\tif (next.done) { break; }\n\t\t\t\t\t\t\t\tvar nextItem = next.value;\n\t\t\t\t\t\t\t\tif (!ES.TypeIsObject(nextItem)) {\n\t\t\t\t\t\t\t\t\tthrow new TypeError('expected iterable of pairs');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tadder.call(map, nextItem[0], nextItem[1]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn map;\n\t\t\t\t\t}\n\t\t\t\t\tvar Map$prototype = Map.prototype;\n\t\t\t\t\tdefineProperties(Map, {\n\t\t\t\t\t\t'@@create': function(obj) {\n\t\t\t\t\t\t\tvar constructor = this;\n\t\t\t\t\t\t\tvar prototype = constructor.prototype || Map$prototype;\n\t\t\t\t\t\t\tobj = obj || create(prototype);\n\t\t\t\t\t\t\tdefineProperties(obj, { _es6map: true });\n\t\t\t\t\t\t\treturn obj;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tObject.defineProperty(Map.prototype, 'size', {\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tenumerable: false,\n\t\t\t\t\t\tget: function() {\n\t\t\t\t\t\t\tif (typeof this._size === 'undefined') {\n\t\t\t\t\t\t\t\tthrow new TypeError('size method called on incompatible Map');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn this._size;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tdefineProperties(Map.prototype, {\n\t\t\t\t\t\tget: function(key) {\n\t\t\t\t\t\t\tvar fkey = fastkey(key);\n\t\t\t\t\t\t\tif (fkey !== null) {\n\t\t\t\t\t\t\t\t// fast O(1) path\n\t\t\t\t\t\t\t\tvar entry = this._storage[fkey];\n\t\t\t\t\t\t\t\treturn entry ? entry.value : undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvar head = this._head, i = head;\n\t\t\t\t\t\t\twhile ((i = i.next) !== head) {\n\t\t\t\t\t\t\t\tif (ES.SameValueZero(i.key, key)) {\n\t\t\t\t\t\t\t\t\treturn i.value;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\thas: function(key) {\n\t\t\t\t\t\t\tvar fkey = fastkey(key);\n\t\t\t\t\t\t\tif (fkey !== null) {\n\t\t\t\t\t\t\t\t// fast O(1) path\n\t\t\t\t\t\t\t\treturn typeof this._storage[fkey] !== 'undefined';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvar head = this._head, i = head;\n\t\t\t\t\t\t\twhile ((i = i.next) !== head) {\n\t\t\t\t\t\t\t\tif (ES.SameValueZero(i.key, key)) {\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tset: function(key, value) {\n\t\t\t\t\t\t\tvar head = this._head, i = head, entry;\n\t\t\t\t\t\t\tvar fkey = fastkey(key);\n\t\t\t\t\t\t\tif (fkey !== null) {\n\t\t\t\t\t\t\t\t// fast O(1) path\n\t\t\t\t\t\t\t\tif (typeof this._storage[fkey] !== 'undefined') {\n\t\t\t\t\t\t\t\t\tthis._storage[fkey].value = value;\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tentry = this._storage[fkey] = new MapEntry(key, value);\n\t\t\t\t\t\t\t\t\ti = head.prev;\n\t\t\t\t\t\t\t\t\t// fall through\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twhile ((i = i.next) !== head) {\n\t\t\t\t\t\t\t\tif (ES.SameValueZero(i.key, key)) {\n\t\t\t\t\t\t\t\t\ti.value = value;\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tentry = entry || new MapEntry(key, value);\n\t\t\t\t\t\t\tif (ES.SameValue(-0, key)) {\n\t\t\t\t\t\t\t\tentry.key = +0; // coerce -0 to +0 in entry\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tentry.next = this._head;\n\t\t\t\t\t\t\tentry.prev = this._head.prev;\n\t\t\t\t\t\t\tentry.prev.next = entry;\n\t\t\t\t\t\t\tentry.next.prev = entry;\n\t\t\t\t\t\t\tthis._size += 1;\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t'delete': function(key) {\n\t\t\t\t\t\t\tvar head = this._head, i = head;\n\t\t\t\t\t\t\tvar fkey = fastkey(key);\n\t\t\t\t\t\t\tif (fkey !== null) {\n\t\t\t\t\t\t\t\t// fast O(1) path\n\t\t\t\t\t\t\t\tif (typeof this._storage[fkey] === 'undefined') {\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ti = this._storage[fkey].prev;\n\t\t\t\t\t\t\t\tdelete this._storage[fkey];\n\t\t\t\t\t\t\t\t// fall through\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twhile ((i = i.next) !== head) {\n\t\t\t\t\t\t\t\tif (ES.SameValueZero(i.key, key)) {\n\t\t\t\t\t\t\t\t\ti.key = i.value = empty;\n\t\t\t\t\t\t\t\t\ti.prev.next = i.next;\n\t\t\t\t\t\t\t\t\ti.next.prev = i.prev;\n\t\t\t\t\t\t\t\t\tthis._size -= 1;\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tclear: function() {\n\t\t\t\t\t\t\tthis._size = 0;\n\t\t\t\t\t\t\tthis._storage = emptyObject();\n\t\t\t\t\t\t\tvar head = this._head, i = head, p = i.next;\n\t\t\t\t\t\t\twhile ((i = p) !== head) {\n\t\t\t\t\t\t\t\ti.key = i.value = empty;\n\t\t\t\t\t\t\t\tp = i.next;\n\t\t\t\t\t\t\t\ti.next = i.prev = head;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\thead.next = head.prev = head;\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tkeys: function() {\n\t\t\t\t\t\t\treturn new MapIterator(this, \"key\");\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tvalues: function() {\n\t\t\t\t\t\t\treturn new MapIterator(this, \"value\");\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tentries: function() {\n\t\t\t\t\t\t\treturn new MapIterator(this, \"key+value\");\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tforEach: function(callback) {\n\t\t\t\t\t\t\tvar context = arguments.length > 1 ? arguments[1] : null;\n\t\t\t\t\t\t\tvar it = this.entries();\n\t\t\t\t\t\t\tfor (var entry = it.next(); !entry.done; entry = it.next()) {\n\t\t\t\t\t\t\t\tcallback.call(context, entry.value[1], entry.value[0], this);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\taddIterator(Map.prototype, function() { return this.entries(); });\n\n\t\t\t\t\treturn Map;\n\t\t\t\t})(),\n\n\t\t\t\tSet: (function() {\n\t\t\t\t\t// Creating a Map is expensive. To speed up the common case of\n\t\t\t\t\t// Sets containing only string or numeric keys, we use an object\n\t\t\t\t\t// as backing storage and lazily create a full Map only when\n\t\t\t\t\t// required.\n\t\t\t\t\tvar SetShim = function Set() {\n\t\t\t\t\t\tvar set = this;\n\t\t\t\t\t\tset = emulateES6construct(set);\n\t\t\t\t\t\tif (!set._es6set) {\n\t\t\t\t\t\t\tthrow new TypeError('bad set');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdefineProperties(set, {\n\t\t\t\t\t\t\t'[[SetData]]': null,\n\t\t\t\t\t\t\t'_storage': emptyObject()\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Optionally initialize map from iterable\n\t\t\t\t\t\tvar iterable = arguments[0];\n\t\t\t\t\t\tif (iterable !== undefined && iterable !== null) {\n\t\t\t\t\t\t\tvar it = ES.GetIterator(iterable);\n\t\t\t\t\t\t\tvar adder = set.add;\n\t\t\t\t\t\t\tif (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }\n\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\tvar next = ES.IteratorNext(it);\n\t\t\t\t\t\t\t\tif (next.done) { break; }\n\t\t\t\t\t\t\t\tvar nextItem = next.value;\n\t\t\t\t\t\t\t\tadder.call(set, nextItem);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn set;\n\t\t\t\t\t};\n\t\t\t\t\tvar Set$prototype = SetShim.prototype;\n\t\t\t\t\tdefineProperties(SetShim, {\n\t\t\t\t\t\t'@@create': function(obj) {\n\t\t\t\t\t\t\tvar constructor = this;\n\t\t\t\t\t\t\tvar prototype = constructor.prototype || Set$prototype;\n\t\t\t\t\t\t\tobj = obj || create(prototype);\n\t\t\t\t\t\t\tdefineProperties(obj, { _es6set: true });\n\t\t\t\t\t\t\treturn obj;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\t// Switch from the object backing storage to a full Map.\n\t\t\t\t\tvar ensureMap = function ensureMap(set) {\n\t\t\t\t\t\tif (!set['[[SetData]]']) {\n\t\t\t\t\t\t\tvar m = set['[[SetData]]'] = new collectionShims.Map();\n\t\t\t\t\t\t\tObject.keys(set._storage).forEach(function(k) {\n\t\t\t\t\t\t\t\t// fast check for leading '$'\n\t\t\t\t\t\t\t\tif (k.charCodeAt(0) === 36) {\n\t\t\t\t\t\t\t\t\tk = k.substring(1);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tk = +k;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tm.set(k, k);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tset._storage = null; // free old backing storage\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tObject.defineProperty(SetShim.prototype, 'size', {\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tenumerable: false,\n\t\t\t\t\t\tget: function() {\n\t\t\t\t\t\t\tif (typeof this._storage === 'undefined') {\n\t\t\t\t\t\t\t\t// https://github.com/paulmillr/es6-shim/issues/176\n\t\t\t\t\t\t\t\tthrow new TypeError('size method called on incompatible Set');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\treturn this['[[SetData]]'].size;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tdefineProperties(SetShim.prototype, {\n\t\t\t\t\t\thas: function(key) {\n\t\t\t\t\t\t\tvar fkey;\n\t\t\t\t\t\t\tif (this._storage && (fkey = fastkey(key)) !== null) {\n\t\t\t\t\t\t\t\treturn !!this._storage[fkey];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\treturn this['[[SetData]]'].has(key);\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tadd: function(key) {\n\t\t\t\t\t\t\tvar fkey;\n\t\t\t\t\t\t\tif (this._storage && (fkey = fastkey(key)) !== null) {\n\t\t\t\t\t\t\t\tthis._storage[fkey]=true;\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\treturn this['[[SetData]]'].set(key, key);\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t'delete': function(key) {\n\t\t\t\t\t\t\tvar fkey;\n\t\t\t\t\t\t\tif (this._storage && (fkey = fastkey(key)) !== null) {\n\t\t\t\t\t\t\t\tdelete this._storage[fkey];\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\treturn this['[[SetData]]']['delete'](key);\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tclear: function() {\n\t\t\t\t\t\t\tif (this._storage) {\n\t\t\t\t\t\t\t\tthis._storage = emptyObject();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn this['[[SetData]]'].clear();\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tkeys: function() {\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\treturn this['[[SetData]]'].keys();\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tvalues: function() {\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\treturn this['[[SetData]]'].values();\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tentries: function() {\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\treturn this['[[SetData]]'].entries();\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tforEach: function(callback) {\n\t\t\t\t\t\t\tvar context = arguments.length > 1 ? arguments[1] : null;\n\t\t\t\t\t\t\tvar entireSet = this;\n\t\t\t\t\t\t\tensureMap(this);\n\t\t\t\t\t\t\tthis['[[SetData]]'].forEach(function(value, key) {\n\t\t\t\t\t\t\t\tcallback.call(context, key, key, entireSet);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\taddIterator(SetShim.prototype, function() { return this.values(); });\n\n\t\t\t\t\treturn SetShim;\n\t\t\t\t})()\n\t\t\t};\n\t\t\tdefineProperties(globals, collectionShims);\n\n\t\t\tif (globals.Map || globals.Set) {\n\t\t\t\t/*\n\t\t\t\t - In Firefox < 23, Map#size is a function.\n\t\t\t\t - In all current Firefox, Set#entries/keys/values & Map#clear do not exist\n\t\t\t\t - https://bugzilla.mozilla.org/show_bug.cgi?id=869996\n\t\t\t\t - In Firefox 24, Map and Set do not implement forEach\n\t\t\t\t - In Firefox 25 at least, Map and Set are callable without \"new\"\n\t\t\t\t */\n\t\t\t\tif (\n\t\t\t\t\ttypeof globals.Map.prototype.clear !== 'function' ||\n\t\t\t\t\t\tnew globals.Set().size !== 0 ||\n\t\t\t\t\t\tnew globals.Map().size !== 0 ||\n\t\t\t\t\t\ttypeof globals.Map.prototype.keys !== 'function' ||\n\t\t\t\t\t\ttypeof globals.Set.prototype.keys !== 'function' ||\n\t\t\t\t\t\ttypeof globals.Map.prototype.forEach !== 'function' ||\n\t\t\t\t\t\ttypeof globals.Set.prototype.forEach !== 'function' ||\n\t\t\t\t\t\tisCallableWithoutNew(globals.Map) ||\n\t\t\t\t\t\tisCallableWithoutNew(globals.Set) ||\n\t\t\t\t\t\t!supportsSubclassing(globals.Map, function(M) {\n\t\t\t\t\t\t\treturn (new M([])) instanceof M;\n\t\t\t\t\t\t})\n\t\t\t\t\t) {\n\t\t\t\t\tglobals.Map = collectionShims.Map;\n\t\t\t\t\tglobals.Set = collectionShims.Set;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Shim incomplete iterator implementations.\n\t\t\taddIterator(Object.getPrototypeOf((new globals.Map()).keys()));\n\t\t\taddIterator(Object.getPrototypeOf((new globals.Set()).keys()));\n\t\t}\n\t};\n\n\tif (typeof define === 'function' && define.amd) {\n\t\tdefine(main); // RequireJS\n\t} else {\n\t\tmain(); // CommonJS and \n \n @property value \n @type mixed\n @default element's text\n **/\n value: null,\n /**\n Callback to perform custom displaying of value in element's text. \n If `null`, default input's display used. \n If `false`, no displaying methods will be called, element's text will never change. \n Runs under element's scope. \n _**Parameters:**_ \n \n * `value` current value to be displayed\n * `response` server response (if display called after ajax submit), since 1.4.0\n \n For _inputs with source_ (select, checklist) parameters are different: \n \n * `value` current value to be displayed\n * `sourceData` array of items for current input (e.g. dropdown items) \n * `response` server response (if display called after ajax submit), since 1.4.0\n \n To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`.\n \n @property display \n @type function|boolean\n @default null\n @since 1.2.0\n @example\n display: function(value, sourceData) {\n //display checklist as comma-separated values\n var html = [],\n checked = $.fn.editableutils.itemsByValue(value, sourceData);\n \n if(checked.length) {\n $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });\n $(this).html(html.join(', '));\n } else {\n $(this).empty(); \n }\n }\n **/ \n display: null,\n /**\n Css class applied when editable text is empty.\n\n @property emptyclass \n @type string\n @since 1.4.1 \n @default editable-empty\n **/ \n emptyclass: 'editable-empty',\n /**\n Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). \n You may set it to `null` if you work with editables locally and submit them together. \n\n @property unsavedclass \n @type string\n @since 1.4.1 \n @default editable-unsaved\n **/ \n unsavedclass: 'editable-unsaved',\n /**\n If selector is provided, editable will be delegated to the specified targets. \n Usefull for dynamically generated DOM elements. \n **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, \n as they actually become editable only after first click. \n You should manually set class `editable-click` to these elements. \n Also, if element originally empty you should add class `editable-empty`, set `data-value=\"\"` and write emptytext into element:\n\n @property selector \n @type string\n @since 1.4.1 \n @default null\n @example\n
\n \n Empty\n \n Operator\n
\n \n \n **/ \n selector: null \n };\n \n}(window.jQuery));\n\r\n/**\nAbstractInput - base class for all editable inputs.\nIt defines interface to be implemented by any input type.\nTo create your own input you can inherit from this class.\n\n@class abstractinput\n**/\n(function ($) {\n \"use strict\";\n \n //types\n $.fn.editabletypes = {};\n \n var AbstractInput = function () { };\n\n AbstractInput.prototype = {\n /**\n Initializes input\n \n @method init() \n **/\n init: function(type, options, defaults) {\n this.type = type;\n this.options = $.extend({}, defaults, options);\n },\n \n /*\n this method called before render to init $tpl that is inserted in DOM\n */\n prerender: function() {\n this.$tpl = $(this.options.tpl); //whole tpl as jquery object \n this.$input = this.$tpl; //control itself, can be changed in render method\n this.$clear = null; //clear button\n this.error = null; //error message, if input cannot be rendered \n },\n \n /**\n Renders input from tpl. Can return jQuery deferred object.\n Can be overwritten in child objects\n \n @method render() \n **/ \n render: function() {\n\n }, \n\n /**\n Sets element's html by value. \n \n @method value2html(value, element) \n @param {mixed} value\n @param {DOMElement} element\n **/ \n value2html: function(value, element) {\n $(element).text(value);\n },\n \n /**\n Converts element's html to value\n \n @method html2value(html) \n @param {string} html\n @returns {mixed}\n **/ \n html2value: function(html) {\n return $('
').html(html).text();\n },\n \n /**\n Converts value to string (for internal compare). For submitting to server used value2submit().\n \n @method value2str(value) \n @param {mixed} value\n @returns {string}\n **/ \n value2str: function(value) {\n return value;\n }, \n \n /**\n Converts string received from server into value. Usually from `data-value` attribute.\n \n @method str2value(str) \n @param {string} str\n @returns {mixed}\n **/ \n str2value: function(str) {\n return str;\n }, \n \n /**\n Converts value for submitting to server. Result can be string or object.\n \n @method value2submit(value) \n @param {mixed} value\n @returns {mixed}\n **/ \n value2submit: function(value) {\n return value;\n }, \n \n /**\n Sets value of input.\n \n @method value2input(value) \n @param {mixed} value\n **/ \n value2input: function(value) {\n this.$input.val(value);\n },\n \n /**\n Returns value of input. Value can be object (e.g. datepicker)\n \n @method input2value() \n **/ \n input2value: function() { \n return this.$input.val();\n }, \n\n /**\n Activates input. For text it sets focus.\n \n @method activate() \n **/ \n activate: function() {\n if(this.$input.is(':visible')) {\n this.$input.focus();\n }\n },\n \n /**\n Creates input.\n \n @method clear() \n **/ \n clear: function() {\n this.$input.val(null);\n },\n \n /**\n method to escape html.\n **/\n escape: function(str) {\n return $('
').text(str).html();\n },\n \n /**\n attach handler to automatically submit form when value changed (useful when buttons not shown)\n **/ \n autosubmit: function() {\n \n },\n \n // -------- helper functions --------\n setClass: function() {\n if(this.options.inputclass) {\n this.$input.addClass(this.options.inputclass); \n } \n },\n \n setAttr: function(attr) {\n if (this.options[attr] !== undefined && this.options[attr] !== null) {\n this.$input.attr(attr, this.options[attr]);\n } \n },\n \n option: function(key, value) {\n this.options[key] = value;\n }\n \n };\n \n AbstractInput.defaults = { \n /**\n HTML template of input. Normally you should not change it.\n\n @property tpl \n @type string\n @default ''\n **/ \n tpl: '',\n /**\n CSS class automatically applied to input\n \n @property inputclass \n @type string\n @default input-medium\n **/ \n inputclass: 'input-medium',\n //scope for external methods (e.g. source defined as function)\n //for internal use only\n scope: null,\n \n //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults)\n showbuttons: true \n };\n \n $.extend($.fn.editabletypes, {abstractinput: AbstractInput});\n \n}(window.jQuery));\n\r\n/**\nList - abstract class for inputs that have source option loaded from js array or via ajax\n\n@class list\n@extends abstractinput\n**/\n(function ($) {\n \"use strict\";\n \n var List = function (options) {\n \n };\n\n $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput);\n\n $.extend(List.prototype, {\n render: function () {\n var deferred = $.Deferred();\n\n this.error = null;\n this.onSourceReady(function () {\n this.renderList();\n deferred.resolve();\n }, function () {\n this.error = this.options.sourceError;\n deferred.resolve();\n });\n\n return deferred.promise();\n },\n\n html2value: function (html) {\n return null; //can't set value by text\n },\n \n value2html: function (value, element, display, response) {\n var deferred = $.Deferred(),\n success = function () {\n if(typeof display === 'function') {\n //custom display method\n display.call(element, value, this.sourceData, response); \n } else {\n this.value2htmlFinal(value, element);\n }\n deferred.resolve();\n };\n \n //for null value just call success without loading source\n if(value === null) {\n success.call(this); \n } else {\n this.onSourceReady(success, function () { deferred.resolve(); });\n }\n\n return deferred.promise();\n }, \n\n // ------------- additional functions ------------\n\n onSourceReady: function (success, error) {\n //if allready loaded just call success\n if($.isArray(this.sourceData)) {\n success.call(this);\n return; \n }\n\n // try parse json in single quotes (for double quotes jquery does automatically)\n try {\n this.options.source = $.fn.editableutils.tryParseJson(this.options.source, false);\n } catch (e) {\n error.call(this);\n return;\n }\n \n var source = this.options.source;\n \n //run source if it function\n if ($.isFunction(source)) {\n source = source.call(this.options.scope);\n }\n\n //loading from url\n if (typeof source === 'string') {\n //try to get from cache\n if(this.options.sourceCache) {\n var cacheID = source,\n cache;\n\n if (!$(document).data(cacheID)) {\n $(document).data(cacheID, {});\n }\n cache = $(document).data(cacheID);\n\n //check for cached data\n if (cache.loading === false && cache.sourceData) { //take source from cache\n this.sourceData = cache.sourceData;\n this.doPrepend();\n success.call(this);\n return;\n } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later\n cache.callbacks.push($.proxy(function () {\n this.sourceData = cache.sourceData;\n this.doPrepend();\n success.call(this);\n }, this));\n\n //also collecting error callbacks\n cache.err_callbacks.push($.proxy(error, this));\n return;\n } else { //no cache yet, activate it\n cache.loading = true;\n cache.callbacks = [];\n cache.err_callbacks = [];\n }\n }\n \n //loading sourceData from server\n $.ajax({\n url: source,\n type: 'get',\n cache: false,\n dataType: 'json',\n success: $.proxy(function (data) {\n if(cache) {\n cache.loading = false;\n }\n this.sourceData = this.makeArray(data);\n if($.isArray(this.sourceData)) {\n if(cache) {\n //store result in cache\n cache.sourceData = this.sourceData;\n //run success callbacks for other fields waiting for this source\n $.each(cache.callbacks, function () { this.call(); }); \n }\n this.doPrepend();\n success.call(this);\n } else {\n error.call(this);\n if(cache) {\n //run error callbacks for other fields waiting for this source\n $.each(cache.err_callbacks, function () { this.call(); }); \n }\n }\n }, this),\n error: $.proxy(function () {\n error.call(this);\n if(cache) {\n cache.loading = false;\n //run error callbacks for other fields\n $.each(cache.err_callbacks, function () { this.call(); }); \n }\n }, this)\n });\n } else { //options as json/array\n this.sourceData = this.makeArray(source);\n \n if($.isArray(this.sourceData)) {\n this.doPrepend();\n success.call(this); \n } else {\n error.call(this);\n }\n }\n },\n\n doPrepend: function () {\n if(this.options.prepend === null || this.options.prepend === undefined) {\n return; \n }\n \n if(!$.isArray(this.prependData)) {\n //run prepend if it is function (once)\n if ($.isFunction(this.options.prepend)) {\n this.options.prepend = this.options.prepend.call(this.options.scope);\n }\n \n //try parse json in single quotes\n this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true);\n \n //convert prepend from string to object\n if (typeof this.options.prepend === 'string') {\n this.options.prepend = {'': this.options.prepend};\n }\n \n this.prependData = this.makeArray(this.options.prepend);\n }\n\n if($.isArray(this.prependData) && $.isArray(this.sourceData)) {\n this.sourceData = this.prependData.concat(this.sourceData);\n }\n },\n\n /*\n renders input list\n */\n renderList: function() {\n // this method should be overwritten in child class\n },\n \n /*\n set element's html by value\n */\n value2htmlFinal: function(value, element) {\n // this method should be overwritten in child class\n }, \n\n /**\n * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}]\n */\n makeArray: function(data) {\n var count, obj, result = [], item, iterateItem;\n if(!data || typeof data === 'string') {\n return null; \n }\n\n if($.isArray(data)) { //array\n /* \n function to iterate inside item of array if item is object.\n Caclulates count of keys in item and store in obj. \n */\n iterateItem = function (k, v) {\n obj = {value: k, text: v};\n if(count++ >= 2) {\n return false;// exit from `each` if item has more than one key.\n }\n };\n \n for(var i = 0; i < data.length; i++) {\n item = data[i]; \n if(typeof item === 'object') {\n count = 0; //count of keys inside item\n $.each(item, iterateItem);\n //case: [{val1: 'text1'}, {val2: 'text2} ...]\n if(count === 1) { \n result.push(obj); \n //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...]\n } else if(count > 1) {\n //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text')\n if(item.children) {\n item.children = this.makeArray(item.children); \n }\n result.push(item);\n }\n } else {\n //case: ['text1', 'text2' ...]\n result.push({value: item, text: item}); \n }\n }\n } else { //case: {val1: 'text1', val2: 'text2, ...}\n $.each(data, function (k, v) {\n result.push({value: k, text: v});\n }); \n }\n return result;\n },\n \n option: function(key, value) {\n this.options[key] = value;\n if(key === 'source') {\n this.sourceData = null;\n }\n if(key === 'prepend') {\n this.prependData = null;\n } \n } \n\n }); \n\n List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {\n /**\n Source data for list. \n If **array** - it should be in format: `[{value: 1, text: \"text1\"}, {value: 2, text: \"text2\"}, ...]` \n For compability, object format is also supported: `{\"1\": \"text1\", \"2\": \"text2\" ...}` but it does not guarantee elements order.\n \n If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option.\n \n If **function**, it should return data in format above (since 1.4.0).\n \n Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). \n `[{text: \"group1\", children: [{value: 1, text: \"text1\"}, {value: 2, text: \"text2\"}]}, ...]` \n\n\t\t\n @property source \n @type string | array | object | function\n @default null\n **/ \n source: null, \n /**\n Data automatically prepended to the beginning of dropdown list.\n \n @property prepend \n @type string | array | object | function\n @default false\n **/ \n prepend: false,\n /**\n Error message when list cannot be loaded (e.g. ajax error)\n \n @property sourceError \n @type string\n @default Error when loading list\n **/ \n sourceError: 'Error when loading list',\n /**\n if true and source is **string url** - results will be cached for fields with the same source. \n Usefull for editable column in grid to prevent extra requests.\n \n @property sourceCache \n @type boolean\n @default true\n @since 1.2.0\n **/ \n sourceCache: true\n });\n\n $.fn.editabletypes.list = List; \n\n}(window.jQuery));\n\r\n/**\nText input\n\n@class text\n@extends abstractinput\n@final\n@example\nawesome\n\n**/\n(function ($) {\n \"use strict\";\n \n var Text = function (options) {\n this.init('text', options, Text.defaults);\n };\n\n $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput);\n\n $.extend(Text.prototype, {\n render: function() {\n this.renderClear();\n this.setClass();\n this.setAttr('placeholder');\n },\n \n activate: function() {\n if(this.$input.is(':visible')) {\n this.$input.focus();\n $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length);\n if(this.toggleClear) {\n this.toggleClear();\n }\n }\n },\n \n //render clear button\n renderClear: function() {\n if (this.options.clear) {\n this.$clear = $('');\n this.$input.after(this.$clear)\n .css('padding-right', 24)\n .keyup($.proxy(function(e) {\n //arrows, enter, tab, etc\n if(~$.inArray(e.keyCode, [40,38,9,13,27])) {\n return;\n } \n\n clearTimeout(this.t);\n var that = this;\n this.t = setTimeout(function() {\n that.toggleClear(e);\n }, 100);\n \n }, this))\n .parent().css('position', 'relative');\n \n this.$clear.click($.proxy(this.clear, this)); \n } \n },\n \n postrender: function() {\n /*\n //now `clear` is positioned via css\n if(this.$clear) {\n //can position clear button only here, when form is shown and height can be calculated\n// var h = this.$input.outerHeight(true) || 20,\n var h = this.$clear.parent().height(),\n delta = (h - this.$clear.height()) / 2;\n \n //this.$clear.css({bottom: delta, right: delta});\n }\n */ \n },\n \n //show / hide clear button\n toggleClear: function(e) {\n if(!this.$clear) {\n return;\n }\n \n var len = this.$input.val().length,\n visible = this.$clear.is(':visible');\n \n if(len && !visible) {\n this.$clear.show();\n } \n \n if(!len && visible) {\n this.$clear.hide();\n } \n },\n \n clear: function() {\n this.$clear.hide();\n this.$input.val('').focus();\n } \n });\n\n Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {\n /**\n @property tpl \n @default \n **/ \n tpl: '',\n /**\n Placeholder attribute of input. Shown when input is empty.\n\n @property placeholder \n @type string\n @default null\n **/ \n placeholder: null,\n \n /**\n Whether to show `clear` button \n \n @property clear \n @type boolean\n @default true \n **/\n clear: true\n });\n\n $.fn.editabletypes.text = Text;\n\n}(window.jQuery));\n\r\n/**\nTextarea input\n\n@class textarea\n@extends abstractinput\n@final\n@example\nawesome comment!\n\n**/\n(function ($) {\n \"use strict\";\n \n var Textarea = function (options) {\n this.init('textarea', options, Textarea.defaults);\n };\n\n $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput);\n\n $.extend(Textarea.prototype, {\n render: function () {\n this.setClass();\n this.setAttr('placeholder');\n this.setAttr('rows'); \n \n //ctrl + enter\n this.$input.keydown(function (e) {\n if (e.ctrlKey && e.which === 13) {\n $(this).closest('form').submit();\n }\n });\n },\n\n value2html: function(value, element) {\n var html = '', lines;\n if(value) {\n lines = value.split(\"\\n\");\n for (var i = 0; i < lines.length; i++) {\n lines[i] = $('
').text(lines[i]).html();\n }\n html = lines.join('
');\n }\n $(element).html(html);\n },\n\n html2value: function(html) {\n if(!html) {\n return '';\n }\n\n var regex = new RegExp(String.fromCharCode(10), 'g');\n var lines = html.split(//i);\n for (var i = 0; i < lines.length; i++) {\n var text = $('
').html(lines[i]).text();\n\n // Remove newline characters (\\n) to avoid them being converted by value2html() method\n // thus adding extra
tags\n text = text.replace(regex, '');\n\n lines[i] = text;\n }\n return lines.join(\"\\n\");\n },\n\n activate: function() {\n $.fn.editabletypes.text.prototype.activate.call(this);\n }\n });\n\n Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {\n /**\n @property tpl\n @default \n **/\n tpl:'',\n /**\n @property inputclass\n @default input-large\n **/\n inputclass: 'input-large',\n /**\n Placeholder attribute of input. Shown when input is empty.\n\n @property placeholder\n @type string\n @default null\n **/\n placeholder: null,\n /**\n Number of rows in textarea\n\n @property rows\n @type integer\n @default 7\n **/ \n rows: 7 \n });\n\n $.fn.editabletypes.textarea = Textarea;\n\n}(window.jQuery));\n\r\n/**\nSelect (dropdown)\n\n@class select\n@extends list\n@final\n@example\n\n\n**/\n(function ($) {\n \"use strict\";\n \n var Select = function (options) {\n this.init('select', options, Select.defaults);\n };\n\n $.fn.editableutils.inherit(Select, $.fn.editabletypes.list);\n\n $.extend(Select.prototype, {\n renderList: function() {\n this.$input.empty();\n\n var fillItems = function($el, data) {\n if($.isArray(data)) {\n for(var i=0; i', {label: data[i].text}), data[i].children)); \n } else {\n $el.append($('