Asankhaya Sharma
commited on
Commit
•
0414e50
1
Parent(s):
c74a45a
add py and js data
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- data/javascript/0.txt +1 -0
- data/javascript/1.txt +1 -0
- data/javascript/10.txt +0 -0
- data/javascript/100.txt +1 -0
- data/javascript/101.txt +1 -0
- data/javascript/102.txt +1 -0
- data/javascript/103.txt +1 -0
- data/javascript/104.txt +1 -0
- data/javascript/105.txt +1 -0
- data/javascript/106.txt +1 -0
- data/javascript/107.txt +1 -0
- data/javascript/108.txt +1 -0
- data/javascript/109.txt +1 -0
- data/javascript/11.txt +1 -0
- data/javascript/110.txt +1 -0
- data/javascript/111.txt +1 -0
- data/javascript/112.txt +1 -0
- data/javascript/113.txt +1 -0
- data/javascript/114.txt +1 -0
- data/javascript/115.txt +1 -0
- data/javascript/116.txt +1 -0
- data/javascript/117.txt +1 -0
- data/javascript/118.txt +1 -0
- data/javascript/119.txt +0 -0
- data/javascript/12.txt +1 -0
- data/javascript/120.txt +1 -0
- data/javascript/121.txt +1 -0
- data/javascript/122.txt +1 -0
- data/javascript/123.txt +1 -0
- data/javascript/124.txt +1 -0
- data/javascript/125.txt +1 -0
- data/javascript/126.txt +1 -0
- data/javascript/127.txt +1 -0
- data/javascript/128.txt +1 -0
- data/javascript/129.txt +1 -0
- data/javascript/13.txt +0 -0
- data/javascript/130.txt +1 -0
- data/javascript/131.txt +1 -0
- data/javascript/132.txt +1 -0
- data/javascript/133.txt +1 -0
- data/javascript/134.txt +1 -0
- data/javascript/135.txt +1 -0
- data/javascript/136.txt +1 -0
- data/javascript/137.txt +1 -0
- data/javascript/138.txt +1 -0
- data/javascript/139.txt +1 -0
- data/javascript/14.txt +1 -0
- data/javascript/140.txt +1 -0
- data/javascript/141.txt +1 -0
- data/javascript/142.txt +1 -0
data/javascript/0.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
(function (global) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var setImmediate; function addFromSetImmediateArguments(args) { tasksByHandle[nextHandle] = partiallyApplied.apply(undefined, args); return nextHandle++; } // This function accepts the same arguments as setImmediate, but // returns a function that requires no arguments. function partiallyApplied(handler, timeout) { var args = [].slice.call(arguments, 1); return function() { if (typeof handler === "function") { handler.apply(undefined, args); } else { (new Function("" + handler))(); } }; } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(partiallyApplied(runIfPresent, handle), 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { task(); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function clearImmediate(handle) { delete tasksByHandle[handle]; } function installNextTickImplementation() { setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); process.nextTick(partiallyApplied(runIfPresent, handle)); return handle; }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; // BUG: CWE-345: Insufficient Verification of Data Authenticity// global.postMessage("", "*");// FIXED: global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); global.postMessage(messagePrefix + handle, "*"); return handle; }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); channel.port2.postMessage(handle); return handle; }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); return handle; }; } function installSetTimeoutImplementation() { setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); setTimeout(partiallyApplied(runIfPresent, handle), 0); return handle; }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate;}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
|
data/javascript/1.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
(function (global) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var setImmediate; function addFromSetImmediateArguments(args) { tasksByHandle[nextHandle] = partiallyApplied.apply(undefined, args); return nextHandle++; } // This function accepts the same arguments as setImmediate, but // returns a function that requires no arguments. function partiallyApplied(handler, timeout) { var args = [].slice.call(arguments, 1); return function() { if (typeof handler === "function") { handler.apply(undefined, args); } else { (new Function("" + handler))(); } }; } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(partiallyApplied(runIfPresent, handle), 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { task(); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function clearImmediate(handle) { delete tasksByHandle[handle]; } function installNextTickImplementation() { setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); process.nextTick(partiallyApplied(runIfPresent, handle)); return handle; }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); // BUG: CWE-345: Insufficient Verification of Data Authenticity// global.postMessage(messagePrefix + handle, "*");// FIXED: return handle; }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); channel.port2.postMessage(handle); return handle; }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); return handle; }; } function installSetTimeoutImplementation() { setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); setTimeout(partiallyApplied(runIfPresent, handle), 0); return handle; }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate;}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
|
data/javascript/10.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data/javascript/100.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import React from 'react'import * as ReactDOM from 'react-dom'import { formatDate } from 'front/date'import { IssueIcon, EditArticleIcon, NewArticleIcon, SeeIcon, SignupOrLogin, TimeIcon, TopicIcon } from 'front'import Comment from 'front/Comment'import CommentInput from 'front/CommentInput'import LikeArticleButton from 'front/LikeArticleButton'import { CommentType } from 'front/types/CommentType'import ArticleList from 'front/ArticleList'import routes from 'front/routes'import { cant } from 'front/cant'import CustomLink from 'front/CustomLink'// This also worked. But using the packaged one reduces the need to replicate// or factor out the webpack setup of the ourbigbook package.//import { ourbigbook_runtime } from 'ourbigbook/ourbigbook_runtime.js';import { ourbigbook_runtime } from 'ourbigbook/dist/ourbigbook_runtime.js'const Article = ({ article, articlesInSamePage, comments, commentsCount=0, commentCountByLoggedInUser=undefined, isIssue=false, issueArticle=undefined, issuesCount, latestIssues, loggedInUser, topIssues,}) => { const [curComments, setComments] = React.useState(comments) let seeAllCreateNew if (!isIssue) { seeAllCreateNew = <> {latestIssues.length > 0 && <> <CustomLink href={routes.issues(article.slug)}><SeeIcon /> See all ({ issuesCount })</CustomLink>{' '} </> } {loggedInUser ? <CustomLink href={routes.issueNew(article.slug)}><NewArticleIcon /> New discussion</CustomLink> : <SignupOrLogin to="create discussions"/> } </> } const articlesInSamePageMap = {} if (!isIssue) { for (const article of articlesInSamePage) { articlesInSamePageMap[article.topicId] = article } } const canEdit = isIssue ? !cant.editIssue(loggedInUser, article) : !cant.editArticle(loggedInUser, article) const renderRefCallback = React.useCallback( (elem) => { if (elem) { for (const h of elem.querySelectorAll('.h')) { const id = h.id const web = h.querySelector('.web') const toplevel = web.classList.contains('top') // TODO rename to article later on. let curArticle, isIndex if (isIssue) { if (!toplevel) { continue } curArticle = article } else if ( // Happens on user index page. id === '' ) { curArticle = article isIndex = true } else { curArticle = articlesInSamePageMap[id] if (!curArticle) { // Possible for Include headers. Maybe one day we will cover them. continue } } let mySlug if (loggedInUser) { mySlug = `${loggedInUser.username}/${curArticle.topicId}` } ReactDOM.render( <> <LikeArticleButton {...{ article: curArticle, loggedInUser, isIssue: false, showText: toplevel, }} /> {!isIssue && <> {' '} {!isIndex && <a className="by-others btn" href={routes.topic(id)} title="Articles by others on the same topic"> <TopicIcon title={false} /> {curArticle.topicCount}{toplevel ? <> By Others<span className="mobile-hide"> On Same Topic</span></> : ''} </a> } {' '} <a className="issues btn" href={routes.issues(curArticle.slug)} title="Discussions"> <IssueIcon title={false} /> {isIndex ? issuesCount : curArticle.issueCount}{toplevel ? ' Discussions' : ''}</a> </> } {toplevel && <> {' '} <span title="Last updated"> <TimeIcon />{' '} <span className="article-dates"> {formatDate(article.updatedAt)} </span> </span> </> } {false && article.createdAt !== article.updatedAt && <> <span className="mobile-hide"> {' Updated: '} </span> <span className="article-dates"> {formatDate(article.updatedAt)} </span> </> } {canEdit ? <> {' '} <span> {false && <>TODO: convert this a and all other injected links to Link. https://github.com/cirosantilli/ourbigbook/issues/274</> } <a href={isIssue ? routes.issueEdit(issueArticle.slug, curArticle.number) : routes.articleEdit(curArticle.slug)} className="btn edit" > <EditArticleIcon />{toplevel && <> <span className="shortcut">E</span>dit</>} </a> </span> </> : <> {!isIssue && <> {curArticle.hasSameTopic ? <> {article.slug !== mySlug && <> {' '} <a href={routes.article(mySlug)} className="btn see" title="See my version of this topic"> {' '}<SeeIcon title={false}/>{toplevel ? ' See My Version' : ''}{' '} </a> </> } </> : <> {' '} <a href={routes.articleNew({ title: curArticle.titleSource })} className="btn new" title="Create my version of this topic"> {' '}<NewArticleIcon title={false}/>{toplevel ? ' Create my own version' : ''}{' '} </a> </> } </> } </> } </>, web ); } ourbigbook_runtime(elem); } }, [] ); return <> <div // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// dangerouslySetInnerHTML={{ __html: article.render }}// FIXED: className="ourbigbook" ref={renderRefCallback} /> <div className="comments content-not-ourbigbook"> {isIssue ? <> <h2><IssueIcon /> Comments ({ commentsCount })</h2> <div className="comment-form-holder"> <CommentInput {...{ comments, commentCountByLoggedInUser, issueNumber: article.number, loggedInUser, setComments, }}/> </div> {curComments?.map((comment: CommentType) => <Comment {...{ comment, comments, id: comment.id, key: comment.id, loggedInUser, setComments, }} /> )} </> : <> <h2><CustomLink href={routes.issues(article.slug)}><IssueIcon /> Discussion ({ issuesCount })</CustomLink></h2> { seeAllCreateNew } { latestIssues.length > 0 ? <> <h3>Latest threads</h3> <ArticleList {...{ articles: latestIssues, articlesCount: issuesCount, comments, commentsCount, issueArticle: article, itemType: 'discussion', loggedInUser, page: 0, showAuthor: true, what: 'discussion', }}/> <h3>Top threads</h3> <ArticleList {...{ articles: topIssues, articlesCount: issuesCount, comments, commentsCount, issueArticle: article, itemType: 'discussion', loggedInUser, page: 0, showAuthor: true, what: 'issues', }}/> { seeAllCreateNew } </> : <p>There are no discussions about this article yet.</p> } </> } </div> </>}export default Article
|
data/javascript/101.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import { useRouter } from 'next/router'import React from 'react'import CustomLink from 'front/CustomLink'import LikeArticleButton from 'front/LikeArticleButton'import LoadingSpinner from 'front/LoadingSpinner'import Pagination, { PaginationPropsUrlFunc } from 'front/Pagination'import UserLinkWithImage from 'front/UserLinkWithImage'import { AppContext, ArticleIcon, TimeIcon, UserIcon } from 'front'import { articleLimit } from 'front/config'import { formatDate } from 'front/date'import routes from 'front/routes'import { ArticleType } from 'front/types/ArticleType'import { CommentType } from 'front/types/CommentType'import { IssueType } from 'front/types/IssueType'import { TopicType } from 'front/types/TopicType'import { UserType } from 'front/types/UserType'export type ArticleListProps = { articles: (ArticleType & IssueType & TopicType)[]; articlesCount: number; comments?: Comment[]; commentsCount?: number; followed?: boolean; issueArticle?: ArticleType; itemType?: string; loggedInUser?: UserType, page: number; paginationUrlFunc?: PaginationPropsUrlFunc; showAuthor: boolean; what?: string;}const ArticleList = ({ articles, articlesCount, comments, commentsCount, followed=false, itemType='article', issueArticle, loggedInUser, page, paginationUrlFunc, showAuthor, what='all',}: ArticleListProps) => { const router = useRouter(); const { asPath, pathname, query } = router; const { like, follow, tag, uid } = query; let isIssue switch (itemType) { case 'discussion': isIssue = true break case 'topic': showAuthor = false break } if (articles.length === 0) { let message; let voice; if (loggedInUser?.username === uid) { voice = "You have not" } else { voice = "This user has not" } switch (what) { case 'likes': message = `${voice} liked any articles yet.` break case 'user-articles': message = `${voice} published any articles yet.` break case 'all': if (followed) { message = `Follow some users to see their posts here.` } else { message = (<> There are no {isIssue ? 'discussions' : 'articles'} on this {isIssue ? 'article' : 'website'} yet. Why don't you <a href={isIssue ? routes.issueNew(issueArticle.slug) : routes.articleNew()}>create a new one</a>? </>) } break default: message = 'There are no articles matching this search' } return <div className="article-preview"> {message} </div>; } return ( <div className="list-nav-container"> <div className="list-container"> <table className="list"> <thead> <tr> {itemType === 'topic' ? <th className="shrink right">Articles</th> : <th className="shrink center">Score</th> } <th className="expand"><ArticleIcon /> Title</th> {showAuthor && <th className="shrink"><UserIcon /> Author</th> } {isIssue && <th className="shrink"> # </th> } <th className="shrink"><TimeIcon /> Created</th> <th className="shrink"><TimeIcon /> Updated</th> </tr> </thead> <tbody> {articles?.map((article, i) => ( <tr key={itemType === 'discussion' ? article.number : itemType === 'article' ? article.slug : article.topicId}> {itemType === 'topic' ? <td className="shrink right bold"> {article.articleCount} </td> : <td className="shrink center"> <LikeArticleButton {...{ article, isIssue, issueArticle, loggedInUser, showText: false, }} /> </td> } <td className="expand title"> <CustomLink href={itemType === 'discussion' ? routes.issue(issueArticle.slug, article.number) : itemType === 'article' ? routes.article(article.slug) : routes.topic(article.topicId, { sort: 'score' }) } > <div className="comment-body ourbigbook-title" // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// dangerouslySetInnerHTML={{ __html: article.titleRender }}// FIXED: /> </CustomLink> </td> {showAuthor && <td className="shrink"> <UserLinkWithImage showUsername={false} user={article.author} /> </td> } {isIssue && <td className="shrink bold"> <CustomLink href={isIssue ? routes.issue(issueArticle.slug, article.number) : routes.article(article.slug)} > #{article.number} </CustomLink> </td> } <td className="shrink">{formatDate(article.createdAt)}</td> <td className="shrink">{formatDate(article.updatedAt)}</td> </tr> ))} </tbody> </table> </div> {paginationUrlFunc && <Pagination {...{ currentPage: page, what: isIssue ? 'threads' : 'articles', itemsCount: articlesCount, itemsPerPage: articleLimit, urlFunc: paginationUrlFunc, }} /> } </div> );};export default ArticleList;
|
data/javascript/102.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import React from 'react'import { useRouter } from 'next/router'import Maybe from 'front/Maybe'import { webApi } from 'front/api'import config from 'front/config'import CustomLink from 'front/CustomLink'import { cant } from 'front/cant'import { formatDate } from 'front/date'import UserLinkWithImage from 'front/UserLinkWithImage'const Comment = ({ comment, comments, id, loggedInUser, setComments }) => { const router = useRouter(); const { query: { number: issueNumber, slug }, } = router; const handleDelete = async (commentId) => { await webApi.commentDelete((slug as string[]).join('/'), issueNumber, comment.number) setComments(comments => comments.filter(comment => comment.id !== id)) }; const targetId = `comment${config.idSep}${comment.number}` return ( <div className="comment" id={targetId}> <div className="comment-header"> <CustomLink className="number" href={`#${targetId}`}>#{comment.number}</CustomLink> {' by '} <UserLinkWithImage user={comment.author} showUsernameMobile={false} /> {' on '} {formatDate(comment.createdAt)} {' '} <Maybe test={!cant.deleteComment(loggedInUser, comment)}> <button className="btn" onClick={() => handleDelete(comment.id)} > <i className="ion-trash-a" /> Delete Comment </button> </Maybe> </div> <div className="comment-body ourbigbook" // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// dangerouslySetInnerHTML={{ __html: comment.render }}// FIXED: /> </div> );};export default Comment;
|
data/javascript/103.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import Head from 'next/head'import React from 'react'import { useRouter } from 'next/router'import { AppContext, ArticleIcon, NewArticleIcon, TopicIcon, slugFromArray} from 'front'import ArticleList from 'front/ArticleList'import CustomLink from 'front/CustomLink'import LoadingSpinner from 'front/LoadingSpinner'import LogoutButton from 'front/LogoutButton'import Maybe from 'front/Maybe'import routes from 'front/routes'import { ArticleType } from 'front/types/ArticleType'import { IssueType } from 'front/types/IssueType'import { TopicType } from 'front/types/TopicType'import { UserType } from 'front/types/UserType'export interface TopicPageProps { articles: (ArticleType & IssueType & TopicType)[]; articlesCount: number; loggedInUser?: UserType; order: string; topic: TopicType; page: number; what: string;}export const TopicPage = ({ articles, articlesCount, loggedInUser, order, page, topic, what}: TopicPageProps) => { const router = useRouter(); const topicId = slugFromArray(router.query.id) const paginationUrlFunc = (page) => routes.topic(topicId, { page, sort: order }) const { setTitle } = React.useContext(AppContext) if (topic) { React.useEffect(() => { setTitle(topic.titleSource) }, [topic.titleSource]) } if (router.isFallback) { return <LoadingSpinner />; } return ( <div className="topic-page content-not-ourbigbook"> {topic ? <> // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// <h1><TopicIcon /> <span className="ourbigbook-title" dangerouslySetInnerHTML={{ __html: topic.titleRender }} /></h1>// FIXED: <div className="tab-list"> <CustomLink className={`tab-item${order === 'score' ? ' active' : ''}`} href={routes.topic(topicId, { sort: 'score' })} > <ArticleIcon /> Top Articles </CustomLink> <CustomLink className={`tab-item${order === 'createdAt' ? ' active' : ''}`} href={routes.topic(topicId, { sort: 'created' })} > Latest Articles </CustomLink> <CustomLink className={`tab-item`} href={routes.articleNew({ title: topic.titleSource })} > <NewArticleIcon /> New Article in Topic </CustomLink> </div> <ArticleList {...{ articles, articlesCount, loggedInUser, page, paginationUrlFunc, showAuthor: true, what, }}/> </> : <> <h1><TopicIcon /> Topic does not exist: {topicId}</h1> {false && <div>TODO: add a link for user to create an article with that topic.</div> } </> } </div> )}export default TopicPage
|
data/javascript/104.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import React from 'react'import Router from 'next/router'import { mutate } from 'swr'import ourbigbook from 'ourbigbook';import { webApi } from 'front/api'import { AUTH_COOKIE_NAME } from 'front/js'import CustomLink from 'front/CustomLink'import routes from 'front/routes'import { ArticleType } from 'front/types/ArticleType'import { IssueType } from 'front/types/IssueType'export const AUTH_LOCAL_STORAGE_NAME = 'user'export const LOGIN_ACTION = 'Sign in'export const REGISTER_ACTION = 'Sign up'export function capitalize(s) { return s[0].toUpperCase() + s.slice(1)}export function decapitalize(s) { return s[0].toLowerCase() + s.slice(1)}export function ArticleBy( { article, newTab=false }: { article?: ArticleType }) { const inner = <> "<span className="comment-body ourbigbook-title" // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// dangerouslySetInnerHTML={{ __html: article.titleRender }}// FIXED: />" by { article.author.displayName } </> const href = routes.article(article.slug) if (newTab) { return <a href={href} target="_blank">{inner}</a> } else { return <CustomLink href={href}>{inner}</CustomLink> }}export function IssueBy( { article }: { article?: ArticleType }) { return <CustomLink href={routes.article(article.slug)}> "<span className="comment-body ourbigbook-title" dangerouslySetInnerHTML={{ __html: article.titleRender }} />" by { article.author.displayName } </CustomLink>}export function DiscussionAbout( { article, issue }: { article?: ArticleType; issue?: IssueType }) { const inner = <> <IssueIcon />{' '} Discussion{issue ? ` #${issue.number}` : ''}:{' '} <ArticleBy {...{article, issue}} /> </> if (issue) { return <div className="h1">{ inner }</div> } else { return <h1>{ inner }</h1> }}// Icons.export function Icon(cls, title, opts) { const showTitle = opts.title === undefined ? true : opts.title return <i className={cls} title={showTitle ? title : undefined } />}export function ArticleIcon(opts) { return Icon("ion-ios-book", "Article", opts)}export function CancelIcon(opts) { return Icon("ion-close", "Cancel", opts)}export function EditArticleIcon(opts) { return Icon("ion-edit", "Edit", opts)}export function ErrorIcon(opts) { return Icon("ion-close", "Edit", opts)}export function HelpIcon(opts) { return Icon("ion-help-circled", "Help", opts)}export function IssueIcon(opts) { return Icon("ion-ios-chatbubble", "Discussion", opts)}export function NewArticleIcon(opts) { return Icon("ion-plus", "New", opts)}export function SeeIcon(opts) { return Icon("ion-eye", "View", opts)}export function TimeIcon(opts) { return Icon("ion-android-time", undefined, opts)}export function TopicIcon(opts) { return Icon("ion-ios-people", "Topic", opts)}export function UserIcon(opts) { return Icon("ion-ios-person", "User", opts)}export function SignupOrLogin( { to }: { to: string }) { return <> <CustomLink href={routes.userNew()}> {REGISTER_ACTION} </CustomLink> {' '}or{' '} <CustomLink href={routes.userLogin()}> {decapitalize(LOGIN_ACTION)} </CustomLink> {' '}{to}. </>}export function disableButton(btn, msg) { btn.setAttribute('disabled', '') btn.setAttribute('title', msg) btn.classList.add('disabled')}export function enableButton(btn, msgGiven) { btn.removeAttribute('disabled') if (msgGiven) { btn.removeAttribute('title') } btn.classList.remove('disabled')}export function slugFromArray(arr, { username }: { username?: boolean } = {}) { if (username === undefined) { username = true } const start = username ? 0 : 1 return arr.slice(start).join(ourbigbook.Macro.HEADER_SCOPE_SEPARATOR)}export function slugFromRouter(router, opts={}) { let arr = router.query.slug if (!arr) { return router.query.uid } return slugFromArray(arr, opts)}export const AppContext = React.createContext<{ title: string setTitle: React.Dispatch<any> | undefined}>({ title: '', setTitle: undefined,});// Global state.export const AppContextProvider = ({ children }) => { const [title, setTitle] = React.useState() return <AppContext.Provider value={{ title, setTitle, }}> {children} </AppContext.Provider>};export function useCtrlEnterSubmit(handleSubmit) { React.useEffect(() => { function ctrlEnterListener(e) { if (e.code === 'Enter' && e.ctrlKey) { handleSubmit(e) } } document.addEventListener('keydown', ctrlEnterListener); return () => { document.removeEventListener('keydown', ctrlEnterListener); }; }, [handleSubmit]);}export function useEEdit(canEdit, slug) { React.useEffect(() => { function listener(e) { if (e.code === 'KeyE') { if (canEdit) { Router.push(routes.articleEdit(slug)) } } } if (slug !== undefined) { document.addEventListener('keydown', listener); return () => { document.removeEventListener('keydown', listener); } } }, [canEdit, slug]);}// https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie/38699214#38699214export function setCookie(name, value, days?: number, path = '/') { let delta if (days === undefined) { delta = Number.MAX_SAFE_INTEGER } else { delta = days * 864e5 } const expires = new Date(Date.now() + delta).toUTCString() document.cookie = `${name}=${encodeURIComponent( value )};expires=${expires};path=${path}`}export function setCookies(cookieDict, days, path = '/') { for (let key in cookieDict) { setCookie(key, cookieDict[key], days, path) }}export function getCookie(name) { return getCookieFromString(document.cookie, name)}export function getCookieFromReq(req, name) { const cookie = req.headers.cookie if (cookie) { return getCookieFromString(cookie, name) } else { return null }}export function getCookieFromString(s, name) { return getCookiesFromString(s)[name]}// https://stackoverflow.com/questions/5047346/converting-strings-like-document-cookie-to-objectsexport function getCookiesFromString(s) { return s.split('; ').reduce((prev, current) => { const [name, ...value] = current.split('=') prev[name] = value.join('=') return prev }, {})}export function deleteCookie(name, path = '/') { setCookie(name, '', -1, path)}export async function setupUserLocalStorage(user, setErrors?) { // We fetch from /profiles/:username again because the return from /users/login above // does not contain the image placeholder. const { data: userData, status: userStatus } = await webApi.user( user.username ) user.effectiveImage = userData.effectiveImage window.localStorage.setItem( AUTH_LOCAL_STORAGE_NAME, JSON.stringify(user) ); setCookie(AUTH_COOKIE_NAME, user.token) mutate(AUTH_COOKIE_NAME, user.token) mutate(AUTH_LOCAL_STORAGE_NAME, user);}
|
data/javascript/105.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import React from 'react'import Router from 'next/router'import { mutate } from 'swr'import ourbigbook from 'ourbigbook';import { webApi } from 'front/api'import { AUTH_COOKIE_NAME } from 'front/js'import CustomLink from 'front/CustomLink'import routes from 'front/routes'import { ArticleType } from 'front/types/ArticleType'import { IssueType } from 'front/types/IssueType'export const AUTH_LOCAL_STORAGE_NAME = 'user'export const LOGIN_ACTION = 'Sign in'export const REGISTER_ACTION = 'Sign up'export function capitalize(s) { return s[0].toUpperCase() + s.slice(1)}export function decapitalize(s) { return s[0].toLowerCase() + s.slice(1)}export function ArticleBy( { article, newTab=false }: { article?: ArticleType }) { const inner = <> "<span className="comment-body ourbigbook-title" // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// dangerouslySetInnerHTML={{ __html: article.titleRender }}// FIXED: />" by { article.author.displayName } </> const href = routes.article(article.slug) if (newTab) { return <a href={href} target="_blank">{inner}</a> } else { return <CustomLink href={href}>{inner}</CustomLink> }}export function IssueBy( { article }: { article?: ArticleType }) { return <CustomLink href={routes.article(article.slug)}> "<span className="comment-body ourbigbook-title" dangerouslySetInnerHTML={{ __html: article.titleRender }} />" by { article.author.displayName } </CustomLink>}export function DiscussionAbout( { article, issue }: { article?: ArticleType; issue?: IssueType }) { const inner = <> <IssueIcon />{' '} Discussion{issue ? ` #${issue.number}` : ''}:{' '} <ArticleBy {...{article, issue}} /> </> if (issue) { return <div className="h1">{ inner }</div> } else { return <h1>{ inner }</h1> }}// Icons.export function Icon(cls, title, opts) { const showTitle = opts.title === undefined ? true : opts.title return <i className={cls} title={showTitle ? title : undefined } />}export function ArticleIcon(opts) { return Icon("ion-ios-book", "Article", opts)}export function CancelIcon(opts) { return Icon("ion-close", "Cancel", opts)}export function EditArticleIcon(opts) { return Icon("ion-edit", "Edit", opts)}export function ErrorIcon(opts) { return Icon("ion-close", "Edit", opts)}export function HelpIcon(opts) { return Icon("ion-help-circled", "Help", opts)}export function IssueIcon(opts) { return Icon("ion-ios-chatbubble", "Discussion", opts)}export function NewArticleIcon(opts) { return Icon("ion-plus", "New", opts)}export function SeeIcon(opts) { return Icon("ion-eye", "View", opts)}export function TimeIcon(opts) { return Icon("ion-android-time", undefined, opts)}export function TopicIcon(opts) { return Icon("ion-ios-people", "Topic", opts)}export function UserIcon(opts) { return Icon("ion-ios-person", "User", opts)}export function SignupOrLogin( { to }: { to: string }) { return <> <CustomLink href={routes.userNew()}> {REGISTER_ACTION} </CustomLink> {' '}or{' '} <CustomLink href={routes.userLogin()}> {decapitalize(LOGIN_ACTION)} </CustomLink> {' '}{to}. </>}export function disableButton(btn, msg) { btn.setAttribute('disabled', '') btn.setAttribute('title', msg) btn.classList.add('disabled')}export function enableButton(btn, msgGiven) { btn.removeAttribute('disabled') if (msgGiven) { btn.removeAttribute('title') } btn.classList.remove('disabled')}export function slugFromArray(arr, { username }: { username?: boolean } = {}) { if (username === undefined) { username = true } const start = username ? 0 : 1 return arr.slice(start).join(ourbigbook.Macro.HEADER_SCOPE_SEPARATOR)}export function slugFromRouter(router, opts={}) { let arr = router.query.slug if (!arr) { return router.query.uid } return slugFromArray(arr, opts)}export const AppContext = React.createContext<{ title: string setTitle: React.Dispatch<any> | undefined}>({ title: '', setTitle: undefined,});// Global state.export const AppContextProvider = ({ children }) => { const [title, setTitle] = React.useState() return <AppContext.Provider value={{ title, setTitle, }}> {children} </AppContext.Provider>};export function useCtrlEnterSubmit(handleSubmit) { React.useEffect(() => { function ctrlEnterListener(e) { if (e.code === 'Enter' && e.ctrlKey) { handleSubmit(e) } } document.addEventListener('keydown', ctrlEnterListener); return () => { document.removeEventListener('keydown', ctrlEnterListener); }; }, [handleSubmit]);}export function useEEdit(canEdit, slug) { React.useEffect(() => { function listener(e) { if (e.code === 'KeyE') { if (canEdit) { Router.push(routes.articleEdit(slug)) } } } if (slug !== undefined) { document.addEventListener('keydown', listener); return () => { document.removeEventListener('keydown', listener); } } }, [canEdit, slug]);}// https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie/38699214#38699214export function setCookie(name, value, days?: number, path = '/') { let delta if (days === undefined) { delta = Number.MAX_SAFE_INTEGER } else { delta = days * 864e5 } const expires = new Date(Date.now() + delta).toUTCString() document.cookie = `${name}=${encodeURIComponent( value )};expires=${expires};path=${path}`}export function setCookies(cookieDict, days, path = '/') { for (let key in cookieDict) { setCookie(key, cookieDict[key], days, path) }}export function getCookie(name) { return getCookieFromString(document.cookie, name)}export function getCookieFromReq(req, name) { const cookie = req.headers.cookie if (cookie) { return getCookieFromString(cookie, name) } else { return null }}export function getCookieFromString(s, name) { return getCookiesFromString(s)[name]}// https://stackoverflow.com/questions/5047346/converting-strings-like-document-cookie-to-objectsexport function getCookiesFromString(s) { return s.split('; ').reduce((prev, current) => { const [name, ...value] = current.split('=') prev[name] = value.join('=') return prev }, {})}export function deleteCookie(name, path = '/') { setCookie(name, '', -1, path)}export async function setupUserLocalStorage(user, setErrors?) { // We fetch from /profiles/:username again because the return from /users/login above // does not contain the image placeholder. const { data: userData, status: userStatus } = await webApi.user( user.username ) user.effectiveImage = userData.effectiveImage window.localStorage.setItem( AUTH_LOCAL_STORAGE_NAME, JSON.stringify(user) ); setCookie(AUTH_COOKIE_NAME, user.token) mutate(AUTH_COOKIE_NAME, user.token) mutate(AUTH_LOCAL_STORAGE_NAME, user);}
|
data/javascript/106.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-errorError.stackTraceLimit = Infinity;const bodyParser = require('body-parser')const cors = require('cors')const express = require('express')const http = require('http')const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');const methods = require('methods')const morgan = require('morgan')const next = require('next')const passport = require('passport')const passport_local = require('passport-local');const path = require('path')const session = require('express-session')const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')const api = require('./api')const apilib = require('./api/lib')const models = require('./models')const config = require('./front/config')async function start(port, startNext, cb) { const app = express() let nextApp let nextHandle if (startNext) { nextApp = next({ dev: !config.isProductionNext }) nextHandle = nextApp.getRequestHandler() } const sequelize = models.getSequelize(__dirname) // https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https // req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links. app.enable('trust proxy') // Enforce HTTPS. // https://github.com/cirosantilli/ourbigbook/issues/258 app.use(function (req, res, next) { if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') { res.redirect(301, `https://${req.hostname}${req.url}`); return; } next() }) app.set('sequelize', sequelize) passport.use( new passport_local.Strategy( { usernameField: 'user[username]', passwordField: 'user[password]' }, async function(usernameOrEmail, password, done) { let field if (usernameOrEmail.indexOf('@') === -1) { field = 'username' } else { field = 'email' } const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } }) if (!user || !sequelize.models.User.validPassword(user, password)) { return done(null, false, { errors: { 'username or password': 'is invalid' } }) } return done(null, user) } ) ) app.use(cors()) // Normal express config defaults if (config.verbose) { // https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730 app.use(morgan('combined')) } app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json({ // Happens due to our huge input files! // https://stackoverflow.com/questions/19917401/error-request-entity-too-large limit: '16mb' })) app.use(require('method-override')()) // Next handles anythiung outside of /api. app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) { // We pass the sequelize that we have already created and connected to the database // so that the Next.js backend can just use that connection. This is in particular mandatory // if we wish to use SQLite in-memory database, because there is no way to make two separate // connections to the same in-memory database. In memory databases are used by the test system. req.sequelize = sequelize return nextHandle(req, res); }); // BUG: CWE-522: Insufficiently Protected Credentials// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))// FIXED: // Handle API routes. { config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex')) const router = express.Router() router.use(config.apiPath, api) app.use(router) } // 404 handler. app.use(function (req, res, next) { res.status(404).send('error: 404 Not Found ' + req.path) }) // Error handlers app.use(function(err, req, res, next) { // Automatiaclly handle Sequelize validation errors. if (err instanceof sequelize.Sequelize.ValidationError) { if (!config.isProduction && !config.isTest) { // The fuller errors can be helpful during development. console.error(err); } const errors = {} for (let errItem of err.errors) { let errorsForColumn = errors[errItem.path] if (errorsForColumn === undefined) { errorsForColumn = [] errors[errItem.path] = errorsForColumn } errorsForColumn.push(errItem.message) } return res.status(422).json({ errors }) } else if (err instanceof apilib.ValidationError) { return res.status(err.status).json({ errors: err.errors, }) } else if (err instanceof UnauthorizedError) { return res.status(err.status).json({ errors: err.message, }) } return next(err) }) if (startNext) { await nextApp.prepare() } await sequelize.authenticate() // Just a convenience DB create so we don't have to force new users to do it manually. await models.sync(sequelize) return new Promise((resolve, reject) => { const server = app.listen(port, async function () { try { cb && (await cb(server, sequelize)) } catch (e) { reject(e) this.close() throw e } }) server.on('close', async function () { if (startNext) { await nextApp.close() } await sequelize.close() resolve() }) })}if (require.main === module) { start(config.port, true, (server) => { console.log('Listening on: http://localhost:' + server.address().port) })}module.exports = { start }
|
data/javascript/107.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-errorError.stackTraceLimit = Infinity;const bodyParser = require('body-parser')const cors = require('cors')const express = require('express')const http = require('http')const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');const methods = require('methods')const morgan = require('morgan')const next = require('next')const passport = require('passport')const passport_local = require('passport-local');const path = require('path')const session = require('express-session')const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')const api = require('./api')const apilib = require('./api/lib')const models = require('./models')const config = require('./front/config')async function start(port, startNext, cb) { const app = express() let nextApp let nextHandle if (startNext) { nextApp = next({ dev: !config.isProductionNext }) nextHandle = nextApp.getRequestHandler() } const sequelize = models.getSequelize(__dirname) // https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https // req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links. app.enable('trust proxy') // Enforce HTTPS. // https://github.com/cirosantilli/ourbigbook/issues/258 app.use(function (req, res, next) { if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') { res.redirect(301, `https://${req.hostname}${req.url}`); return; } next() }) app.set('sequelize', sequelize) passport.use( new passport_local.Strategy( { usernameField: 'user[username]', passwordField: 'user[password]' }, async function(usernameOrEmail, password, done) { let field if (usernameOrEmail.indexOf('@') === -1) { field = 'username' } else { field = 'email' } const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } }) if (!user || !sequelize.models.User.validPassword(user, password)) { return done(null, false, { errors: { 'username or password': 'is invalid' } }) } return done(null, user) } ) ) app.use(cors()) // Normal express config defaults if (config.verbose) { // https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730 app.use(morgan('combined')) } app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json({ // Happens due to our huge input files! // https://stackoverflow.com/questions/19917401/error-request-entity-too-large limit: '16mb' })) app.use(require('method-override')()) // Next handles anythiung outside of /api. app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) { // We pass the sequelize that we have already created and connected to the database // so that the Next.js backend can just use that connection. This is in particular mandatory // if we wish to use SQLite in-memory database, because there is no way to make two separate // connections to the same in-memory database. In memory databases are used by the test system. req.sequelize = sequelize return nextHandle(req, res); }); // BUG: CWE-522: Insufficiently Protected Credentials// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))// FIXED: // Handle API routes. { config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex')) const router = express.Router() router.use(config.apiPath, api) app.use(router) } // 404 handler. app.use(function (req, res, next) { res.status(404).send('error: 404 Not Found ' + req.path) }) // Error handlers app.use(function(err, req, res, next) { // Automatiaclly handle Sequelize validation errors. if (err instanceof sequelize.Sequelize.ValidationError) { if (!config.isProduction && !config.isTest) { // The fuller errors can be helpful during development. console.error(err); } const errors = {} for (let errItem of err.errors) { let errorsForColumn = errors[errItem.path] if (errorsForColumn === undefined) { errorsForColumn = [] errors[errItem.path] = errorsForColumn } errorsForColumn.push(errItem.message) } return res.status(422).json({ errors }) } else if (err instanceof apilib.ValidationError) { return res.status(err.status).json({ errors: err.errors, }) } else if (err instanceof UnauthorizedError) { return res.status(err.status).json({ errors: err.message, }) } return next(err) }) if (startNext) { await nextApp.prepare() } await sequelize.authenticate() // Just a convenience DB create so we don't have to force new users to do it manually. await models.sync(sequelize) return new Promise((resolve, reject) => { const server = app.listen(port, async function () { try { cb && (await cb(server, sequelize)) } catch (e) { reject(e) this.close() throw e } }) server.on('close', async function () { if (startNext) { await nextApp.close() } await sequelize.close() resolve() }) })}if (require.main === module) { start(config.port, true, (server) => { console.log('Listening on: http://localhost:' + server.address().port) })}module.exports = { start }
|
data/javascript/108.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-errorError.stackTraceLimit = Infinity;const bodyParser = require('body-parser')const cors = require('cors')const express = require('express')const http = require('http')const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');const methods = require('methods')const morgan = require('morgan')const next = require('next')const passport = require('passport')const passport_local = require('passport-local');const path = require('path')const session = require('express-session')const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')const api = require('./api')const apilib = require('./api/lib')const models = require('./models')const config = require('./front/config')async function start(port, startNext, cb) { const app = express() let nextApp let nextHandle if (startNext) { nextApp = next({ dev: !config.isProductionNext }) nextHandle = nextApp.getRequestHandler() } const sequelize = models.getSequelize(__dirname) // https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https // req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links. app.enable('trust proxy') // Enforce HTTPS. // https://github.com/cirosantilli/ourbigbook/issues/258 app.use(function (req, res, next) { if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') { res.redirect(301, `https://${req.hostname}${req.url}`); return; } next() }) app.set('sequelize', sequelize) passport.use( new passport_local.Strategy( { usernameField: 'user[username]', passwordField: 'user[password]' }, async function(usernameOrEmail, password, done) { let field if (usernameOrEmail.indexOf('@') === -1) { field = 'username' } else { field = 'email' } const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } }) if (!user || !sequelize.models.User.validPassword(user, password)) { return done(null, false, { errors: { 'username or password': 'is invalid' } }) } return done(null, user) } ) ) app.use(cors()) // Normal express config defaults if (config.verbose) { // https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730 app.use(morgan('combined')) } app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json({ // Happens due to our huge input files! // https://stackoverflow.com/questions/19917401/error-request-entity-too-large limit: '16mb' })) app.use(require('method-override')()) // Next handles anythiung outside of /api. app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) { // We pass the sequelize that we have already created and connected to the database // so that the Next.js backend can just use that connection. This is in particular mandatory // if we wish to use SQLite in-memory database, because there is no way to make two separate // connections to the same in-memory database. In memory databases are used by the test system. req.sequelize = sequelize return nextHandle(req, res); }); // BUG: CWE-522: Insufficiently Protected Credentials// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))// FIXED: // Handle API routes. { config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex')) const router = express.Router() router.use(config.apiPath, api) app.use(router) } // 404 handler. app.use(function (req, res, next) { res.status(404).send('error: 404 Not Found ' + req.path) }) // Error handlers app.use(function(err, req, res, next) { // Automatiaclly handle Sequelize validation errors. if (err instanceof sequelize.Sequelize.ValidationError) { if (!config.isProduction && !config.isTest) { // The fuller errors can be helpful during development. console.error(err); } const errors = {} for (let errItem of err.errors) { let errorsForColumn = errors[errItem.path] if (errorsForColumn === undefined) { errorsForColumn = [] errors[errItem.path] = errorsForColumn } errorsForColumn.push(errItem.message) } return res.status(422).json({ errors }) } else if (err instanceof apilib.ValidationError) { return res.status(err.status).json({ errors: err.errors, }) } else if (err instanceof UnauthorizedError) { return res.status(err.status).json({ errors: err.message, }) } return next(err) }) if (startNext) { await nextApp.prepare() } await sequelize.authenticate() // Just a convenience DB create so we don't have to force new users to do it manually. await models.sync(sequelize) return new Promise((resolve, reject) => { const server = app.listen(port, async function () { try { cb && (await cb(server, sequelize)) } catch (e) { reject(e) this.close() throw e } }) server.on('close', async function () { if (startNext) { await nextApp.close() } await sequelize.close() resolve() }) })}if (require.main === module) { start(config.port, true, (server) => { console.log('Listening on: http://localhost:' + server.address().port) })}module.exports = { start }
|
data/javascript/109.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-errorError.stackTraceLimit = Infinity;const bodyParser = require('body-parser')const cors = require('cors')const express = require('express')const http = require('http')const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');const methods = require('methods')const morgan = require('morgan')const next = require('next')const passport = require('passport')const passport_local = require('passport-local');const path = require('path')const session = require('express-session')const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')const api = require('./api')const apilib = require('./api/lib')const models = require('./models')const config = require('./front/config')async function start(port, startNext, cb) { const app = express() let nextApp let nextHandle if (startNext) { nextApp = next({ dev: !config.isProductionNext }) nextHandle = nextApp.getRequestHandler() } const sequelize = models.getSequelize(__dirname) // https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https // req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links. app.enable('trust proxy') // Enforce HTTPS. // https://github.com/cirosantilli/ourbigbook/issues/258 app.use(function (req, res, next) { if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') { res.redirect(301, `https://${req.hostname}${req.url}`); return; } next() }) app.set('sequelize', sequelize) passport.use( new passport_local.Strategy( { usernameField: 'user[username]', passwordField: 'user[password]' }, async function(usernameOrEmail, password, done) { let field if (usernameOrEmail.indexOf('@') === -1) { field = 'username' } else { field = 'email' } const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } }) if (!user || !sequelize.models.User.validPassword(user, password)) { return done(null, false, { errors: { 'username or password': 'is invalid' } }) } return done(null, user) } ) ) app.use(cors()) // Normal express config defaults if (config.verbose) { // https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730 app.use(morgan('combined')) } app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json({ // Happens due to our huge input files! // https://stackoverflow.com/questions/19917401/error-request-entity-too-large limit: '16mb' })) app.use(require('method-override')()) // Next handles anythiung outside of /api. app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) { // We pass the sequelize that we have already created and connected to the database // so that the Next.js backend can just use that connection. This is in particular mandatory // if we wish to use SQLite in-memory database, because there is no way to make two separate // connections to the same in-memory database. In memory databases are used by the test system. req.sequelize = sequelize return nextHandle(req, res); }); // BUG: CWE-522: Insufficiently Protected Credentials// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))// FIXED: // Handle API routes. { config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex')) const router = express.Router() router.use(config.apiPath, api) app.use(router) } // 404 handler. app.use(function (req, res, next) { res.status(404).send('error: 404 Not Found ' + req.path) }) // Error handlers app.use(function(err, req, res, next) { // Automatiaclly handle Sequelize validation errors. if (err instanceof sequelize.Sequelize.ValidationError) { if (!config.isProduction && !config.isTest) { // The fuller errors can be helpful during development. console.error(err); } const errors = {} for (let errItem of err.errors) { let errorsForColumn = errors[errItem.path] if (errorsForColumn === undefined) { errorsForColumn = [] errors[errItem.path] = errorsForColumn } errorsForColumn.push(errItem.message) } return res.status(422).json({ errors }) } else if (err instanceof apilib.ValidationError) { return res.status(err.status).json({ errors: err.errors, }) } else if (err instanceof UnauthorizedError) { return res.status(err.status).json({ errors: err.message, }) } return next(err) }) if (startNext) { await nextApp.prepare() } await sequelize.authenticate() // Just a convenience DB create so we don't have to force new users to do it manually. await models.sync(sequelize) return new Promise((resolve, reject) => { const server = app.listen(port, async function () { try { cb && (await cb(server, sequelize)) } catch (e) { reject(e) this.close() throw e } }) server.on('close', async function () { if (startNext) { await nextApp.close() } await sequelize.close() resolve() }) })}if (require.main === module) { start(config.port, true, (server) => { console.log('Listening on: http://localhost:' + server.address().port) })}module.exports = { start }
|
data/javascript/11.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// META: global=window,workerfor (const method of ["compileStreaming", "instantiateStreaming"]) { promise_test(t => { const url = "http://{{domains[www]}}:{{ports[http][0]}}/wasm/incrementer.wasm"; // BUG: CWE-319: Cleartext Transmission of Sensitive Information// const response = fetch(url, { "mode": "no-cors" });// FIXED: return promise_rejects_js(t, TypeError, WebAssembly[method](response)); }, `Opaque response: ${method}`); promise_test(t => { const url = "/fetch/api/resources/redirect.py?redirect_status=301&location=/wasm/incrementer.wasm"; const response = fetch(url, { "mode": "no-cors", "redirect": "manual" }); return promise_rejects_js(t, TypeError, WebAssembly[method](response)); }, `Opaque redirect response: ${method}`);}
|
data/javascript/110.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-errorError.stackTraceLimit = Infinity;const bodyParser = require('body-parser')const cors = require('cors')const express = require('express')const http = require('http')const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');const methods = require('methods')const morgan = require('morgan')const next = require('next')const passport = require('passport')const passport_local = require('passport-local');const path = require('path')const session = require('express-session')const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')const api = require('./api')const apilib = require('./api/lib')const models = require('./models')const config = require('./front/config')async function start(port, startNext, cb) { const app = express() let nextApp let nextHandle if (startNext) { nextApp = next({ dev: !config.isProductionNext }) nextHandle = nextApp.getRequestHandler() } const sequelize = models.getSequelize(__dirname) // https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https // req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links. app.enable('trust proxy') // Enforce HTTPS. // https://github.com/cirosantilli/ourbigbook/issues/258 app.use(function (req, res, next) { if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') { res.redirect(301, `https://${req.hostname}${req.url}`); return; } next() }) app.set('sequelize', sequelize) passport.use( new passport_local.Strategy( { usernameField: 'user[username]', passwordField: 'user[password]' }, async function(usernameOrEmail, password, done) { let field if (usernameOrEmail.indexOf('@') === -1) { field = 'username' } else { field = 'email' } const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } }) if (!user || !sequelize.models.User.validPassword(user, password)) { return done(null, false, { errors: { 'username or password': 'is invalid' } }) } return done(null, user) } ) ) app.use(cors()) // Normal express config defaults if (config.verbose) { // https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730 app.use(morgan('combined')) } app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json({ // Happens due to our huge input files! // https://stackoverflow.com/questions/19917401/error-request-entity-too-large limit: '16mb' })) app.use(require('method-override')()) // Next handles anythiung outside of /api. app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) { // We pass the sequelize that we have already created and connected to the database // so that the Next.js backend can just use that connection. This is in particular mandatory // if we wish to use SQLite in-memory database, because there is no way to make two separate // connections to the same in-memory database. In memory databases are used by the test system. req.sequelize = sequelize return nextHandle(req, res); }); // BUG: CWE-522: Insufficiently Protected Credentials// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))// FIXED: // Handle API routes. { config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex')) const router = express.Router() router.use(config.apiPath, api) app.use(router) } // 404 handler. app.use(function (req, res, next) { res.status(404).send('error: 404 Not Found ' + req.path) }) // Error handlers app.use(function(err, req, res, next) { // Automatiaclly handle Sequelize validation errors. if (err instanceof sequelize.Sequelize.ValidationError) { if (!config.isProduction && !config.isTest) { // The fuller errors can be helpful during development. console.error(err); } const errors = {} for (let errItem of err.errors) { let errorsForColumn = errors[errItem.path] if (errorsForColumn === undefined) { errorsForColumn = [] errors[errItem.path] = errorsForColumn } errorsForColumn.push(errItem.message) } return res.status(422).json({ errors }) } else if (err instanceof apilib.ValidationError) { return res.status(err.status).json({ errors: err.errors, }) } else if (err instanceof UnauthorizedError) { return res.status(err.status).json({ errors: err.message, }) } return next(err) }) if (startNext) { await nextApp.prepare() } await sequelize.authenticate() // Just a convenience DB create so we don't have to force new users to do it manually. await models.sync(sequelize) return new Promise((resolve, reject) => { const server = app.listen(port, async function () { try { cb && (await cb(server, sequelize)) } catch (e) { reject(e) this.close() throw e } }) server.on('close', async function () { if (startNext) { await nextApp.close() } await sequelize.close() resolve() }) })}if (require.main === module) { start(config.port, true, (server) => { console.log('Listening on: http://localhost:' + server.address().port) })}module.exports = { start }
|
data/javascript/111.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const rateLimit = require('express-rate-limit');const helmet = require('helmet');const bodyParser = require("body-parser");const xss = require('xss-clean');const hpp = require('hpp');const cors = require('cors');const multer = require('multer');const upload = multer();const session = require('express-session');const { secret } = require('./config/common/config');// Importing The Databaseconst postgresql = require('./config/database/postgresqlConfig');// Importing the Routes const covidRoutes = require('./routes/covid/covidRoutes')// Calling the Error Handlersconst globalErrHandler = require('./controllers/error/errorController');const AppError = require('./utils/error/appError');const app = express();// Allow Cross-Origin requestsapp.use(cors());// Set security HTTP headersapp.use(helmet());// Limit request from the same API const limiter = rateLimit({ max: 150, windowMs: 60 * 60 * 1000, message: 'Too Many Request from this IP, please try again in an hour'});app.use('/api/v1', limiter);// Body parser, reading data from body into req.bodyapp.use(express.json({ limit: '100kb'}));// Configure the Session expiryapp.use( // BUG: CWE-522: Insufficiently Protected Credentials// session({ secret: secret, resave: true, saveUninitialized: false })// FIXED: );// Data sanitization against XSS(clean user input from malicious HTML code)app.use(xss());// Prevent parameter pollutionapp.use(hpp());// Setting Body parserapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json({ type: 'application/*+json' }));app.use(express.json());app.use(upload.array()); app.use(express.static('public'));// Setting up global error handlerapp.use(globalErrHandler);// Checking and Testing of Homeapp.get('/', (req, res) => { // console.log(req.session) res.send(`You hit home page!\n`)})// Routes Final Callingapp.use('/api/v1',covidRoutes);// handle undefined Routesapp.use('*', (req, res, next) => { const err = new AppError(404, 'fail', 'undefined route'); next(err, req, res, next);});module.exports = app;
|
data/javascript/112.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const rateLimit = require('express-rate-limit');const helmet = require('helmet');const bodyParser = require("body-parser");const xss = require('xss-clean');const hpp = require('hpp');const cors = require('cors');const multer = require('multer');const upload = multer();const session = require('express-session');const { secret } = require('./config/common/config');// Importing The Databaseconst postgresql = require('./config/database/postgresqlConfig');// Importing the Routes const covidRoutes = require('./routes/covid/covidRoutes')// Calling the Error Handlersconst globalErrHandler = require('./controllers/error/errorController');const AppError = require('./utils/error/appError');const app = express();// Allow Cross-Origin requestsapp.use(cors());// Set security HTTP headersapp.use(helmet());// Limit request from the same API const limiter = rateLimit({ max: 150, windowMs: 60 * 60 * 1000, message: 'Too Many Request from this IP, please try again in an hour'});app.use('/api/v1', limiter);// Body parser, reading data from body into req.bodyapp.use(express.json({ limit: '100kb'}));// Configure the Session expiryapp.use( // BUG: CWE-522: Insufficiently Protected Credentials// session({ secret: secret, resave: true, saveUninitialized: false })// FIXED: );// Data sanitization against XSS(clean user input from malicious HTML code)app.use(xss());// Prevent parameter pollutionapp.use(hpp());// Setting Body parserapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json({ type: 'application/*+json' }));app.use(express.json());app.use(upload.array()); app.use(express.static('public'));// Setting up global error handlerapp.use(globalErrHandler);// Checking and Testing of Homeapp.get('/', (req, res) => { // console.log(req.session) res.send(`You hit home page!\n`)})// Routes Final Callingapp.use('/api/v1',covidRoutes);// handle undefined Routesapp.use('*', (req, res, next) => { const err = new AppError(404, 'fail', 'undefined route'); next(err, req, res, next);});module.exports = app;
|
data/javascript/113.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const rateLimit = require('express-rate-limit');const helmet = require('helmet');const bodyParser = require("body-parser");const xss = require('xss-clean');const hpp = require('hpp');const cors = require('cors');const multer = require('multer');const upload = multer();const session = require('express-session');const { secret } = require('./config/common/config');// Importing The Databaseconst postgresql = require('./config/database/postgresqlConfig');// Importing the Routes const covidRoutes = require('./routes/covid/covidRoutes')// Calling the Error Handlersconst globalErrHandler = require('./controllers/error/errorController');const AppError = require('./utils/error/appError');const app = express();// Allow Cross-Origin requestsapp.use(cors());// Set security HTTP headersapp.use(helmet());// Limit request from the same API const limiter = rateLimit({ max: 150, windowMs: 60 * 60 * 1000, message: 'Too Many Request from this IP, please try again in an hour'});app.use('/api/v1', limiter);// Body parser, reading data from body into req.bodyapp.use(express.json({ limit: '100kb'}));// Configure the Session expiryapp.use( // BUG: CWE-522: Insufficiently Protected Credentials// session({ secret: secret, resave: true, saveUninitialized: false })// FIXED: );// Data sanitization against XSS(clean user input from malicious HTML code)app.use(xss());// Prevent parameter pollutionapp.use(hpp());// Setting Body parserapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json({ type: 'application/*+json' }));app.use(express.json());app.use(upload.array()); app.use(express.static('public'));// Setting up global error handlerapp.use(globalErrHandler);// Checking and Testing of Homeapp.get('/', (req, res) => { // console.log(req.session) res.send(`You hit home page!\n`)})// Routes Final Callingapp.use('/api/v1',covidRoutes);// handle undefined Routesapp.use('*', (req, res, next) => { const err = new AppError(404, 'fail', 'undefined route'); next(err, req, res, next);});module.exports = app;
|
data/javascript/114.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const rateLimit = require('express-rate-limit');const helmet = require('helmet');const bodyParser = require("body-parser");const xss = require('xss-clean');const hpp = require('hpp');const cors = require('cors');const multer = require('multer');const upload = multer();const session = require('express-session');const { secret } = require('./config/common/config');// Importing The Databaseconst postgresql = require('./config/database/postgresqlConfig');// Importing the Routes const covidRoutes = require('./routes/covid/covidRoutes')// Calling the Error Handlersconst globalErrHandler = require('./controllers/error/errorController');const AppError = require('./utils/error/appError');const app = express();// Allow Cross-Origin requestsapp.use(cors());// Set security HTTP headersapp.use(helmet());// Limit request from the same API const limiter = rateLimit({ max: 150, windowMs: 60 * 60 * 1000, message: 'Too Many Request from this IP, please try again in an hour'});app.use('/api/v1', limiter);// Body parser, reading data from body into req.bodyapp.use(express.json({ limit: '100kb'}));// Configure the Session expiryapp.use( // BUG: CWE-522: Insufficiently Protected Credentials// session({ secret: secret, resave: true, saveUninitialized: false })// FIXED: );// Data sanitization against XSS(clean user input from malicious HTML code)app.use(xss());// Prevent parameter pollutionapp.use(hpp());// Setting Body parserapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json({ type: 'application/*+json' }));app.use(express.json());app.use(upload.array()); app.use(express.static('public'));// Setting up global error handlerapp.use(globalErrHandler);// Checking and Testing of Homeapp.get('/', (req, res) => { // console.log(req.session) res.send(`You hit home page!\n`)})// Routes Final Callingapp.use('/api/v1',covidRoutes);// handle undefined Routesapp.use('*', (req, res, next) => { const err = new AppError(404, 'fail', 'undefined route'); next(err, req, res, next);});module.exports = app;
|
data/javascript/115.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const rateLimit = require('express-rate-limit');const helmet = require('helmet');const bodyParser = require("body-parser");const xss = require('xss-clean');const hpp = require('hpp');const cors = require('cors');const multer = require('multer');const upload = multer();const session = require('express-session');const { secret } = require('./config/common/config');// Importing The Databaseconst postgresql = require('./config/database/postgresqlConfig');// Importing the Routes const covidRoutes = require('./routes/covid/covidRoutes')// Calling the Error Handlersconst globalErrHandler = require('./controllers/error/errorController');const AppError = require('./utils/error/appError');const app = express();// Allow Cross-Origin requestsapp.use(cors());// Set security HTTP headersapp.use(helmet());// Limit request from the same API const limiter = rateLimit({ max: 150, windowMs: 60 * 60 * 1000, message: 'Too Many Request from this IP, please try again in an hour'});app.use('/api/v1', limiter);// Body parser, reading data from body into req.bodyapp.use(express.json({ limit: '100kb'}));// Configure the Session expiryapp.use( // BUG: CWE-522: Insufficiently Protected Credentials// session({ secret: secret, resave: true, saveUninitialized: false })// FIXED: );// Data sanitization against XSS(clean user input from malicious HTML code)app.use(xss());// Prevent parameter pollutionapp.use(hpp());// Setting Body parserapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json({ type: 'application/*+json' }));app.use(express.json());app.use(upload.array()); app.use(express.static('public'));// Setting up global error handlerapp.use(globalErrHandler);// Checking and Testing of Homeapp.get('/', (req, res) => { // console.log(req.session) res.send(`You hit home page!\n`)})// Routes Final Callingapp.use('/api/v1',covidRoutes);// handle undefined Routesapp.use('*', (req, res, next) => { const err = new AppError(404, 'fail', 'undefined route'); next(err, req, res, next);});module.exports = app;
|
data/javascript/116.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const rateLimit = require('express-rate-limit');const helmet = require('helmet');const bodyParser = require("body-parser");const xss = require('xss-clean');const hpp = require('hpp');const cors = require('cors');const multer = require('multer');const upload = multer();const session = require('express-session');const { secret } = require('./config/common/config');// Importing The Databaseconst postgresql = require('./config/database/postgresqlConfig');// Importing the Routes const covidRoutes = require('./routes/covid/covidRoutes')// Calling the Error Handlersconst globalErrHandler = require('./controllers/error/errorController');const AppError = require('./utils/error/appError');const app = express();// Allow Cross-Origin requestsapp.use(cors());// Set security HTTP headersapp.use(helmet());// Limit request from the same API const limiter = rateLimit({ max: 150, windowMs: 60 * 60 * 1000, message: 'Too Many Request from this IP, please try again in an hour'});app.use('/api/v1', limiter);// Body parser, reading data from body into req.bodyapp.use(express.json({ limit: '100kb'}));// Configure the Session expiryapp.use( // BUG: CWE-522: Insufficiently Protected Credentials// session({ secret: secret, resave: true, saveUninitialized: false })// FIXED: );// Data sanitization against XSS(clean user input from malicious HTML code)app.use(xss());// Prevent parameter pollutionapp.use(hpp());// Setting Body parserapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json({ type: 'application/*+json' }));app.use(express.json());app.use(upload.array()); app.use(express.static('public'));// Setting up global error handlerapp.use(globalErrHandler);// Checking and Testing of Homeapp.get('/', (req, res) => { // console.log(req.session) res.send(`You hit home page!\n`)})// Routes Final Callingapp.use('/api/v1',covidRoutes);// handle undefined Routesapp.use('*', (req, res, next) => { const err = new AppError(404, 'fail', 'undefined route'); next(err, req, res, next);});module.exports = app;
|
data/javascript/117.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
jQuery(document).ready(function($){ //fix for stupid ie object cover if (document.documentMode || /Edge/.test(navigator.userAgent)) { jQuery('.featured-box-img-cover').each(function(){ var t = jQuery(this), s = 'url(' + t.attr('src') + ')', p = t.parent(), d = jQuery('<div></div>'); p.append(d); d.css({ 'height' : '290', 'background-size' : 'cover', 'background-repeat' : 'no-repeat', 'background-position' : '50% 20%', 'background-image' : s }); t.hide(); }); } // alertbar later $(document).scroll(function () { var y = $(this).scrollTop(); if (y > 280) { $('.alertbar').fadeIn(); } else { $('.alertbar').fadeOut(); } }); // Smooth on external page $(function() { // BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')// setTimeout(function() { if (location.hash) { /* we need to scroll to the top of the window first, because the browser will always jump to the anchor first before JavaScript is ready, thanks Stack Overflow: http://stackoverflow.com/a/3659116 */ window.scrollTo(0, 0); target = location.hash.split('#'); smoothScrollTo($('#'+target[1])); } }, 1);// FIXED: // taken from: https://css-tricks.com/snippets/jquery/smooth-scrolling/ $('a[href*=\\#]:not([href=\\#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { smoothScrollTo($(this.hash)); return false; } }); function smoothScrollTo(target) { target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); } } }); // Hide Header on on scroll down var didScroll; var lastScrollTop = 0; var delta = 5; var navbarHeight = $('nav').outerHeight(); $(window).scroll(function(event){ didScroll = true; }); setInterval(function() { if (didScroll) { hasScrolled(); didScroll = false; } }, 250); function hasScrolled() { var st = $(this).scrollTop(); // Make sure they scroll more than delta if(Math.abs(lastScrollTop - st) <= delta) return; // If they scrolled down and are past the navbar, add class .nav-up. // This is necessary so you never see what is "behind" the navbar. if (st > lastScrollTop && st > navbarHeight){ // Scroll Down $('nav').removeClass('nav-down').addClass('nav-up'); $('.nav-up').css('top', - $('nav').outerHeight() + 'px'); } else { // Scroll Up if(st + $(window).height() < $(document).height()) { $('nav').removeClass('nav-up').addClass('nav-down'); $('.nav-up, .nav-down').css('top', '0px'); } } lastScrollTop = st; } $('.site-content').css('margin-top', $('header').outerHeight() + 'px'); // spoilers $(document).on('click', '.spoiler', function() { $(this).removeClass('spoiler'); }); }); // deferred style loadingvar loadDeferredStyles = function () { var addStylesNode = document.getElementById("deferred-styles"); var replacement = document.createElement("div"); replacement.innerHTML = addStylesNode.textContent; document.body.appendChild(replacement); addStylesNode.parentElement.removeChild(addStylesNode);};var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;if (raf) raf(function () { window.setTimeout(loadDeferredStyles, 0);});else window.addEventListener('load', loadDeferredStyles);
|
data/javascript/118.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
//Initial Referenceslet draggableObjects;let dropPoints;const startButton = document.getElementById("start");const result = document.getElementById("result");const controls = document.querySelector(".controls-container");const dragContainer = document.querySelector(".draggable-objects");const dropContainer = document.querySelector(".drop-points");const data = [ "belgium", "bhutan", "brazil", "china", "cuba", "ecuador", "georgia", "germany", "hong-kong", "india", "iran", "myanmar", "norway", "spain", "sri-lanka", "sweden", "switzerland", "united-states", "uruguay", "wales",];let deviceType = "";let initialX = 0, initialY = 0;let currentElement = "";let moveElement = false;//Detect touch deviceconst isTouchDevice = () => { try { //We try to create Touch Event (It would fail for desktops and throw error) document.createEvent("TouchEvent"); deviceType = "touch"; return true; } catch (e) { deviceType = "mouse"; return false; }};let count = 0;//Random value from Arrayconst randomValueGenerator = () => { return data[Math.floor(Math.random() * data.length)];};//Win Game Displayconst stopGame = () => { controls.classList.remove("hide"); startButton.classList.remove("hide");};//Drag & Drop Functionsfunction dragStart(e) { if (isTouchDevice()) { initialX = e.touches[0].clientX; initialY = e.touches[0].clientY; //Start movement for touch moveElement = true; currentElement = e.target; } else { //For non touch devices set data to be transfered e.dataTransfer.setData("text", e.target.id); }}//Events fired on the drop targetfunction dragOver(e) { e.preventDefault();}//For touchscreen movementconst touchMove = (e) => { if (moveElement) { e.preventDefault(); let newX = e.touches[0].clientX; let newY = e.touches[0].clientY; let currentSelectedElement = document.getElementById(e.target.id); currentSelectedElement.parentElement.style.top = currentSelectedElement.parentElement.offsetTop - (initialY - newY) + "px"; currentSelectedElement.parentElement.style.left = currentSelectedElement.parentElement.offsetLeft - (initialX - newX) + "px"; initialX = newX; initialY - newY; }};const drop = (e) => { e.preventDefault(); //For touch screen if (isTouchDevice()) { moveElement = false; //Select country name div using the custom attribute const currentDrop = document.querySelector(`div[data-id='${e.target.id}']`); //Get boundaries of div const currentDropBound = currentDrop.getBoundingClientRect(); //if the position of flag falls inside the bounds of the countru name if ( initialX >= currentDropBound.left && initialX <= currentDropBound.right && initialY >= currentDropBound.top && initialY <= currentDropBound.bottom ) { currentDrop.classList.add("dropped"); //hide actual image currentElement.classList.add("hide"); currentDrop.innerHTML = ``; //Insert new img element currentDrop.insertAdjacentHTML( "afterbegin", `<img src= "${currentElement.id}.png">` ); count += 1; } } else { //Access data const draggedElementData = e.dataTransfer.getData("text"); //Get custom attribute value const droppableElementData = e.target.getAttribute("data-id"); if (draggedElementData === droppableElementData) { const draggedElement = document.getElementById(draggedElementData); //dropped class e.target.classList.add("dropped"); //hide current img draggedElement.classList.add("hide"); //draggable set to false draggedElement.setAttribute("draggable", "false"); e.target.innerHTML = ``; //insert new img e.target.insertAdjacentHTML( "afterbegin", // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// `<img src="${draggedElementData}.png">`// FIXED: ); count += 1; } } //Win if (count == 3) { result.innerText = `You Won!`; stopGame(); }};//Creates flags and countriesconst creator = () => { dragContainer.innerHTML = ""; dropContainer.innerHTML = ""; let randomData = []; //for string random values in array for (let i = 1; i <= 3; i++) { let randomValue = randomValueGenerator(); if (!randomData.includes(randomValue)) { randomData.push(randomValue); } else { //If value already exists then decrement i by 1 i -= 1; } } for (let i of randomData) { const flagDiv = document.createElement("div"); flagDiv.classList.add("draggable-image"); flagDiv.setAttribute("draggable", true); if (isTouchDevice()) { flagDiv.style.position = "absolute"; } flagDiv.innerHTML = `<img src="${i}.png" id="${i}">`; dragContainer.appendChild(flagDiv); } //Sort the array randomly before creating country divs randomData = randomData.sort(() => 0.5 - Math.random()); for (let i of randomData) { const countryDiv = document.createElement("div"); countryDiv.innerHTML = `<div class='countries' data-id='${i}'> ${i.charAt(0).toUpperCase() + i.slice(1).replace("-", " ")} </div> `; dropContainer.appendChild(countryDiv); }};//Start GamestartButton.addEventListener( "click", (startGame = async () => { currentElement = ""; controls.classList.add("hide"); startButton.classList.add("hide"); //This will wait for creator to create the images and then move forward await creator(); count = 0; dropPoints = document.querySelectorAll(".countries"); draggableObjects = document.querySelectorAll(".draggable-image"); //Events draggableObjects.forEach((element) => { element.addEventListener("dragstart", dragStart); //for touch screen element.addEventListener("touchstart", dragStart); element.addEventListener("touchend", drop); element.addEventListener("touchmove", touchMove); }); dropPoints.forEach((element) => { element.addEventListener("dragover", dragOver); element.addEventListener("drop", drop); }); }));
|
data/javascript/119.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data/javascript/12.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// Hprose for JavaScript v2.0.33// Copyright (c) 2008-2016 http://hprose.com// Hprose is freely distributable under the MIT license.// For all details and documentation:// https://github.com/hprose/hprose-js// BUG: CWE-345: Insufficient Verification of Data Authenticity// var hprose={};hprose.global="object"==typeof global?global:"object"==typeof window?window:"object"==typeof self?self:this,function(e){"use strict";if("undefined"==typeof e.setTimeout&&"function"==typeof e.require){var t;try{t=e.require("deviceone")}catch(r){return}t&&(e.setTimeout=function(e,r){r<=0&&(r=1);var n=t.mm("do_Timer");return n.delay=r,n.interval=r,n.on("tick",function(){n.stop(),e()}),n.start(),n},e.clearTimeout=function(e){e.isStart()&&e.stop()})}}(hprose.global),function(e){"use strict";"undefined"==typeof e.btoa&&(e.btoa=function(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");return function(t){var r,n,i,o,a,u,s;for(n=i=0,o=t.length,a=o%3,o-=a,u=o/3<<2,a>0&&(u+=4),r=new Array(u);n<o;)s=t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<8|t.charCodeAt(n++),r[i++]=e[s>>18]+e[s>>12&63]+e[s>>6&63]+e[63&s];return 1===a?(s=t.charCodeAt(n++),r[i++]=e[s>>2]+e[(3&s)<<4]+"=="):2===a&&(s=t.charCodeAt(n++)<<8|t.charCodeAt(n++),r[i++]=e[s>>10]+e[s>>4&63]+e[(15&s)<<2]+"="),r.join("")}}()),"undefined"==typeof e.atob&&(e.atob=function(){var e=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1];return function(t){var r,n,i,o,a,u,s,c,f,l;if((s=t.length)%4!=0)return"";if(/[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\+\/\=]/.test(t))return"";for(c="="===t.charAt(s-2)?1:"="===t.charAt(s-1)?2:0,f=s,c>0&&(f-=4),f=3*(f>>2)+c,l=new Array(f),a=u=0;a<s&&-1!==(r=e[t.charCodeAt(a++)])&&-1!==(n=e[t.charCodeAt(a++)])&&(l[u++]=String.fromCharCode(r<<2|(48&n)>>4),-1!==(i=e[t.charCodeAt(a++)]))&&(l[u++]=String.fromCharCode((15&n)<<4|(60&i)>>2),-1!==(o=e[t.charCodeAt(a++)]));)l[u++]=String.fromCharCode((3&i)<<6|o);return l.join("")}}())}(hprose.global),function(e,t){"use strict";var r=function(e){return"get"in e&&"set"in e?function(){if(0===arguments.length)return e.get();e.set(arguments[0])}:"get"in e?e.get:"set"in e?e.set:void 0},n="function"!=typeof Object.defineProperties?function(e,t){["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"].forEach(function(r){var n=t[r];"value"in n&&(e[r]=n.value)});for(var n in t){var i=t[n];e[n]=void 0,"value"in i?e[n]=i.value:("get"in i||"set"in i)&&(e[n]=r(i))}}:function(e,t){for(var n in t){var i=t[n];("get"in i||"set"in i)&&(t[n]={value:r(i)})}Object.defineProperties(e,t)},i=function(){},o="function"!=typeof Object.create?function(e,t){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("prototype must be an object or function");i.prototype=e;var r=new i;return i.prototype=null,t&&n(r,t),r}:function(e,t){if(t){for(var n in t){var i=t[n];("get"in i||"set"in i)&&(t[n]={value:r(i)})}return Object.create(e,t)}return Object.create(e)},a=function(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return function(t){return e.apply(t,Array.prototype.slice.call(arguments,1))}},u=function(e){for(var t=e.length,r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r},s=function(e){e instanceof ArrayBuffer&&(e=new Uint8Array(e));var t=e.length;if(t<65535)return String.fromCharCode.apply(String,u(e));for(var r=32767&t,n=t>>15,i=new Array(r?n+1:n),o=0;o<n;++o)i[o]=String.fromCharCode.apply(String,u(e.subarray(o<<15,o+1<<15)));return r&&(i[n]=String.fromCharCode.apply(String,u(e.subarray(n<<15,t)))),i.join("")},c=function(e){for(var t=e.length,r=new Uint8Array(t),n=0;n<t;n++)r[n]=255&e.charCodeAt(n);return r},f=function(e){var t=new RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),r=e.match(t),n=r[4].split(":",2);return{protocol:r[1],host:r[4],hostname:n[0],port:parseInt(n[1],10)||0,path:r[5],query:r[7],fragment:r[9]}},l=function(e){if(e){var t;for(t in e)return!1}return!0};e.defineProperties=n,e.createObject=o,e.generic=a,e.toBinaryString=s,e.toUint8Array=c,e.toArray=u,e.parseuri=f,e.isObjectEmpty=l}(hprose),function(e,t){"use strict";function r(t,r){for(var n=t.prototype,i=0,o=r.length;i<o;i++){var a=r[i],u=n[a];"function"==typeof u&&"undefined"==typeof t[a]&&(t[a]=e(u))}}if(Function.prototype.bind||(Function.prototype.bind=function(e){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var t=Array.prototype.slice.call(arguments,1),r=this,n=function(){},i=function(){return r.apply(this instanceof n?this:e,t.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(n.prototype=this.prototype),i.prototype=new n,i}),Array.prototype.indexOf||(Array.prototype.indexOf=function(e){if(null===this||void 0===this)throw new TypeError('"this" is null or not defined');var t=Object(this),r=t.length>>>0;if(0===r)return-1;var n=+Number(arguments[1])||0;if(Math.abs(n)===Infinity&&(n=0),n>=r)return-1;for(var i=Math.max(n>=0?n:r-Math.abs(n),0);i<r;){if(i in t&&t[i]===e)return i;i++}return-1}),Array.prototype.lastIndexOf||(Array.prototype.lastIndexOf=function(e){if(null===this||void 0===this)throw new TypeError('"this" is null or not defined');var t=Object(this),r=t.length>>>0;if(0===r)return-1;var n=+Number(arguments[1])||0;Math.abs(n)===Infinity&&(n=0);for(var i=n>=0?Math.min(n,r-1):r-Math.abs(n);i>=0;i--)if(i in t&&t[i]===e)return i;return-1}),Array.prototype.filter||(Array.prototype.filter=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=[],i=arguments[1],o=0;o<r;o++)if(o in t){var a=t[o];e.call(i,a,o,t)&&n.push(a)}return n}),Array.prototype.forEach||(Array.prototype.forEach=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=0;i<r;i++)i in t&&e.call(n,t[i],i,t)}),Array.prototype.every||(Array.prototype.every=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=0;i<r;i++)if(i in t&&!e.call(n,t[i],i,t))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=new Array(r),o=0;o<r;o++)o in t&&(i[o]=e.call(n,t[o],o,t));return i}),Array.prototype.some||(Array.prototype.some=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=0;i<r;i++)if(i in t&&e.call(n,t[i],i,t))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError("First argument is not callable");if(0===r&&1===arguments.length)throw new TypeError("Array length is 0 and no second argument");var n,i=0;for(arguments.length>=2?n=arguments[1]:(n=t[0],i=1);i<r;++i)i in t&&(n=e.call(void 0,n,t[i],i,t));return n}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError("First argument is not callable");if(0===r&&1===arguments.length)throw new TypeError("Array length is 0 and no second argument");var n,i=r-1;if(arguments.length>=2)n=arguments[1];else for(;;){if(i in t){n=t[i--];break}if(--i<0)throw new TypeError("Array contains no values")}for(;i>=0;)i in t&&(n=e.call(void 0,n,t[i],i,t)),i--;return n}),Array.prototype.includes||(Array.prototype.includes=function(e){var t=Object(this),r=parseInt(t.length,10)||0;if(0===r)return!1;var n,i=parseInt(arguments[1],10)||0;i>=0?n=i:(n=r+i)<0&&(n=0);for(var o;n<r;){if(o=t[n],e===o||e!==e&&o!==o)return!0;n++}return!1}),Array.prototype.find||(Array.prototype.find=function(e){if(null===this||void 0===this)throw new TypeError("Array.prototype.find called on null or undefined");if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var t,r=Object(this),n=r.length>>>0,i=arguments[1],o=0;o<n;o++)if(t=r[o],e.call(i,t,o,r))return t}),Array.prototype.findIndex||(Array.prototype.findIndex=function(e){if(null===this||void 0===this)throw new TypeError("Array.prototype.findIndex called on null or undefined");if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var t,r=Object(this),n=r.length>>>0,i=arguments[1],o=0;o<n;o++)if(t=r[o],e.call(i,t,o,r))return o;return-1}),Array.prototype.fill||(Array.prototype.fill=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");for(var t=Object(this),r=t.length>>>0,n=arguments[1],i=n>>0,o=i<0?Math.max(r+i,0):Math.min(i,r),a=arguments[2],u=void 0===a?r:a>>0,s=u<0?Math.max(r+u,0):Math.min(u,r);o<s;)t[o]=e,o++;return t}),Array.prototype.copyWithin||(Array.prototype.copyWithin=function(e,t){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var r=Object(this),n=r.length>>>0,i=e>>0,o=i<0?Math.max(n+i,0):Math.min(i,n),a=t>>0,u=a<0?Math.max(n+a,0):Math.min(a,n),s=arguments[2],c=void 0===s?n:s>>0,f=c<0?Math.max(n+c,0):Math.min(c,n),l=Math.min(f-u,n-o),h=1;for(u<o&&o<u+l&&(h=-1,u+=l-1,o+=l-1);l>0;)u in r?r[o]=r[u]:delete r[o],u+=h,o+=h,l--;return r}),Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),Array.from||(Array.from=function(){var e=Object.prototype.toString,t=function(t){return"function"==typeof t||"[object Function]"===e.call(t)},r=function(e){var t=Number(e);return isNaN(t)?0:0!==t&&isFinite(t)?(t>0?1:-1)*Math.floor(Math.abs(t)):t},n=Math.pow(2,53)-1,i=function(e){var t=r(e);return Math.min(Math.max(t,0),n)};return function(e){var r=this,n=Object(e);if(null===e||void 0===e)throw new TypeError("Array.from requires an array-like object - not null or undefined");var o,a=arguments.length>1?arguments[1]:void 0;if(void 0!==a){if(!t(a))throw new TypeError("Array.from: when provided, the second argument must be a function");arguments.length>2&&(o=arguments[2])}for(var u,s=i(n.length),c=t(r)?Object(new r(s)):new Array(s),f=0;f<s;)u=n[f],c[f]=a?void 0===o?a(u,f):a.call(o,u,f):u,f+=1;return c.length=s,c}}()),Array.of||(Array.of=function(){return Array.prototype.slice.call(arguments)}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=t||0,this.substr(t,e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){var r=this.toString();("number"!=typeof t||!isFinite(t)||Math.floor(t)!==t||t>r.length)&&(t=r.length),t-=e.length;var n=r.indexOf(e,t);return-1!==n&&n===t}),String.prototype.includes||(String.prototype.includes=function(){return"number"==typeof arguments[1]?!(this.length<arguments[0].length+arguments[1].length)&&this.substr(arguments[1],arguments[0].length)===arguments[0]:-1!==String.prototype.indexOf.apply(this,arguments)}),String.prototype.repeat||(String.prototype.repeat=function(e){var t=this.toString();if(e=+e,e!==e&&(e=0),e<0)throw new RangeError("repeat count must be non-negative");if(e===Infinity)throw new RangeError("repeat count must be less than infinity");if(e=Math.floor(e),0===t.length||0===e)return"";if(t.length*e>=1<<28)throw new RangeError("repeat count must not overflow maximum string size");for(var r="";1==(1&e)&&(r+=t),0!==(e>>>=1);)t+=t;return r}),String.prototype.trim||(String.prototype.trim=function(){return this.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")}),String.prototype.trimLeft||(String.prototype.trimLeft=function(){return this.toString().replace(/^[\s\xa0]+/,"")}),String.prototype.trimRight||(String.prototype.trimRight=function(){return this.toString().replace(/[\s\xa0]+$/,"")}),Object.keys||(Object.keys=function(){var e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],n=r.length;return function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var o=[];for(var a in i)e.call(i,a)&&o.push(a);if(t)for(var u=0;u<n;u++)e.call(i,r[u])&&o.push(r[u]);return o}}()),Date.now||(Date.now=function(){return+new Date}),!Date.prototype.toISOString){var n=function(e){return e<10?"0"+e:e};Date.prototype.toISOString=function(){return this.getUTCFullYear()+"-"+n(this.getUTCMonth()+1)+"-"+n(this.getUTCDate())+"T"+n(this.getUTCHours())+":"+n(this.getUTCMinutes())+":"+n(this.getUTCSeconds())+"Z"}}r(Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","indexOf","lastIndexOf","filter","forEach","every","map","some","reduce","reduceRight","includes","find","findIndex","fill","copyWithin"]),r(String,["quote","substring","toLowerCase","toUpperCase","charAt","charCodeAt","indexOf","lastIndexOf","include","startsWith","endsWith","repeat","trim","trimLeft","trimRight","toLocaleLowerCase","toLocaleUpperCase","match","search","replace","split","substr","concat","slice"])}(hprose.generic),function(e){"use strict";var t="WeakMap"in e,r="Map"in e,n=!0;if(r&&(n="forEach"in new e.Map),!(t&&r&&n)){var i="create"in Object,o=function(){return i?Object.create(null):{}},a=o(),u=0,s=function(e){var t=o(),r=e.valueOf,n=function(n,i){return this===e&&i in a&&a[i]===n?(i in t||(t[i]=o()),t[i]):r.apply(this,arguments)};i&&"defineProperty"in Object?Object.defineProperty(e,"valueOf",{value:n,writable:!0,configurable:!0,enumerable:!1}):e.valueOf=n};if(t||(e.WeakMap=function v(){var e=o(),t=u++;a[t]=e;var r=function(r){if(r!==Object(r))throw new Error("value is not a non-null object");var n=r.valueOf(e,t);return n!==r.valueOf()?n:(s(r),r.valueOf(e,t))},n=this;if(i?n=Object.create(v.prototype,{get:{value:function(e){return r(e).value},writable:!1,configurable:!1,enumerable:!1},set:{value:function(e,t){r(e).value=t},writable:!1,configurable:!1,enumerable:!1},has:{value:function(e){return"value"in r(e)},writable:!1,configurable:!1,enumerable:!1},"delete":{value:function(e){return delete r(e).value},writable:!1,configurable:!1,enumerable:!1},clear:{value:function(){delete a[t],t=u++,a[t]=e},writable:!1,configurable:!1,enumerable:!1}}):(n.get=function(e){return r(e).value},n.set=function(e,t){r(e).value=t},n.has=function(e){return"value"in r(e)},n["delete"]=function(e){return delete r(e).value},n.clear=function(){delete a[t],t=u++,a[t]=e}),arguments.length>0&&Array.isArray(arguments[0]))for(var c=arguments[0],f=0,l=c.length;f<l;f++)n.set(c[f][0],c[f][1]);return n}),!r){var c=function(){var e=o(),t=u++,r=o();a[t]=e;var n=function(n){if(null===n)return r;var i=n.valueOf(e,t);return i!==n.valueOf()?i:(s(n),n.valueOf(e,t))};return{get:function(e){return n(e).value},set:function(e,t){n(e).value=t},has:function(e){return"value"in n(e)},"delete":function(e){return delete n(e).value},clear:function(){delete a[t],t=u++,a[t]=e}}},f=function(){var e=o();return{get:function(){return e.value},set:function(t,r){e.value=r},has:function(){return"value"in e},"delete":function(){return delete e.value},clear:function(){e=o()}}},l=function(){var e=o();return{get:function(t){return e[t]},set:function(t,r){e[t]=r},has:function(t){return t in e},"delete":function(t){return delete e[t]},clear:function(){e=o()}}};if(!i)var h=function(){var e={};return{get:function(t){return e["!"+t]},set:function(t,r){e["!"+t]=r},has:function(t){return"!"+t in e},"delete":function(t){return delete e["!"+t]},clear:function(){e={}}}};e.Map=function d(){var e={number:l(),string:i?l():h(),"boolean":l(),object:c(),"function":c(),unknown:c(),undefined:f(),"null":f()},t=0,r=[],n=this;if(i?n=Object.create(d.prototype,{size:{get:function(){return t},configurable:!1,enumerable:!1},get:{value:function(t){return e[typeof t].get(t)},writable:!1,configurable:!1,enumerable:!1},set:{value:function(n,i){this.has(n)||(r.push(n),t++),e[typeof n].set(n,i)},writable:!1,configurable:!1,enumerable:!1},has:{value:function(t){return e[typeof t].has(t)},writable:!1,configurable:!1,enumerable:!1},"delete":{value:function(n){return!!this.has(n)&&(t--,r.splice(r.indexOf(n),1),e[typeof n]["delete"](n))},writable:!1,configurable:!1,enumerable:!1},clear:{value:function(){r.length=0;for(var n in e)e[n].clear();t=0},writable:!1,configurable:!1,enumerable:!1},forEach:{value:function(e,t){for(var n=0,i=r.length;n<i;n++)e.call(t,this.get(r[n]),r[n],this)},writable:!1,configurable:!1,enumerable:!1}}):(n.size=t,n.get=function(t){return e[typeof t].get(t)},n.set=function(n,i){this.has(n)||(r.push(n),this.size=++t),e[typeof n].set(n,i)},n.has=function(t){return e[typeof t].has(t)},n["delete"]=function(n){return!!this.has(n)&&(this.size=--t,r.splice(r.indexOf(n),1),e[typeof n]["delete"](n))},n.clear=function(){r.length=0;for(var n in e)e[n].clear();this.size=t=0},n.forEach=function(e,t){for(var n=0,i=r.length;n<i;n++)e.call(t,this.get(r[n]),r[n],this)}),arguments.length>0&&Array.isArray(arguments[0]))for(var o=arguments[0],a=0,u=o.length;a<u;a++)n.set(o[a][0],o[a][1]);return n}}if(!n){var p=e.Map;e.Map=function g(){var e=new p,t=0,r=[],n=Object.create(g.prototype,{size:{get:function(){return t},configurable:!1,enumerable:!1},get:{value:function(t){return e.get(t)},writable:!1,configurable:!1,enumerable:!1},set:{value:function(n,i){e.has(n)||(r.push(n),t++),e.set(n,i)},writable:!1,configurable:!1,enumerable:!1},has:{value:function(t){return e.has(t)},writable:!1,configurable:!1,enumerable:!1},"delete":{value:function(n){return!!e.has(n)&&(t--,r.splice(r.indexOf(n),1),e["delete"](n))},writable:!1,configurable:!1,enumerable:!1},clear:{value:function(){if("clear"in e)e.clear();else for(var n=0,i=r.length;n<i;n++)e["delete"](r[n]);r.length=0,t=0},writable:!1,configurable:!1,enumerable:!1},forEach:{value:function(e,t){for(var n=0,i=r.length;n<i;n++)e.call(t,this.get(r[n]),r[n],this)},writable:!1,configurable:!1,enumerable:!1}});if(arguments.length>0&&Array.isArray(arguments[0]))for(var i=arguments[0],o=0,a=i.length;o<a;o++)n.set(i[o][0],i[o][1]);return n}}}}(hprose.global),function(e,t){function r(e){Error.call(this),this.message=e,this.name=r.name,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,r)}r.prototype=e.createObject(Error.prototype),r.prototype.constructor=r,t.TimeoutError=r}(hprose,hprose.global),function(e,t){"use strict";function r(e){var r=Array.prototype.slice.call(arguments,1);return function(){e.apply(t,r)}}function n(e){delete f[e]}function i(e){var t=f[e];if(t)try{t()}finally{n(e)}}function o(e){return f[c]=r.apply(t,e),c++}if(!e.setImmediate){var a=e.document,u=e.MutationObserver||e.WebKitMutationObserver||e.MozMutationOvserver,s={},c=1,f={};s.mutationObserver=function(){var e=[],t=a.createTextNode("");return new u(function(){for(;e.length>0;)i(e.shift())}).observe(t,{characterData:!0}),function(){var r=o(arguments);return e.push(r),t.data=1&r,r}},s.messageChannel=function(){var t=new e.MessageChannel;return t.port1.onmessage=function(e){i(Number(e.data))},function(){var e=o(arguments);return t.port2.postMessage(e),e}},s.nextTick=function(){return function(){var t=o(arguments);return e.process.nextTick(r(i,t)),t}},s.postMessage=function(){var e=a.createElement("iframe");e.style.display="none",a.documentElement.appendChild(e);var t=e.contentWindow;t.document.write('<script>window.onmessage=function(){parent.postMessage(1, "*");};<\/script>'),t.document.close();var r=[];return window.addEventListener("message",function(){for(;r.length>0;)i(r.shift())}),function(){var e=o(arguments);return r.push(e),t.postMessage(1,"*"),e}},s.readyStateChange=function(){var e=a.documentElement;return function(){var t=o(arguments),r=a.createElement("script");return r.onreadystatechange=function(){i(t),r.onreadystatechange=null,e.removeChild(r),r=null},e.appendChild(r),t}};var l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,s.setTimeout=function(){return function(){var e=o(arguments);return l.setTimeout(r(i,e),0),e}},"undefined"==typeof e.process||"[object process]"!==Object.prototype.toString.call(e.process)||e.process.browser?a&&"onreadystatechange"in a.createElement("script")?l.setImmediate=s.readyStateChange():a&&u?l.setImmediate=s.mutationObserver():e.MessageChannel?l.setImmediate=s.messageChannel():l.setImmediate=a&&"postMessage"in e&&"addEventListener"in e?s.postMessage():s.setTimeout():l.setImmediate=s.nextTick(),l.clearImmediate=n}}(hprose.global),function(e,t,r){"use strict";function n(e){var t=this;Q(this,{_subscribers:{value:[]},resolve:{value:this.resolve.bind(this)},reject:{value:this.reject.bind(this)}}),"function"==typeof e&&J(function(){try{t.resolve(e())}catch(r){t.reject(r)}})}function i(e){return e instanceof n}function o(e){return i(e)?e:c(e)}function a(e){return"function"==typeof e.then}function u(e,t){var r="function"==typeof t?t:function(){return t},i=new n;return V(function(){try{i.resolve(r())}catch(e){i.reject(e)}},e),i}function s(e){var t=new n;return t.reject(e),t}function c(e){var t=new n;return t.resolve(e),t}function f(e){try{return c(e())}catch(t){return s(t)}}function l(e){var t=new n;return e(t.resolve,t.reject),t}function h(e){var t=0;return ee.call(e,function(){++t}),t}function p(e){return o(e).then(function(e){var t=e.length,r=h(e),i=new Array(t);if(0===r)return i;var a=new n;return ee.call(e,function(e,t){o(e).then(function(e){i[t]=e,0==--r&&a.resolve(i)},a.reject)}),a})}function v(){return p(arguments)}function d(e){return o(e).then(function(e){var t=new n;return ee.call(e,function(e){o(e).fill(t)}),t})}function g(e){return o(e).then(function(e){var t=e.length,r=h(e);if(0===r)throw new RangeError("any(): array must not be empty");var i=new Array(t),a=new n;return ee.call(e,function(e,t){o(e).then(a.resolve,function(e){i[t]=e,0==--r&&a.reject(i)})}),a})}function w(e){return o(e).then(function(e){var t=e.length,r=h(e),i=new Array(t);if(0===r)return i;var a=new n;return ee.call(e,function(e,t){var n=o(e);n.complete(function(){i[t]=n.inspect(),0==--r&&a.resolve(i)})}),a})}function y(e){var t=function(){return this}();return p(te.call(arguments,1)).then(function(r){return e.apply(t,r)})}function m(e,t){return p(te.call(arguments,2)).then(function(r){return e.apply(t,r)})}function b(e){return!!e&&("function"==typeof e.next&&"function"==typeof e["throw"])}function T(e){if(!e)return!1;var t=e.constructor;return!!t&&("GeneratorFunction"===t.name||"GeneratorFunction"===t.displayName||b(t.prototype))}function C(e){return function(t,n){return t instanceof Error?e.reject(t):arguments.length<2?e.resolve(t):(n=null===t||t===r?te.call(arguments,1):te.call(arguments,0),void(1==n.length?e.resolve(n[0]):e.resolve(n)))}}function E(e){if(T(e)||b(e))return O(e);var t=function(){return this}(),r=new n;return e.call(t,C(r)),r}function A(e){return function(){var t=te.call(arguments,0),r=this,i=new n;t.push(function(){r=this,i.resolve(arguments)});try{e.apply(this,t)}catch(o){i.resolve([o])}return function(e){i.then(function(t){e.apply(r,t)})}}}function k(e){return function(){var t=te.call(arguments,0),r=new n;t.push(C(r));try{e.apply(this,t)}catch(i){r.reject(i)}return r}}function S(e){return T(e)||b(e)?O(e):o(e)}function O(e){function t(t){try{i(e.next(t))}catch(r){s.reject(r)}}function r(t){try{i(e["throw"](t))}catch(r){s.reject(r)}}function i(e){e.done?s.resolve(e.value):("function"==typeof e.value?E(e.value):S(e.value)).then(t,r)}var a=function(){return this}();if("function"==typeof e){var u=te.call(arguments,1);e=e.apply(a,u)}if(!e||"function"!=typeof e.next)return o(e);var s=new n;return t(),s}function j(e,t){return function(){return t=t||this,p(arguments).then(function(r){var n=e.apply(t,r);return T(n)||b(n)?O.call(t,n):n})}}function I(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.forEach(t,r)})}function _(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.every(t,r)})}function x(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.some(t,r)})}function M(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.filter(t,r)})}function R(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.map(t,r)})}function U(e,t,r){return arguments.length>2?p(e).then(function(e){return o(r).then(function(r){return e.reduce(t,r)})}):p(e).then(function(e){return e.reduce(t)})}function L(e,t,r){return arguments.length>2?p(e).then(function(e){return o(r).then(function(r){return e.reduceRight(t,r)})}):p(e).then(function(e){return e.reduceRight(t)})}function F(e,t,r){return p(e).then(function(e){return o(t).then(function(t){return e.indexOf(t,r)})})}function P(e,t,n){return p(e).then(function(e){return o(t).then(function(t){return n===r&&(n=e.length-1),e.lastIndexOf(t,n)})})}function N(e,t,r){return p(e).then(function(e){return o(t).then(function(t){return e.includes(t,r)})})}function H(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.find(t,r)})}function D(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.findIndex(t,r)})}function W(e,t,r){J(function(){try{var n=e(r);t.resolve(n)}catch(i){t.reject(i)}})}function B(e,t,r){e?W(e,t,r):t.resolve(r)}function q(e,t,r){e?W(e,t,r):t.reject(r)}function z(){var e=new n;Q(this,{future:{value:e},complete:{value:e.resolve},completeError:{value:e.reject},isCompleted:{get:function(){return e._state!==G}}})}function X(e){n.call(this),e(this.resolve,this.reject)}var G=0,Q=e.defineProperties,Y=e.createObject,$="Promise"in t,J=t.setImmediate,V=t.setTimeout,K=t.clearTimeout,Z=t.TimeoutError,ee=Array.prototype.forEach,te=Array.prototype.slice;O.wrap=j,Q(n,{delayed:{value:u},error:{value:s},sync:{value:f},value:{value:c},all:{value:p},race:{value:d},resolve:{value:c},reject:{value:s},promise:{value:l},isFuture:{value:i},toFuture:{value:o},isPromise:{value:a},toPromise:{value:S},join:{value:v},any:{value:g},settle:{value:w},attempt:{value:y},run:{value:m},thunkify:{value:A},promisify:{value:k},co:{value:O},wrap:{value:j},forEach:{value:I},every:{value:_},some:{value:x},filter:{value:M},map:{value:R},reduce:{value:U},reduceRight:{value:L},indexOf:{value:F},lastIndexOf:{value:P},includes:{value:N},find:{value:H},findIndex:{value:D}}),Q(n.prototype,{_value:{writable:!0},_reason:{writable:!0},_state:{value:G,writable:!0},resolve:{value:function(e){if(e===this)return void this.reject(new TypeError("Self resolution"));if(i(e))return void e.fill(this);if(null!==e&&"object"==typeof e||"function"==typeof e){var t;try{t=e.then}catch(u){return void this.reject(u)}if("function"==typeof t){var r=!0;try{var n=this;return void t.call(e,function(e){r&&(r=!1,n.resolve(e))},function(e){r&&(r=!1,n.reject(e))})}catch(u){r&&(r=!1,this.reject(u))}return}}if(this._state===G){this._state=1,this._value=e;for(var o=this._subscribers;o.length>0;){var a=o.shift();B(a.onfulfill,a.next,e)}}}},reject:{value:function(e){if(this._state===G){this._state=2,this._reason=e;for(var t=this._subscribers;t.length>0;){var r=t.shift();q(r.onreject,r.next,e)}}}},then:{value:function(e,t){"function"!=typeof e&&(e=null),"function"!=typeof t&&(t=null);var r=new n;return 1===this._state?B(e,r,this._value):2===this._state?q(t,r,this._reason):this._subscribers.push({onfulfill:e,onreject:t,next:r}),r}},done:{value:function(e,t){this.then(e,t).then(null,function(e){J(function(){throw e})})}},inspect:{value:function(){switch(this._state){case G:return{state:"pending"};case 1:return{state:"fulfilled",value:this._value};case 2:return{state:"rejected",reason:this._reason}}}},catchError:{value:function(e,t){if("function"==typeof t){var r=this;return this["catch"](function(n){if(t(n))return r["catch"](e);throw n})}return this["catch"](e)}},"catch":{value:function(e){return this.then(null,e)}},fail:{value:function(e){this.done(null,e)}},whenComplete:{value:function(e){return this.then(function(t){return e(),t},function(t){throw e(),t})}},complete:{value:function(e){return e=e||function(e){return e},this.then(e,e)}},always:{value:function(e){this.done(e,e)}},fill:{value:function(e){this.then(e.resolve,e.reject)}},timeout:{value:function(e,t){var r=new n,i=V(function(){r.reject(t||new Z("timeout"))},e);return this.whenComplete(function(){K(i)}).fill(r),r}},delay:{value:function(e){var t=new n;return this.then(function(r){V(function(){t.resolve(r)},e)},t.reject),t}},tap:{value:function(e,t){return this.then(function(r){return e.call(t,r),r})}},spread:{value:function(e,t){return this.then(function(r){return e.apply(t,r)})}},get:{value:function(e){return this.then(function(t){return t[e]})}},set:{value:function(e,t){return this.then(function(r){return r[e]=t,r})}},apply:{value:function(e,t){return t=t||[],this.then(function(r){return p(t).then(function(t){return r[e].apply(r,t)})})}},call:{value:function(e){var t=te.call(arguments,1);return this.then(function(r){return p(t).then(function(t){return r[e].apply(r,t)})})}},bind:{value:function(e){var t=te.call(arguments);{if(!Array.isArray(e)){t.shift();var r=this;return Q(this,{method:{value:function(){var n=te.call(arguments);return r.then(function(r){return p(t.concat(n)).then(function(t){return r[e].apply(r,t)})})}}}),this}for(var n=0,i=e.length;n<i;++n)t[0]=e[n],this.bind.apply(this,t)}}},forEach:{value:function(e,t){return I(this,e,t)}},every:{value:function(e,t){return _(this,e,t)}},some:{value:function(e,t){return x(this,e,t)}},filter:{value:function(e,t){return M(this,e,t)}},map:{value:function(e,t){return R(this,e,t)}},reduce:{value:function(e,t){return arguments.length>1?U(this,e,t):U(this,e)}},reduceRight:{value:function(e,t){return arguments.length>1?L(this,e,t):L(this,e)}},indexOf:{value:function(e,t){return F(this,e,t)}},lastIndexOf:{value:function(e,t){return P(this,e,t)}},includes:{value:function(e,t){return N(this,e,t)}},find:{value:function(e,t){return H(this,e,t)}},findIndex:{value:function(e,t){return D(this,e,t)}}}),e.Future=n,e.thunkify=A,e.promisify=k,e.co=O,e.co.wrap=e.wrap=j,e.Completer=z,e.resolved=c,e.rejected=s,e.deferred=function(){var e=new n;return Y(null,{promise:{value:e},resolve:{value:e.resolve},reject:{value:e.reject}})},$||(X.prototype=Y(n.prototype),X.prototype.constructor=n,Q(X,{all:{value:p},race:{value:d},resolve:{value:c},reject:{value:s}}),t.Promise=X)}(hprose,hprose.global),function(e){"use strict";function t(e,t){if(t&&!/^[\x00-\xff]*$/.test(e))throw new Error("argument is not a binary string.");r(this,{length:{value:e.length},toString:{value:function(){return e}},valueOf:{value:function(){return e},writable:!0,configurable:!0,enumerable:!1}})}var r=e.defineProperties,n=e.createObject,i={};["quote","substring","toLowerCase","toUpperCase","charAt","charCodeAt","indexOf","lastIndexOf","include","startsWith","endsWith","repeat","trim","trimLeft","trimRight","toLocaleLowerCase","toLocaleUpperCase","match","search","replace","split","substr","concat","slice"].forEach(function(e){i[e]={value:String.prototype[e]}}),t.prototype=n(null,i),t.prototype.constructor=t,e.BinaryString=t,e.binary=function(e){return new t(e,!0)}}(hprose),function(e,t){"use strict";function r(e){return String.fromCharCode(e>>>24&255,e>>>16&255,e>>>8&255,255&e)}function n(e){return String.fromCharCode(255&e,e>>>8&255,e>>>16&255,e>>>24&255)}function i(e){for(var t=[],r=e.length,n=0,i=0;n<r;++n,++i){var o=e.charCodeAt(n);if(o<128)t[i]=e.charAt(n);else if(o<2048)t[i]=String.fromCharCode(192|o>>6,128|63&o);else{if(!(o<55296||o>57343)){// FIXED: if(n+1<r){var a=e.charCodeAt(n+1);if(o<56320&&56320<=a&&a<=57343){var u=65536+((1023&o)<<10|1023&a);t[i]=String.fromCharCode(240|u>>18&63,128|u>>12&63,128|u>>6&63,128|63&u),++n;continue}}throw new Error("Malformed string")}t[i]=String.fromCharCode(224|o>>12,128|o>>6&63,128|63&o)}}return t.join("")}function o(e,t){for(var r=new Array(t),n=0,i=0,o=e.length;n<t&&i<o;n++){var a=e.charCodeAt(i++);switch(a>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:r[n]=a;break;case 12:case 13:if(i<o){r[n]=(31&a)<<6|63&e.charCodeAt(i++);break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(i+1<o){r[n]=(15&a)<<12|(63&e.charCodeAt(i++))<<6|63&e.charCodeAt(i++);break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(i+2<o){var u=((7&a)<<18|(63&e.charCodeAt(i++))<<12|(63&e.charCodeAt(i++))<<6|63&e.charCodeAt(i++))-65536;if(0<=u&&u<=1048575){r[n++]=u>>10&1023|55296,r[n]=1023&u|56320;break}throw new Error("Character outside valid Unicode range: 0x"+u.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+a.toString(16))}}return n<t&&(r.length=n),[String.fromCharCode.apply(String,r),i]}function a(e,t){for(var r=[],n=new Array(32768),i=0,o=0,a=e.length;i<t&&o<a;i++){var u=e.charCodeAt(o++);switch(u>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n[i]=u;break;case 12:case 13:if(o<a){n[i]=(31&u)<<6|63&e.charCodeAt(o++);break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(o+1<a){n[i]=(15&u)<<12|(63&e.charCodeAt(o++))<<6|63&e.charCodeAt(o++);break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(o+2<a){var s=((7&u)<<18|(63&e.charCodeAt(o++))<<12|(63&e.charCodeAt(o++))<<6|63&e.charCodeAt(o++))-65536;if(0<=s&&s<=1048575){n[i++]=s>>10&1023|55296,n[i]=1023&s|56320;break}throw new Error("Character outside valid Unicode range: 0x"+s.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+u.toString(16))}if(i>=32766){var c=i+1;n.length=c,r[r.length]=String.fromCharCode.apply(String,n),t-=c,i=-1}}return i>0&&(n.length=i,r[r.length]=String.fromCharCode.apply(String,n)),[r.join(""),o]}function u(e,r){return(r===t||null===r||r<0)&&(r=e.length),0===r?["",0]:r<65535?o(e,r):a(e,r)}function s(e,r){if((r===t||null===r||r<0)&&(r=e.length),0===r)return"";for(var n=0,i=0,o=e.length;n<r&&i<o;n++){var a=e.charCodeAt(i++);switch(a>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:break;case 12:case 13:if(i<o){++i;break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(i+1<o){i+=2;break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(i+2<o){var u=((7&a)<<18|(63&e.charCodeAt(i++))<<12|(63&e.charCodeAt(i++))<<6|63&e.charCodeAt(i++))-65536;if(0<=u&&u<=1048575)break;throw new Error("Character outside valid Unicode range: 0x"+u.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+a.toString(16))}}return e.substr(0,i)}function c(e){return u(e)[0]}function f(e){for(var t=e.length,r=0,n=0;n<t;++n){var i=e.charCodeAt(n);if(i<128)++r;else if(i<2048)r+=2;else{if(!(i<55296||i>57343)){if(n+1<t){var o=e.charCodeAt(n+1);if(i<56320&&56320<=o&&o<=57343){++n,r+=4;continue}}throw new Error("Malformed string")}r+=3}}return r}function l(e){for(var t=e.length,r=0,n=0;n<t;++n,++r){var i=e.charCodeAt(n);switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:break;case 12:case 13:if(n<t){++n;break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(n+1<t){n+=2;break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(n+2<t){var o=((7&i)<<18|(63&e.charCodeAt(n++))<<12|(63&e.charCodeAt(n++))<<6|63&e.charCodeAt(n++))-65536;if(0<=o&&o<=1048575){++r;break}throw new Error("Character outside valid Unicode range: 0x"+o.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+i.toString(16))}}return r}function h(e){for(var t=0,r=e.length;t<r;++t){var n=e.charCodeAt(t);switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:break;case 12:case 13:if(t<r){++t;break}return!1;case 14:if(t+1<r){t+=2;break}return!1;case 15:if(t+2<r){var i=((7&n)<<18|(63&e.charCodeAt(t++))<<12|(63&e.charCodeAt(t++))<<6|63&e.charCodeAt(t++))-65536;if(0<=i&&i<=1048575)break}return!1;default:return!1}}return!0}function p(){var e=arguments;switch(e.length){case 1:this._buffer=[e[0].toString()];break;case 2:this._buffer=[e[0].toString().substr(e[1])];break;case 3:this._buffer=[e[0].toString().substr(e[1],e[2])];break;default:this._buffer=[""]}this.mark()}var v=e.defineProperties;v(p.prototype,{_buffer:{writable:!0},_off:{value:0,writable:!0},_wmark:{writable:!0},_rmark:{writable:!0},toString:{value:function(){return this._buffer.length>1&&(this._buffer=[this._buffer.join("")]),this._buffer[0]}},length:{get:function(){return this.toString().length}},position:{get:function(){return this._off}},mark:{value:function(){this._wmark=this.length(),this._rmark=this._off}},reset:{value:function(){this._buffer=[this.toString().substr(0,this._wmark)],this._off=this._rmark}},clear:{value:function(){this._buffer=[""],this._wmark=0,this._off=0,this._rmark=0}},writeByte:{value:function(e){this._buffer.push(String.fromCharCode(255&e))}},writeInt32BE:{value:function(e){if(e===(0|e)&&e<=2147483647)return void this._buffer.push(r(e));throw new TypeError("value is out of bounds")}},writeUInt32BE:{value:function(e){if(2147483648+(2147483647&e)===e&&e>=0)return void this._buffer.push(r(0|e));throw new TypeError("value is out of bounds")}},writeInt32LE:{value:function(e){if(e===(0|e)&&e<=2147483647)return void this._buffer.push(n(e));throw new TypeError("value is out of bounds")}},writeUInt32LE:{value:function(e){if(2147483648+(2147483647&e)===e&&e>=0)return void this._buffer.push(n(0|e));throw new TypeError("value is out of bounds")}},writeUTF16AsUTF8:{value:function(e){this._buffer.push(i(e))}},writeUTF8AsUTF16:{value:function(e){this._buffer.push(c(e))}},write:{value:function(e){this._buffer.push(e)}},readByte:{value:function(){return this._off<this.length()?this._buffer[0].charCodeAt(this._off++):-1}},readChar:{value:function(){return this._off<this.length()?this._buffer[0].charAt(this._off++):""}},readInt32BE:{value:function(){var e=this.length(),t=this._buffer[0],r=this._off;if(r+3<e){var n=t.charCodeAt(r++)<<24|t.charCodeAt(r++)<<16|t.charCodeAt(r++)<<8|t.charCodeAt(r++);return this._off=r,n}throw new Error("EOF")}},readUInt32BE:{value:function(){var e=this.readInt32BE();return e<0?2147483648+(2147483647&e):e}},readInt32LE:{value:function(){var e=this.length(),t=this._buffer[0],r=this._off;if(r+3<e){var n=t.charCodeAt(r++)|t.charCodeAt(r++)<<8|t.charCodeAt(r++)<<16|t.charCodeAt(r++)<<24;return this._off=r,n}throw new Error("EOF")}},readUInt32LE:{value:function(){var e=this.readInt32LE();return e<0?2147483648+(2147483647&e):e}},read:{value:function(e){var t=this._off,r=this.length();return t+e>r&&(e=r-t),0===e?"":(this._off=t+e,this._buffer[0].substring(t,this._off))}},skip:{value:function(e){var t=this.length();return this._off+e>t?(e=t-this._off,this._off=t):this._off+=e,e}},readString:{value:function(e){var t=this.length(),r=this._off,n=this._buffer[0],i=n.indexOf(e,r);return-1===i?(n=n.substr(r),this._off=t):(n=n.substring(r,i+1),this._off=i+1),n}},readUntil:{value:function(e){var t=this.length(),r=this._off,n=this._buffer[0],i=n.indexOf(e,r);return i===this._off?(n="",this._off++):-1===i?(n=n.substr(r),this._off=t):(n=n.substring(r,i),this._off=i+1),n}},readUTF8:{value:function(e){var t=this.length(),r=s(this._buffer[0].substring(this._off,Math.min(this._off+3*e,t)),e);return this._off+=r.length,r}},readUTF8AsUTF16:{value:function(e){var t=this.length(),r=u(this._buffer[0].substring(this._off,Math.min(this._off+3*e,t)),e);return this._off+=r[1],r[0]}},readUTF16AsUTF8:{value:function(e){return i(this.read(e))}},take:{value:function(){var e=this.toString();return this.clear(),e}},clone:{value:function(){return new p(this.toString())}},trunc:{value:function(){var e=this.toString().substring(this._off,this._length);this._buffer[0]=e,this._off=0,this._wmark=0,this._rmark=0}}}),v(p,{utf8Encode:{value:i},utf8Decode:{value:c},utf8Length:{value:f},utf16Length:{value:l},isUTF8:{value:h}}),e.StringIO=p}(hprose),function(e,t){"use strict";t.HproseTags=e.Tags={TagInteger:"i",TagLong:"l",TagDouble:"d",TagNull:"n",TagEmpty:"e",TagTrue:"t",TagFalse:"f",TagNaN:"N",TagInfinity:"I",TagDate:"D",TagTime:"T",TagUTC:"Z",TagBytes:"b",TagUTF8Char:"u",TagString:"s",TagGuid:"g",TagList:"a",TagMap:"m",TagClass:"c",TagObject:"o",TagRef:"r",TagPos:"+",TagNeg:"-",TagSemicolon:";",TagOpenbrace:"{",TagClosebrace:"}",TagQuote:'"',TagPoint:".",TagFunctions:"F",TagCall:"C",TagResult:"R",TagArgument:"A",TagError:"E",TagEnd:"z"}}(hprose,hprose.global),function(e,t){"use strict";function r(e,t){s.set(e,t),u[t]=e}function n(e){return s.get(e)}function i(e){return u[e]}var o=t.WeakMap,a=e.createObject,u=a(null),s=new o;t.HproseClassManager=e.ClassManager=a(null,{register:{value:r},getClassAlias:{value:n},getClass:{value:i}}),e.register=r,r(Object,"Object")}(hprose,hprose.global),function(e,t,r){"use strict";function n(e){var t=e.constructor;if(!t)return"Object";var r=S.getClassAlias(t);if(r)return r;if(t.name)r=t.name;else{var n=t.toString();if(""===(r=n.substr(0,n.indexOf("(")).replace(/(^\s*function\s*)|(\s*$)/gi,""))||"Object"===r)return"function"==typeof e.getClassName?e.getClassName():"Object"}return"Object"!==r&&S.register(t,r),r}function i(e){O(this,{_stream:{value:e},_ref:{value:new C,writable:!0}})}function o(e){return new i(e)}function a(e,t,r){this.binary=!!r,O(this,{stream:{value:e},_classref:{value:j(null),writable:!0},_fieldsref:{value:[],writable:!0},_refer:{value:t?_:o(e)}})}function u(e,t){var i=e.stream;if(t===r||null===t||t.constructor===Function)return void i.write(k.TagNull);if(""===t)return void i.write(k.TagEmpty);switch(t.constructor){case Number:s(e,t);break;case Boolean:l(e,t);break;case String:1===t.length?(i.write(k.TagUTF8Char),i.write(e.binary?I(t):t)):e.writeStringWithRef(t);break;case A:if(!e.binary)throw new Error("The binary string does not support serialization in text mode.");e.writeBinaryWithRef(t);break;case Date:e.writeDateWithRef(t);break;case C:e.writeMapWithRef(t);break;default:if(Array.isArray(t))e.writeListWithRef(t);else{"Object"===n(t)?e.writeMapWithRef(t):e.writeObjectWithRef(t)}}}function s(e,t){var r=e.stream;t=t.valueOf(),t===(0|t)?0<=t&&t<=9?r.write(t):(r.write(k.TagInteger),r.write(t),r.write(k.TagSemicolon)):f(e,t)}function c(e,t){var r=e.stream;0<=t&&t<=9?r.write(t):(t<-2147483648||t>2147483647?r.write(k.TagLong):r.write(k.TagInteger),r.write(t),r.write(k.TagSemicolon))}function f(e,t){var r=e.stream;t!==t?r.write(k.TagNaN):t!==Infinity&&t!==-Infinity?(r.write(k.TagDouble),r.write(t),r.write(k.TagSemicolon)):(r.write(k.TagInfinity),r.write(t>0?k.TagPos:k.TagNeg))}function l(e,t){e.stream.write(t.valueOf()?k.TagTrue:k.TagFalse)}function h(e,t){e._refer.set(t);var r=e.stream;r.write(k.TagDate),r.write(("0000"+t.getUTCFullYear()).slice(-4)),r.write(("00"+(t.getUTCMonth()+1)).slice(-2)),r.write(("00"+t.getUTCDate()).slice(-2)),r.write(k.TagTime),r.write(("00"+t.getUTCHours()).slice(-2)),r.write(("00"+t.getUTCMinutes()).slice(-2)),r.write(("00"+t.getUTCSeconds()).slice(-2));var n=t.getUTCMilliseconds();0!==n&&(r.write(k.TagPoint),r.write(("000"+n).slice(-3))),r.write(k.TagUTC)}function p(e,t){e._refer.set(t);var r=e.stream,n=("0000"+t.getFullYear()).slice(-4),i=("00"+(t.getMonth()+1)).slice(-2),o=("00"+t.getDate()).slice(-2),a=("00"+t.getHours()).slice(-2),u=("00"+t.getMinutes()).slice(-2),s=("00"+t.getSeconds()).slice(-2),c=("000"+t.getMilliseconds()).slice(-3);"00"===a&&"00"===u&&"00"===s&&"000"===c?(r.write(k.TagDate),r.write(n),r.write(i),r.write(o)):"1970"===n&&"01"===i&&"01"===o?(r.write(k.TagTime),r.write(a),r.write(u),r.write(s),"000"!==c&&(r.write(k.TagPoint),r.write(c))):(r.write(k.TagDate),r.write(n),r.write(i),r.write(o),r.write(k.TagTime),r.write(a),r.write(u),r.write(s),"000"!==c&&(r.write(k.TagPoint),r.write(c))),r.write(k.TagSemicolon)}function v(e,t){e._refer.set(t);var r=e.stream,n=("00"+t.getHours()).slice(-2),i=("00"+t.getMinutes()).slice(-2),o=("00"+t.getSeconds()).slice(-2),a=("000"+t.getMilliseconds()).slice(-3);r.write(k.TagTime),r.write(n),r.write(i),r.write(o),"000"!==a&&(r.write(k.TagPoint),r.write(a)),r.write(k.TagSemicolon)}function d(e,t){e._refer.set(t);var r=e.stream;r.write(k.TagBytes);var n=t.length;n>0?(r.write(n),r.write(k.TagQuote),r.write(t)):r.write(k.TagQuote),r.write(k.TagQuote)}function g(e,t){e._refer.set(t);var r=e.stream,n=t.length;r.write(k.TagString),n>0?(r.write(n),r.write(k.TagQuote),r.write(e.binary?I(t):t)):r.write(k.TagQuote),r.write(k.TagQuote)}function w(e,t){e._refer.set(t);var r=e.stream,n=t.length;if(r.write(k.TagList),n>0){r.write(n),r.write(k.TagOpenbrace);for(var i=0;i<n;i++)u(e,t[i])}else r.write(k.TagOpenbrace);r.write(k.TagClosebrace)}function y(e,t){e._refer.set(t);var r=e.stream,n=[];for(var i in t)t.hasOwnProperty(i)&&"function"!=typeof t[i]&&(n[n.length]=i);var o=n.length;if(r.write(k.TagMap),o>0){r.write(o),r.write(k.TagOpenbrace);for(var a=0;a<o;a++)u(e,n[a]),u(e,t[n[a]])}else r.write(k.TagOpenbrace);r.write(k.TagClosebrace)}function m(e,t){e._refer.set(t);var r=e.stream,n=t.size;r.write(k.TagMap),n>0?(r.write(n),r.write(k.TagOpenbrace),t.forEach(function(t,r){u(e,r),u(e,t)})):r.write(k.TagOpenbrace),r.write(k.TagClosebrace)}function b(e,t){var r,i,o=e.stream,a=n(t);if(a in e._classref)i=e._classref[a],r=e._fieldsref[i];else{r=[];for(var s in t)t.hasOwnProperty(s)&&"function"!=typeof t[s]&&(r[r.length]=s.toString());i=T(e,a,r)}o.write(k.TagObject),o.write(i),o.write(k.TagOpenbrace),e._refer.set(t);for(var c=r.length,f=0;f<c;f++)u(e,t[r[f]]);o.write(k.TagClosebrace)}function T(e,t,r){var n=e.stream,i=r.length;if(n.write(k.TagClass),n.write(t.length),n.write(k.TagQuote),n.write(e.binary?I(t):t),n.write(k.TagQuote),i>0){n.write(i),n.write(k.TagOpenbrace);for(var o=0;o<i;o++)g(e,r[o])}else n.write(k.TagOpenbrace);n.write(k.TagClosebrace);var a=e._fieldsref.length;return e._classref[t]=a,e._fieldsref[a]=r,a}var C=t.Map,E=e.StringIO,A=e.BinaryString,k=e.Tags,S=e.ClassManager,O=e.defineProperties,j=e.createObject,I=E.utf8Encode,_=j(null,{set:{value:function(){}},write:{value:function(){return!1}},reset:{value:function(){}}});O(i.prototype,{_refcount:{value:0,writable:!0},set:{value:function(e){this._ref.set(e,this._refcount++)}},write:{value:function(e){var t=this._ref.get(e);return t!==r&&(this._stream.write(k.TagRef),this._stream.write(t),this._stream.write(k.TagSemicolon),!0)}},reset:{value:function(){this._ref=new C,this._refcount=0}}}),O(a.prototype,{binary:{value:!1,writable:!0},serialize:{value:function(e){u(this,e)}},writeInteger:{value:function(e){c(this,e)}},writeDouble:{value:function(e){f(this,e)}},writeBoolean:{value:function(e){l(this,e)}},writeUTCDate:{value:function(e){h(this,e)}},writeUTCDateWithRef:{value:function(e){this._refer.write(e)||h(this,e)}},writeDate:{value:function(e){p(this,e)}},writeDateWithRef:{value:function(e){this._refer.write(e)||p(this,e)}},writeTime:{value:function(e){v(this,e)}},writeTimeWithRef:{value:function(e){this._refer.write(e)||v(this,e)}},writeBinary:{value:function(e){d(this,e)}},writeBinaryWithRef:{value:function(e){this._refer.write(e)||d(this,e)}},writeString:{value:function(e){g(this,e)}},writeStringWithRef:{value:function(e){this._refer.write(e)||g(this,e)}},writeList:{value:function(e){w(this,e)}},writeListWithRef:{value:function(e){this._refer.write(e)||w(this,e)}},writeMap:{value:function(e){e instanceof C?m(this,e):y(this,e)}},writeMapWithRef:{value:function(e){this._refer.write(e)||this.writeMap(e)}},writeObject:{value:function(e){b(this,e)}},writeObjectWithRef:{value:function(e){this._refer.write(e)||b(this,e)}},reset:{value:function(){this._classref=j(null),this._fieldsref.length=0,this._refer.reset()}}}),t.HproseWriter=e.Writer=a}(hprose,hprose.global),function(e,t,r){"use strict";function n(e,t){if(e&&t)throw new Error('Tag "'+t+'" expected, but "'+e+'" found in stream');if(e)throw new Error('Unexpected serialize tag "'+e+'" in stream');throw new Error("No byte found in stream")}function i(e,t){var r=new ee;return o(e,r,t),r.take()}function o(e,t,r){a(e,t,e.readChar(),r)}function a(e,t,r,i){switch(t.write(r),r){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case re.TagNull:case re.TagEmpty:case re.TagTrue:case re.TagFalse:case re.TagNaN:break;case re.TagInfinity:t.write(e.read());break;case re.TagInteger:case re.TagLong:case re.TagDouble:case re.TagRef:u(e,t);break;case re.TagDate:case re.TagTime:s(e,t);break;case re.TagUTF8Char:c(e,t,i);break;case re.TagBytes:f(e,t,i);break;case re.TagString:l(e,t,i);break;case re.TagGuid:h(e,t);break;case re.TagList:case re.TagMap:case re.TagObject:p(e,t,i);break;case re.TagClass:p(e,t,i),o(e,t,i);break;case re.TagError:o(e,t,i);break;default:n(r)}}function u(e,t){var r;do{r=e.read(),t.write(r)}while(r!==re.TagSemicolon)}function s(e,t){var r;do{r=e.read(),t.write(r)}while(r!==re.TagSemicolon&&r!==re.TagUTC)}function c(e,t,r){r?t.write(e.readUTF8(1)):t.write(e.readChar())}function f(e,t,r){if(!r)throw new Error("The binary string does not support to unserialize in text mode.");var n=e.readUntil(re.TagQuote);t.write(n),t.write(re.TagQuote);var i=0;n.length>0&&(i=parseInt(n,10)),t.write(e.read(i+1))}function l(e,t,r){var n=e.readUntil(re.TagQuote);t.write(n),t.write(re.TagQuote);var i=0;n.length>0&&(i=parseInt(n,10)),r?t.write(e.readUTF8(i+1)):t.write(e.read(i+1))}function h(e,t){t.write(e.read(38))}function p(e,t,r){var n;do{n=e.readChar(),t.write(n)}while(n!==re.TagOpenbrace);for(;(n=e.readChar())!==re.TagClosebrace;)a(e,t,n,r);t.write(n)}function v(e,t){ie(this,{stream:{value:e},binary:{value:!!t,writable:!0},readRaw:{value:function(){return i(e,this.binary)}}})}function d(){ie(this,{ref:{value:[]}})}function g(){return new d}function w(e){var n,i=t,o=e.split(".");for(n=0;n<o.length;n++)if((i=i[o[n]])===r)return null;return i}function y(e,t,r,n){if(r<t.length){e[t[r]]=n;var i=y(e,t,r+1,".");return r+1<t.length&&null===i&&(i=y(e,t,r+1,"_")),i}var o=e.join("");try{var a=w(o);return"function"==typeof a?a:null}catch(u){return null}}function m(e){var t=ne.getClass(e);if(t)return t;if("function"==typeof(t=w(e)))return ne.register(t,e),t;for(var r=[],n=e.indexOf("_");n>=0;)r[r.length]=n,n=e.indexOf("_",n+1);if(r.length>0){var i=e.split("");if(t=y(i,r,0,"."),null===t&&(t=y(i,r,0,"_")),"function"==typeof t)return ne.register(t,e),t}return t=function(){},ie(t.prototype,{getClassName:{value:function(){return e}}}),ne.register(t,e),t}function b(e,t){var r=e.readUntil(t);return 0===r.length?0:parseInt(r,10)}function T(e){var t=e.stream,r=t.readChar();switch(r){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:return C(t);case re.TagLong:return A(t);case re.TagDouble:return S(t);case re.TagNull:return null;case re.TagEmpty:return"";case re.TagTrue:return!0;case re.TagFalse:return!1;case re.TagNaN:return NaN;case re.TagInfinity:return j(t);case re.TagDate:return _(e);case re.TagTime:return M(e);case re.TagBytes:return U(e);case re.TagUTF8Char:return F(e);case re.TagString:return N(e);case re.TagGuid:return D(e);case re.TagList:return B(e);case re.TagMap:return e.useHarmonyMap?G(e):z(e);case re.TagClass:return J(e),$(e);case re.TagObject:return Y(e);case re.TagRef:return V(e);case re.TagError:throw new Error(H(e));default:n(r)}}function C(e){return b(e,re.TagSemicolon)}function E(e){var t=e.readChar();switch(t){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:return C(e);default:n(t)}}function A(e){var t=e.readUntil(re.TagSemicolon),r=parseInt(t,10);return r.toString()===t?r:t}function k(e){var t=e.readChar();switch(t){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:case re.TagLong:return A(e);default:n(t)}}function S(e){return parseFloat(e.readUntil(re.TagSemicolon))}function O(e){var t=e.readChar();switch(t){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:case re.TagLong:case re.TagDouble:return S(e);case re.TagNaN:return NaN;case re.TagInfinity:return j(e);default:n(t)}}function j(e){return e.readChar()===re.TagNeg?-Infinity:Infinity}function I(e){var t=e.readChar();switch(t){case re.TagTrue:return!0;case re.TagFalse:return!1;default:n(t)}}function _(e){var t,r=e.stream,n=parseInt(r.read(4),10),i=parseInt(r.read(2),10)-1,o=parseInt(r.read(2),10),a=r.readChar();if(a===re.TagTime){var u=parseInt(r.read(2),10),s=parseInt(r.read(2),10),c=parseInt(r.read(2),10),f=0;a=r.readChar(),a===re.TagPoint&&(f=parseInt(r.read(3),10),(a=r.readChar())>="0"&&a<="9"&&(r.skip(2),(a=r.readChar())>="0"&&a<="9"&&(r.skip(2),a=r.readChar()))),t=a===re.TagUTC?new Date(Date.UTC(n,i,o,u,s,c,f)):new Date(n,i,o,u,s,c,f)}else t=a===re.TagUTC?new Date(Date.UTC(n,i,o)):new Date(n,i,o);return e.refer.set(t),t}function x(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagDate:return _(e);case re.TagRef:return V(e);default:n(t)}}function M(e){var t,r=e.stream,n=parseInt(r.read(2),10),i=parseInt(r.read(2),10),o=parseInt(r.read(2),10),a=0,u=r.readChar();return u===re.TagPoint&&(a=parseInt(r.read(3),10),(u=r.readChar())>="0"&&u<="9"&&(r.skip(2),(u=r.readChar())>="0"&&u<="9"&&(r.skip(2),u=r.readChar()))),t=u===re.TagUTC?new Date(Date.UTC(1970,0,1,n,i,o,a)):new Date(1970,0,1,n,i,o,a),e.refer.set(t),t}function R(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagTime:return M(e);case re.TagRef:return V(e);default:n(t)}}function U(e){if(!e.binary)throw new Error("The binary string does not support to unserialize in text mode.");var t=e.stream,r=b(t,re.TagQuote),n=new te(t.read(r));return t.skip(1),e.refer.set(n),n}function L(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagEmpty:return new te("");case re.TagBytes:return U(e);case re.TagRef:return V(e);default:n(t)}}function F(e){return e.binary?e.stream.readUTF8AsUTF16(1):e.stream.read(1)}function P(e){var t,r=e.stream,n=b(r,re.TagQuote);return t=e.binary?r.readUTF8AsUTF16(n):r.read(n),r.skip(1),t}function N(e){var t=P(e);return e.refer.set(t),t}function H(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagEmpty:return"";case re.TagUTF8Char:return F(e);case re.TagString:return N(e);case re.TagRef:return V(e);default:n(t)}}function D(e){var t=e.stream;t.skip(1);var r=t.read(36);return t.skip(1),e.refer.set(r),r}function W(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagGuid:return D(e);case re.TagRef:return V(e);default:n(t)}}function B(e){var t=e.stream,r=[];e.refer.set(r);for(var n=b(t,re.TagOpenbrace),i=0;i<n;i++)r[i]=T(e);return t.skip(1),r}function q(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagList:return B(e);case re.TagRef:return V(e);default:n(t)}}function z(e){var t=e.stream,r={};e.refer.set(r);for(var n=b(t,re.TagOpenbrace),i=0;i<n;i++){var o=T(e),a=T(e);r[o]=a}return t.skip(1),r}function X(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagMap:return z(e);case re.TagRef:return V(e);default:n(t)}}function G(e){var t=e.stream,r=new Z;e.refer.set(r);for(var n=b(t,re.TagOpenbrace),i=0;i<n;i++){var o=T(e),a=T(e);r.set(o,a)}return t.skip(1),r}function Q(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagMap:return G(e);case re.TagRef:return V(e);default:n(t)}}function Y(e){var t=e.stream,r=e.classref[b(t,re.TagOpenbrace)],n=new r.classname;e.refer.set(n);for(var i=0;i<r.count;i++)n[r.fields[i]]=T(e);return t.skip(1),n}function $(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagClass:return J(e),$(e);case re.TagObject:return Y(e);case re.TagRef:return V(e);default:n(t)}}function J(e){for(var t=e.stream,r=P(e),n=b(t,re.TagOpenbrace),i=[],o=0;o<n;o++)i[o]=H(e);t.skip(1),r=m(r),e.classref.push({classname:r,count:n,fields:i})}function V(e){return e.refer.read(b(e.stream,re.TagSemicolon))}function K(e,t,r,n){v.call(this,e,n),this.useHarmonyMap=!!r,ie(this,{classref:{value:[]},refer:{value:t?ae:g()}})}var Z=t.Map,ee=e.StringIO,te=e.BinaryString,re=e.Tags,ne=e.ClassManager,ie=e.defineProperties,oe=e.createObject;e.RawReader=v;var ae=oe(null,{set:{value:function(){}},read:{value:function(){n(re.TagRef)}},reset:{value:function(){}}});ie(d.prototype,{set:{value:function(e){this.ref.push(e)}},read:{value:function(e){return this.ref[e]}},reset:{value:function(){this.ref.length=0}}}),K.prototype=oe(v.prototype),K.prototype.constructor=K,ie(K.prototype,{useHarmonyMap:{value:!1,writable:!0},checkTag:{value:function(e,t){t===r&&(t=this.stream.readChar()),t!==e&&n(t,e)}},checkTags:{value:function(e,t){if(t===r&&(t=this.stream.readChar()),e.indexOf(t)>=0)return t;n(t,e)}},unserialize:{value:function(){return T(this)}},readInteger:{value:function(){return E(this.stream)}},readLong:{value:function(){return k(this.stream)}},readDouble:{value:function(){return O(this.stream)}},readBoolean:{value:function(){return I(this.stream)}},readDateWithoutTag:{value:function(){return _(this)}},readDate:{value:function(){return x(this)}},readTimeWithoutTag:{value:function(){return M(this)}},readTime:{value:function(){return R(this)}},readBinaryWithoutTag:{value:function(){return U(this)}},readBinary:{value:function(){return L(this)}},readStringWithoutTag:{value:function(){return N(this)}},readString:{value:function(){return H(this)}},readGuidWithoutTag:{value:function(){return D(this)}},readGuid:{value:function(){return W(this)}},readListWithoutTag:{value:function(){return B(this)}},readList:{value:function(){return q(this)}},readMapWithoutTag:{value:function(){return this.useHarmonyMap?G(this):z(this)}},readMap:{value:function(){return this.useHarmonyMap?Q(this):X(this)}},readObjectWithoutTag:{value:function(){return Y(this)}},readObject:{value:function(){return $(this)}},reset:{value:function(){this.classref.length=0,this.refer.reset()}}}),t.HproseReader=e.Reader=K}(hprose,hprose.global),function(e){"use strict";function t(e,t,r){var o=new n;return new i(o,t,r).serialize(e),o.take()}function r(e,t,r,i){return e instanceof n||(e=new n(e)),new o(e,t,r,i).unserialize()}var n=e.StringIO,i=e.Writer,o=e.Reader,a=e.createObject;e.Formatter=a(null,{serialize:{value:t},unserialize:{value:r}}),e.serialize=t,e.unserialize=r}(hprose),function(e,t){"use strict";t.HproseResultMode=e.ResultMode={Normal:0,Serialized:1,Raw:2,RawWithEndTag:3},e.Normal=e.ResultMode.Normal,e.Serialized=e.ResultMode.Serialized,e.Raw=e.ResultMode.Raw,e.RawWithEndTag=e.ResultMode.RawWithEndTag}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e,t,i){function o(e,t){for(var r=0,n=Ve.length;r<n;r++)e=Ve[r].outputFilter(e,t);return e}function a(e,t){for(var r=Ve.length-1;r>=0;r--)e=Ve[r].inputFilter(e,t);return e}function g(e,t){return e=o(e,t),ut(e,t).then(function(e){if(!t.oneway)return a(e,t)})}function A(e,t){return ht.sendAndReceive(e,t).catchError(function(r){var n=O(e,t);if(null!==n)return n;throw r})}function k(e,t,r,n){at(e,t).then(r,n)}function S(){var e=Ne.length;if(e>1){var t=He+1;t>=e&&(t=0,Qe++),He=t,Pe=Ne[He]}else Qe++;typeof ht.onfailswitch===C&&ht.onfailswitch(ht)}function O(e,t){if(t.failswitch&&S(),t.idempotent&&t.retried<t.retry){var r=500*++t.retried;return t.failswitch&&(r-=500*(Ne.length-1)),r>5e3&&(r=5e3),r>0?p.delayed(r,function(){return A(e,t)}):A(e,t)}return null}function j(e){var t=[d(null)];for(var n in e){var i=e[n].split("_"),o=i.length-1;if(o>0){for(var a=t,u=0;u<o;u++){var s=i[u];a[0][s]===r&&(a[0][s]=[d(null)]),a=a[0][s]}a.push(i[o])}t.push(e[n])}return t}function I(e){k(y,{retry:ze,retried:0,idempotent:!0,failswitch:!0,timeout:qe,client:ht,userdata:{}},function(t){var r=null;try{var n=new f(t),i=new h(n,!0);switch(n.readChar()){case s.TagError:r=new Error(i.readString());break;case s.TagFunctions:var o=j(i.readList());i.checkTag(s.TagEnd),M(e,o);break;default:r=new Error("Wrong Response:\r\n"+t)}}catch(a){r=a}null!==r?et.reject(r):et.resolve(e)},et.reject)}function _(e,t){return function(){return Ke?N(e,t,Array.slice(arguments),!0):p.all(arguments).then(function(r){return N(e,t,r,!1)})}}function x(e,t,n,i,o){if(t[i]===r&&(t[i]={},typeof o!==b&&o.constructor!==Object||(o=[o]),Array.isArray(o)))for(var a=0;a<o.length;a++){var u=o[a];if(typeof u===b)t[i][u]=_(e,n+i+"_"+u);else for(var s in u)x(e,t[i],n+i+"_",s,u[s])}}function M(e,t){for(var n=0;n<t.length;n++){var i=t[n];if(typeof i===b)e[i]===r&&(e[i]=_(e,i));else for(var o in i)x(e,e,"",o,i[o])}}function R(e,t){for(var r=Math.min(e.length,t.length),n=0;n<r;++n)t[n]=e[n]}function U(e){return e?{mode:c.Normal,binary:De,byref:We,simple:Be,onsuccess:r,onerror:r,useHarmonyMap:Je,client:ht,userdata:{}}:{mode:c.Normal,binary:De,byref:We,simple:Be,timeout:qe,retry:ze,retried:0,idempotent:Xe,failswitch:Ge,oneway:!1,sync:!1,onsuccess:r,onerror:r,useHarmonyMap:Je,client:ht,userdata:{}}}function L(e,t,r,n){var i=U(n);if(t in e){var o=e[t];for(var a in o)a in i&&(i[a]=o[a])}for(var u=0,s=r.length;u<s&&typeof r[u]!==C;++u);if(u===s)return i;var c=r.splice(u,s-u);for(i.onsuccess=c[0],s=c.length,u=1;u<s;++u){var f=c[u];switch(typeof f){case C:i.onerror=f;break;case m:i.byref=f;break;case T:i.mode=f;break;case E:for(var l in f)l in i&&(i[l]=f[l])}}return i}function F(e,t,r){var n=new f;n.write(s.TagCall);var i=new l(n,r.simple,r.binary);return i.writeString(e),(t.length>0||r.byref)&&(i.reset(),i.writeList(t),r.byref&&i.writeBoolean(!0)),n}function P(e,t,r,n){return Ye?p.promise(function(i,o){$e.push({batch:n,name:e,args:t,context:r,resolve:i,reject:o})}):n?q(e,t,r):B(e,t,r)}function N(e,t,r,n){return P(t,r,L(e,t,r,n),n)}function H(e,t,r,n){try{r.onerror?r.onerror(e,t):ht.onerror&&ht.onerror(e,t),n(t)}catch(i){n(i)}}function D(e,t,r){var n=F(e,t,r);return n.write(s.TagEnd),p.promise(function(e,i){k(n.toString(),r,function(n){if(r.oneway)return void e();var o=null,a=null;try{if(r.mode===c.RawWithEndTag)o=n;else if(r.mode===c.Raw)o=n.substring(0,n.length-1);else{var u=new f(n),l=new h(u,!1,r.useHarmonyMap,r.binary),p=u.readChar();if(p===s.TagResult){if(o=r.mode===c.Serialized?l.readRaw():l.unserialize(),(p=u.readChar())===s.TagArgument){l.reset();var v=l.readList();R(v,t),p=u.readChar()}}else p===s.TagError&&(a=new Error(l.readString()),p=u.readChar());p!==s.TagEnd&&(a=new Error("Wrong Response:\r\n"+n))}}catch(d){a=d}a?i(a):e(o)},i)})}function W(e){return function(){e&&(Ye=!1,u(function(e){e.forEach(function(e){"settings"in e?Q(e.settings).then(e.resolve,e.reject):P(e.name,e.args,e.context,e.batch).then(e.resolve,e.reject)})},$e),$e=[])}}function B(e,t,r){r.sync&&(Ye=!0);var n=p.promise(function(n,i){it(e,t,r).then(function(o){try{if(r.onsuccess)try{r.onsuccess(o,t)}catch(a){r.onerror&&r.onerror(e,a),i(a)}n(o)}catch(a){i(a)}},function(t){H(e,t,r,i)})});return n.whenComplete(W(r.sync)),n}function q(e,t,r){return p.promise(function(n,i){Ze.push({args:t,name:e,context:r,resolve:n,reject:i})})}function z(e){var t={timeout:qe,binary:De,retry:ze,retried:0,idempotent:Xe,failswitch:Ge,oneway:!1,sync:!1,client:ht,userdata:{}};for(var r in e)r in t&&(t[r]=e[r]);return t}function X(e,t){var r=e.reduce(function(e,r){return r.context.binary=t.binary,e.write(F(r.name,r.args,r.context)),e},new f);return r.write(s.TagEnd),p.promise(function(n,i){k(r.toString(),t,function(r){if(t.oneway)return void n(e);var o=-1,a=new f(r),u=new h(a,!1,!1,t.binary),l=a.readChar();try{for(;l!==s.TagEnd;){var p=null,v=null,d=e[++o].context.mode;if(d>=c.Raw&&(p=new f),l===s.TagResult){if(d===c.Serialized?p=u.readRaw():d>=c.Raw?(p.write(s.TagResult),p.write(u.readRaw())):(u.useHarmonyMap=e[o].context.useHarmonyMap,u.reset(),p=u.unserialize()),(l=a.readChar())===s.TagArgument){if(d>=c.Raw)p.write(s.TagArgument),p.write(u.readRaw());else{u.reset();var g=u.readList();R(g,e[o].args)}l=a.readChar()}}else l===s.TagError&&(d>=c.Raw?(p.write(s.TagError),p.write(u.readRaw())):(u.reset(),v=new Error(u.readString())),l=a.readChar());if([s.TagEnd,s.TagResult,s.TagError].indexOf(l)<0)return void i(new Error("Wrong Response:\r\n"+r));d>=c.Raw?(d===c.RawWithEndTag&&p.write(s.TagEnd),e[o].result=p.toString()):e[o].result=p,e[o].error=v}}catch(w){return void i(w)}n(e)},i)})}function G(){Ke=!0}function Q(e){if(e=e||{},Ke=!1,Ye)return p.promise(function(t,r){$e.push({batch:!0,settings:e,resolve:t,reject:r})});if(0===Ze.length)return p.value([]);var t=z(e);t.sync&&(Ye=!0);var r=Ze;Ze=[];var n=p.promise(function(e,n){ot(r,t).then(function(t){t.forEach(function(e){if(e.error)H(e.name,e.error,e.context,e.reject);else try{if(e.context.onsuccess)try{e.context.onsuccess(e.result,e.args)}catch(t){e.context.onerror&&e.context.onerror(e.name,t),e.reject(t)}e.resolve(e.result)}catch(t){e.reject(t)}delete e.context,delete e.resolve,delete e.reject}),e(t)},function(e){r.forEach(function(t){"reject"in t&&H(t.name,e,t.context,t.reject)}),n(e)})});return n.whenComplete(W(t.sync)),n}function Y(){return Pe}function $(){return Ne}function J(e){if(typeof e===b)Ne=[e];else{if(!Array.isArray(e))return;Ne=e.slice(0),Ne.sort(function(){return Math.random()-.5})}He=0,Pe=Ne[He]}function V(){return De}function K(e){De=!!e}function Z(){return Ge}function ee(e){Ge=!!e}function te(){return Qe}function re(){return qe}function ne(e){qe="number"==typeof e?0|e:0}function ie(){return ze}function oe(e){ze="number"==typeof e?0|e:0}function ae(){return Xe}function ue(e){Xe=!!e}function se(e){nt=!!e}function ce(){return nt}function fe(){return We}function le(e){We=!!e}function he(){return Be}function pe(e){Be=!!e}function ve(){return Je}function de(e){Je=!!e}function ge(){return 0===Ve.length?null:1===Ve.length?Ve[0]:Ve.slice()}function we(e){Ve.length=0,Array.isArray(e)?e.forEach(function(e){ye(e)}):ye(e)}function ye(e){e&&"function"==typeof e.inputFilter&&"function"==typeof e.outputFilter&&Ve.push(e)}function me(e){var t=Ve.indexOf(e);return-1!==t&&(Ve.splice(t,1),!0)}function be(){return Ve}function Te(e,t,n){n===r&&(typeof t===m&&(n=t,t=!1),t||(typeof e===m?(n=e,e=!1):(e&&e.constructor===Object||Array.isArray(e))&&(t=e,e=!1)));var i=ht;return n&&(i={}),e||Pe?(e&&(Pe=e),(typeof t===b||t&&t.constructor===Object)&&(t=[t]),Array.isArray(t)?(M(i,t),et.resolve(i),i):(u(I,i),et)):new Error("You should set server uri first!")}function Ce(e,t,r){var i=arguments.length;if(i<1||typeof e!==b)throw new Error("name must be a string");if(1===i&&(t=[]),2===i&&!Array.isArray(t)){var o=[];typeof t!==C&&o.push(n),o.push(t),t=o}if(i>2){typeof r!==C&&t.push(n);for(var a=2;a<i;a++)t.push(arguments[a])}return N(ht,e,t,Ke)}function Ee(e,t){return et.then(e,t)}function Ae(e,t){if(tt[e]){var r=tt[e];if(r[t])return r[t]}return null}function ke(e,t,n,i,o){if(typeof e!==b)throw new TypeError("topic name must be a string.");if(t===r||null===t){if(typeof n!==C)throw new TypeError("callback must be a function.");t=n}if(tt[e]||(tt[e]=d(null)),typeof t===C)return i=n,n=t,void xe().then(function(t){ke(e,t,n,i,o)});if(typeof n!==C)throw new TypeError("callback must be a function.");if(p.isPromise(t))return void t.then(function(t){ke(e,t,n,i,o)});i===r&&(i=3e5);var a=Ae(e,t);if(null===a){var u=function(){N(ht,e,[t,a.handler,u,{idempotent:!0,failswitch:o,timeout:i}],!1)};a={handler:function(r){var n=Ae(e,t);if(n){if(null!==r)for(var i=n.callbacks,o=0,a=i.length;o<a;++o)try{i[o](r)}catch(s){}null!==Ae(e,t)&&u()}},callbacks:[n]},tt[e][t]=a,u()}else a.callbacks.indexOf(n)<0&&a.callbacks.push(n)}function Se(e,t,r){if(e)if(typeof r===C){var n=e[t];if(n){var i=n.callbacks,o=i.indexOf(r);o>=0&&(i[o]=i[i.length-1],i.length--),0===i.length&&delete e[t]}}else delete e[t]}function Oe(e,t,n){if(typeof e!==b)throw new TypeError("topic name must be a string.");if(t===r||null===t){if(typeof n!==C)return void delete tt[e];t=n}if(typeof t===C&&(n=t,t=null),null===t)if(null===rt){if(tt[e]){var i=tt[e];for(t in i)Se(i,t,n)}}else rt.then(function(t){Oe(e,t,n)});else p.isPromise(t)?t.then(function(t){Oe(e,t,n)}):Se(tt[e],t,n);w(tt[e])&&delete tt[e]}function je(e){return!!tt[e]}function Ie(){var e=[];for(var t in tt)e.push(t);return e}function _e(){return rt}function xe(){return null===rt&&(rt=N(ht,"#",[],!1)),rt}function Me(e){st.push(e),it=st.reduceRight(function(e,t){return function(r,n,i){return p.toPromise(t(r,n,i,e))}},D)}function Re(e){ct.push(e),ot=ct.reduceRight(function(e,t){return function(r,n){return p.toPromise(t(r,n,e))}},X)}function Ue(e){ft.push(e),at=ft.reduceRight(function(e,t){return function(r,n){return p.toPromise(t(r,n,e))}},g)}function Le(e){lt.push(e),ut=lt.reduceRight(function(e,t){return function(r,n){return p.toPromise(t(r,n,e))}},A)}function Fe(e){return Me(e),ht}var Pe,Ne=[],He=-1,De=!1,We=!1,Be=!1,qe=3e4,ze=10,Xe=!1,Ge=!1,Qe=0,Ye=!1,$e=[],Je=!1,Ve=[],Ke=!1,Ze=[],et=new p,tt=d(null),rt=null,nt=!0,it=D,ot=X,at=g,ut=A,st=[],ct=[],ft=[],lt=[],ht=this;xe.sync=!0,xe.idempotent=!0,xe.failswitch=!0;var pt=d(null,{begin:{value:G},end:{value:Q},use:{value:function(e){return Re(e),pt}}}),vt=d(null,{use:{value:function(e){return Ue(e),vt}}}),dt=d(null,{use:{value:function(e){return Le(e),dt}}});v(this,{"#":{value:xe},onerror:{value:null,writable:!0},onfailswitch:{value:null,writable:!0},uri:{get:Y},uriList:{get:$,set:J},id:{get:_e},binary:{get:V,set:K},failswitch:{get:Z,set:ee},failround:{get:te},timeout:{get:re,set:ne},retry:{get:ie,set:oe},idempotent:{get:ae,set:ue},keepAlive:{get:ce,set:se},byref:{get:fe,set:le},simple:{get:he,set:pe},useHarmonyMap:{get:ve,set:de},filter:{get:ge,set:we},addFilter:{value:ye},removeFilter:{value:me},filters:{get:be},useService:{value:Te},invoke:{value:Ce},ready:{value:Ee},subscribe:{value:ke},unsubscribe:{value:Oe},isSubscribed:{value:je},subscribedList:{value:Ie},use:{value:Fe},batch:{value:pt},beforeFilter:{value:vt},afterFilter:{value:dt}}),i&&typeof i===E&&["failswitch","timeout","retry","idempotent","keepAlive","byref","simple","useHarmonyMap","filter","binary"].forEach(function(e){e in i&&ht[e](i[e])}),e&&(J(e),Te(t))}function o(e){var t=g(e),r=t.protocol;if("http:"!==r&&"https:"!==r&&"tcp:"!==r&&"tcp4:"!==r&&"tcp6:"!==r&&"tcps:"!==r&&"tcp4s:"!==r&&"tcp6s:"!==r&&"tls:"!==r&&"ws:"!==r&&"wss:"!==r)throw new Error("The "+r+" client isn't implemented.")}function a(t,r,n){try{return e.HttpClient.create(t,r,n)}catch(i){}try{return e.TcpClient.create(t,r,n)}catch(i){}try{return e.WebSocketClient.create(t,r,n)}catch(i){}if("string"==typeof t)o(t);else if(Array.isArray(t))throw t.forEach(function(e){o(e)}),new Error("Not support multiple protocol.");throw new Error("You should set server uri first!")}var u=t.setImmediate,s=e.Tags,c=e.ResultMode,f=e.StringIO,l=e.Writer,h=e.Reader,p=e.Future,v=e.defineProperties,d=e.createObject,g=e.parseuri,w=e.isObjectEmpty,y=s.TagEnd,m="boolean",b="string",T="number",C="function",E="object";v(i,{create:{value:a}}),t.HproseClient=e.Client=i}(hprose,hprose.global),function(e){"use strict";function t(){if(!navigator)return 0;var t="application/x-shockwave-flash",r=navigator.plugins,n=navigator.mimeTypes,i=0,o=!1;if(r&&r["Shockwave Flash"])!(i=r["Shockwave Flash"].description)||n&&n[t]&&!n[t].enabledPlugin||(i=i.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),i=parseInt(i.replace(/^(.*)\..*$/,"$1"),10));else if(e.ActiveXObject)try{o=!0;var a=new e.ActiveXObject("ShockwaveFlash.ShockwaveFlash");a&&(i=a.GetVariable("$version"))&&(i=i.split(" ")[1].split(","),i=parseInt(i[0],10))}catch(u){}return i<10?0:o?1:2}function r(){var e=t();if(h=e>0){var r=i.createElement("div");r.style.width=0,r.style.height=0,r.innerHTML=1===e?["<object ",'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ','type="application/x-shockwave-flash" ','width="0" height="0" id="',l,'" name="',l,'">','<param name="movie" value="',a,"FlashHttpRequest.swf?",+new Date,'" />','<param name="allowScriptAccess" value="always" />','<param name="quality" value="high" />','<param name="wmode" value="opaque" />',"</object>"].join(""):'<embed id="'+l+'" src="'+a+"FlashHttpRequest.swf?"+ +new Date+'" type="application/x-shockwave-flash" width="0" height="0" name="'+l+'" allowScriptAccess="always" />',i.documentElement.appendChild(r)}}function n(e,t,r,n,i,o){r=encodeURIComponent(r),y?p.post(e,t,r,n,i,o):g.push(function(){p.post(e,t,r,n,i,o)})}if("undefined"==typeof e.document)return void(e.FlashHttpRequest={flashSupport:function(){return!1}});var i=e.document,o=i.getElementsByTagName("script"),a=o.length>0&&o[o.length-1].getAttribute("flashpath")||e.hproseFlashPath||"";o=null;var u=e.location!==undefined&&"file:"===e.location.protocol,s=e.XMLHttpRequest,c=void 0!==s,f=!u&&c&&"withCredentials"in new s,l="flashhttprequest_as3",h=!1,p=null,v=[],d=[],g=[],w=!1,y=!1,m={};m.flashSupport=function(){return h},m.post=function(e,t,r,i,o,a){var u=-1;i&&(u=v.length,v[u]=i),w?n(e,t,r,u,o,a):d.push(function(){n(e,t,r,u,o,a)})},m.__callback=function(e,t,r){t=null!==t?decodeURIComponent(t):null,r=null!==r?decodeURIComponent(r):null,"function"==typeof v[e]&&v[e](t,r),delete v[e]},m.__jsReady=function(){return w},m.__setSwfReady=function(){for(p=-1!==navigator.appName.indexOf("Microsoft")?e[l]:i[l],y=!0,e.__flash__removeCallback=function(e,t){try{e&&(e[t]=null)}catch(r){}};g.length>0;){var t=g.shift();"function"==typeof t&&t()}},e.FlashHttpRequest=m,function(){if(!w)for(u||f||r(),w=!0;d.length>0;){var e=d.shift();"function"==typeof e&&e()}}()}(hprose.global),function(e){"use strict";function t(e,t){function r(e){var t,r,n;for(t=e.replace(/(^\s*)|(\s*$)/g,"").split(";"),r={},e=t[0].replace(/(^\s*)|(\s*$)/g,"").split("=",2),e[1]===undefined&&(e[1]=null),r.name=e[0],r.value=e[1],n=1;n<t.length;n++)e=t[n].replace(/(^\s*)|(\s*$)/g,"").split("=",2),e[1]===undefined&&(e[1]=null),r[e[0].toUpperCase()]=e[1];r.PATH?('"'===r.PATH.charAt(0)&&(r.PATH=r.PATH.substr(1)),'"'===r.PATH.charAt(r.PATH.length-1)&&(r.PATH=r.PATH.substr(0,r.PATH.length-1))):r.PATH="/",r.EXPIRES&&(r.EXPIRES=Date.parse(r.EXPIRES)),r.DOMAIN?r.DOMAIN=r.DOMAIN.toLowerCase():r.DOMAIN=s,r.SECURE=r.SECURE!==undefined,i[r.DOMAIN]===undefined&&(i[r.DOMAIN]={}),i[r.DOMAIN][r.name]=r}var o,a,u=n(t),s=u.host;for(o in e)a=e[o],"set-cookie"!==(o=o.toLowerCase())&&"set-cookie2"!==o||("string"==typeof a&&(a=[a]),a.forEach(r))}function r(e){var t=n(e),r=t.host,o=t.path,a="https:"===t.protocol,u=[];for(var s in i)if(r.indexOf(s)>-1){var c=[];for(var f in i[s]){var l=i[s][f];l.EXPIRES&&(new Date).getTime()>l.EXPIRES?c.push(f):0===o.indexOf(l.PATH)&&(a&&l.SECURE||!l.SECURE)&&null!==l.value&&u.push(l.name+"="+l.value)}for(var h in c)delete i[s][c[h]]}return u.length>0?u.join("; "):""}var n=e.parseuri,i={};e.cookieManager={setCookie:t,getCookie:r}}(hprose),function(e,t,r){"use strict";function n(){if(null!==S)return new k(S);for(var e=["MSXML2.XMLHTTP","MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MsXML2.XMLHTTP.2.6","Microsoft.XMLHTTP","Microsoft.XMLHTTP.1.0","Microsoft.XMLHTTP.1"],t=e.length,r=0;r<t;r++)try{var n=new k(e[r]);return S=e[r],n}catch(i){}throw new Error("Could not find an installed XML parser")}function i(){if(E)return new b;if(k)return n();throw new Error("XMLHttpRequest is not supported by this browser.")}function o(){}function a(e){var t=h(null);if(e){e=e.split("\r\n");for(var r=0,n=e.length;r<n;r++)if(""!==e[r]){var i=e[r].split(": ",2),o=i[0].trim(),a=i[1].trim();o in t?Array.isArray(t[o])?t[o].push(a):t[o]=[t[o],a]:t[o]=a}}return t}function u(e,n,s){function c(e){var t,r,n=h(null);for(t in I)n[t]=I[t];if(e)for(t in e)r=e[t],Array.isArray(r)?n[t]=r.join(", "):n[t]=r;return n}function d(e,t){var r=new l,n=i();n.open("POST",_.uri(),!0),A&&(n.withCredentials="true");var u=c(t.httpHeader);for(var s in u)n.setRequestHeader(s,u[s]);return t.binary||n.setRequestHeader("Content-Type","text/plain; charset=UTF-8"),n.onreadystatechange=function(){if(4===n.readyState&&(n.onreadystatechange=o,n.status)){var e=n.getAllResponseHeaders();t.httpHeader=a(e),200===n.status?t.binary?r.resolve(v(n.response)):r.resolve(n.responseText):r.reject(new Error(n.status+":"+n.statusText))}},n.onerror=function(){r.reject(new Error("error"))},t.timeout>0&&(r=r.timeout(t.timeout).catchError(function(e){throw n.onreadystatechange=o,n.onerror=o,n.abort(),e},function(e){return e instanceof y})),t.binary?(n.responseType="arraybuffer",n.sendAsBinary(e)):n.send(e),r}function b(e,t){var r=new l,n=function(e,n){t.httpHeader=h(null),null===n?r.resolve(e):r.reject(new Error(n))},i=c(t.httpHeader);return m.post(_.uri(),i,e,n,t.timeout,t.binary),r}function E(e,r){var n=new l,i=c(r.httpHeader),o=w.getCookie(_.uri());return""!==o&&(i.Cookie=o),t.api.ajax({url:_.uri(),method:"post",data:{body:e},timeout:r.timeout,dataType:"text",headers:i,returnAll:!0,certificate:_.certificate},function(e,t){e?(r.httpHeader=e.headers,200===e.statusCode?(w.setCookie(e.headers,_.uri()),n.resolve(e.body)):n.reject(new Error(e.statusCode+":"+e.body))):n.reject(new Error(t.msg))}),n}function k(e,t){var r=new l,n=T.mm("do_Http");n.method="POST",n.timeout=t.timeout,n.contentType="text/plain; charset=UTF-8",n.url=_.uri(),n.body=e;var i=c(t.httpHeader);for(var o in i)n.setRequestHeader(o,i[o]);var a=w.getCookie(_.uri());return""!==a&&n.setRequestHeader("Cookie",a),n.on("success",function(e){var t=n.getResponseHeader("set-cookie");t&&w.setCookie({"set-cookie":t},_.uri()),r.resolve(e)}),n.on("fail",function(e){r.reject(new Error(e.status+":"+e.data))}),n.request(),t.httpHeader=h(null),r}function S(){if(t.location===r)return!0;var e=g(_.uri());return e.protocol!==t.location.protocol||e.host!==t.location.host}function O(e,r){var n=m.flashSupport()&&!C&&!A&&(r.binary||S()),i="undefined"!=typeof t.api&&"undefined"!=typeof t.api.ajax,o=n?b(e,r):i?E(e,r):T?k(e,r):d(e,r);return r.oneway&&o.resolve(),o}function j(e,t){"content-type"!==e.toLowerCase()&&(t?I[e]=t:delete I[e])}if(this.constructor!==u)return new u(e,n,s);f.call(this,e,n,s);var I=h(null),_=this;p(this,{certificate:{value:null,writable:!0},setHeader:{value:j},sendAndReceive:{value:O}})}function s(e){var t=g(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error("This client desn't support "+t.protocol+" scheme.")}function c(e,t,r){if("string"==typeof e)s(e);else{if(!Array.isArray(e))throw new Error("You should set server uri first!");e.forEach(function(e){s(e)})}return new u(e,t,r)}var f=e.Client,l=e.Future,h=e.createObject,p=e.defineProperties,v=e.toBinaryString,d=e.toUint8Array,g=e.parseuri,w=e.cookieManager,y=t.TimeoutError,m=t.FlashHttpRequest,b=t.XMLHttpRequest;t.plus&&t.plus.net&&t.plus.net.XMLHttpRequest?b=t.plus.net.XMLHttpRequest:t.document&&t.document.addEventListener&&t.document.addEventListener("plusready",function(){b=t.plus.net.XMLHttpRequest},!1);var T;try{T=t.require("deviceone")}catch(O){}var C=t.location!==r&&"file:"===t.location.protocol,E=void 0!==b,A=!C&&E&&"withCredentials"in new b,k=t.ActiveXObject,S=null;E&&"undefined"!=typeof Uint8Array&&!b.prototype.sendAsBinary&&(b.prototype.sendAsBinary=function(e){var t=d(e);this.send(ArrayBuffer.isView?t:t.buffer)}),p(u,{create:{value:c}}),t.HproseHttpClient=e.HttpClient=u}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e,t,o){function a(){return C<2147483647?++C:C=0}function v(e,t){var r=new u;r.writeInt32BE(e),k[e].binary?r.write(t):r.writeUTF16AsUTF8(t);var n=p(r.take());ArrayBuffer.isView?j.send(n):j.send(n.buffer)}function g(e){O.resolve(e)}function w(e){var t;t=new u("string"==typeof e.data?u.utf8Encode(e.data):h(e.data));var n=t.readInt32BE(),i=A[n],o=k[n];if(delete A[n],delete k[n],i!==r){--E;var a=t.read(t.length()-4);o.binary||(a=u.utf8Decode(a)),i.resolve(a)}if(E<100&&S.length>0){++E;var s=S.pop();O.then(function(){v(s[0],s[1])})}0!==E||I.keepAlive()||T()}function y(e){A.forEach(function(t,r){t.reject(new Error(e.code+":"+e.reason)),delete A[r]}),E=0,j=null}function m(){O=new c,j=new d(I.uri()),j.binaryType="arraybuffer",j.onopen=g,j.onmessage=w,j.onerror=n,j.onclose=y}function b(e,t){var r=a(),n=new c;return A[r]=n,k[r]=t,t.timeout>0&&(n=n.timeout(t.timeout).catchError(function(e){throw delete A[r],--E,T(),e},function(e){return e instanceof f})),null!==j&&j.readyState!==d.CLOSING&&j.readyState!==d.CLOSED||m(),E<100?(++E,O.then(function(){v(r,e)})):S.push([r,e]),t.oneway&&n.resolve(),n}function T(){null!==j&&(j.onopen=n,j.onmessage=n,j.onclose=n,j.close())}if(void 0===d)throw new Error("WebSocket is not supported by this browser.");if(this.constructor!==i)return new i(e,t,o);s.call(this,e,t,o);var C=0,E=0,A=[],k=[],S=[],O=null,j=null,I=this;l(this,{sendAndReceive:{value:b},close:{value:T}})}function o(e){var t=v(e);if("ws:"!==t.protocol&&"wss:"!==t.protocol)throw new Error("This client desn't support "+t.protocol+" scheme.")}function a(e,t,r){if("string"==typeof e)o(e);else{if(!Array.isArray(e))throw new Error("You should set server uri first!");e.forEach(function(e){o(e)})}return new i(e,t,r)}var u=e.StringIO,s=e.Client,c=e.Future,f=t.TimeoutError,l=e.defineProperties,h=e.toBinaryString,p=e.toUint8Array,v=e.parseuri,d=t.WebSocket||t.MozWebSocket;l(i,{create:{value:a}}),t.HproseWebSocketClient=e.WebSocketClient=i}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e){l[e.socketId].onreceive(f(e.data))}function o(e){var t=l[e.socketId];t.onerror(e.resultCode),t.destroy()}function a(){null===h&&(h=t.chrome.sockets.tcp,h.onReceive.addListener(i),h.onReceiveError.addListener(o)),this.socketId=new u,this.connected=!1,this.timeid=r,this.onclose=n,this.onconnect=n,this.onreceive=n,this.onerror=n}var u=e.Future,s=e.defineProperties,c=e.toUint8Array,f=e.toBinaryString,l={},h=null;s(a.prototype,{connect:{value:function(e,t,r){var n=this;h.create({persistent:r&&r.persistent},function(i){r&&("noDelay"in r&&h.setNoDelay(i.socketId,r.noDelay,function(e){e<0&&(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose())}),"keepAlive"in r&&h.setKeepAlive(i.socketId,r.keepAlive,function(e){e<0&&(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose())})),r&&r.tls?h.setPaused(i.socketId,!0,function(){h.connect(i.socketId,e,t,function(e){e<0?(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose()):h.secure(i.socketId,function(t){0!==t?(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose()):h.setPaused(i.socketId,!1,function(){n.socketId.resolve(i.socketId)})})})}):h.connect(i.socketId,e,t,function(e){e<0?(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose()):n.socketId.resolve(i.socketId)})}),this.socketId.then(function(e){l[e]=n,n.connected=!0,n.onconnect(e)},function(e){n.onerror(e)})}},send:{value:function(e){e=c(e).buffer;var t=this,r=new u;return this.socketId.then(function(n){h.send(n,e,function(e){e.resultCode<0?(t.onerror(e.resultCode),r.reject(e.resultCode),t.destroy()):r.resolve(e.bytesSent)})}),r}},destroy:{value:function(){var e=this;this.connected=!1,this.socketId.then(function(t){h.disconnect(t),h.close(t),delete l[t],e.onclose()})}},ref:{value:function(){this.socketId.then(function(e){h.setPaused(e,!1)})}},unref:{value:function(){this.socketId.then(function(e){h.setPaused(e,!0)})}},clearTimeout:{value:function(){this.timeid!==r&&t.clearTimeout(this.timeid)}},setTimeout:{value:function(e,r){this.clearTimeout(),this.timeid=t.setTimeout(r,e)}}}),e.ChromeTcpSocket=a}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(){null===f&&(f=t.api.require("socketManager")),this.socketId=new o,this.connected=!1,this.timeid=r,this.onclose=n,this.onconnect=n,this.onreceive=n,this.onerror=n}var o=e.Future,a=e.defineProperties,u=t.atob,s=t.btoa,c={},f=null;a(i.prototype,{connect:{value:function(e,t,r){var n=this;f.createSocket({type:"tcp",host:e,port:t,timeout:r.timeout,returnBase64:!0},function(e){if(e)switch(e.state){case 101:break;case 102:n.socketId.resolve(e.sid);break;case 103:n.onreceive(u(e.data.replace(/\s+/g,"")));break;case 201:n.socketId.reject(new Error("Create TCP socket failed"));break;case 202:n.socketId.reject(new Error("TCP connection failed"));break;case 203:n.onclose(),n.onerror(new Error("Abnormal disconnect connection"));break;case 204:n.onclose();break;case 205:n.onclose(),n.onerror(new Error("Unknown error"))}}),this.socketId.then(function(e){c[e]=n,n.connected=!0,n.onconnect(e)},function(e){n.onerror(e)})}},send:{value:function(e){var t=this,r=new o;return this.socketId.then(function(n){f.write({sid:n,data:s(e),base64:!0},function(e,n){e.status?r.resolve():(t.onerror(new Error(n.msg)),r.reject(n.msg),t.destroy())})}),r}},destroy:{value:function(){var e=this;this.connected=!1,this.socketId.then(function(t){f.closeSocket({sid:t},function(t,r){t.status||e.onerror(new Error(r.msg))}),delete c[t]})}},ref:{value:n},unref:{value:n},clearTimeout:{value:function(){this.timeid!==r&&t.clearTimeout(this.timeid)}},setTimeout:{value:function(e,r){this.clearTimeout(),this.timeid=t.setTimeout(r,e)}}}),e.APICloudTcpSocket=i}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e,t){e.onreceive=function(r){"receiveEntry"in e||(e.receiveEntry={stream:new d,headerLength:4,dataLength:-1,id:null});var n=e.receiveEntry,i=n.stream,o=n.headerLength,a=n.dataLength,u=n.id;for(i.write(r);;){if(a<0&&i.length()>=o&&0!=(2147483648&(a=i.readInt32BE()))&&(a&=2147483647,o=8),8===o&&null===u&&i.length()>=o&&(u=i.readInt32BE()),!(a>=0&&i.length()-o>=a))break;t(i.read(a),u),o=4,u=null,i.trunc(),a=-1}n.stream=i,n.headerLength=o,n.dataLength=a,n.id=u}}function o(e){e&&(this.client=e,this.uri=this.client.uri(),this.size=0,this.pool=[],this.requests=[])}function a(e){o.call(this,e)}function u(e){o.call(this,e)}function s(e,t,r){function n(){return m}function i(e){m=!!e}function o(){return b}function c(e){b=!!e}function f(){return T}function l(e){"number"==typeof e?(T=0|e)<1&&(T=10):T=10}function h(){return C}function p(e){C="number"==typeof e?0|e:0}function d(e,t){var r=new g;return b?(null!==E&&E.uri===w.uri||(E=new a(w)),E.sendAndReceive(e,r,t)):(null!==A&&A.uri===w.uri||(A=new u(w)),A.sendAndReceive(e,r,t)),t.oneway&&r.resolve(),r}if(this.constructor!==s)return new s(e,t,r);v.call(this,e,t,r);var w=this,m=!0,b=!1,T=10,C=3e4,E=null,A=null;y(this,{noDelay:{get:n,set:i},fullDuplex:{get:o,set:c},maxPoolSize:{get:f,set:l},poolTimeout:{get:h,set:p},sendAndReceive:{value:d}})}function c(e){var t=m(e),r=t.protocol;if("tcp:"!==r&&"tcp4:"!==r&&"tcp6:"!==r&&"tcps:"!==r&&"tcp4s:"!==r&&"tcp6s:"!==r&&"tls:"!==r)throw new Error("This client desn't support "+r+" scheme.")}function f(e,t,r){if("string"==typeof e)c(e);else{if(!Array.isArray(e))throw new Error("You should set server uri first!");e.forEach(function(e){c(e)})}return new s(e,t,r)}var l=t.TimeoutError,h=e.ChromeTcpSocket,p=e.APICloudTcpSocket,v=e.Client,d=e.StringIO,g=e.Future,w=e.createObject,y=e.defineProperties,m=e.parseuri;y(o.prototype,{create:{value:function(){var e,r=m(this.uri),n=r.protocol,i=r.hostname,o=parseInt(r.port,10);if("tcp:"===n||"tcp4:"===n||"tcp6:"===n)e=!1;else{if("tcps:"!==n&&"tcp4s:"!==n&&"tcp6s:"!==n&&"tls:"!==n)throw new Error("Unsupported "+n+" protocol!");e=!0}var a;if(t.chrome&&t.chrome.sockets&&t.chrome.sockets.tcp)a=new h;else{if(!t.api||!t.api.require)throw new Error("TCP Socket is not supported by this browser or platform.");a=new p}var u=this;return a.connect(i,o,{persistent:!0,tls:e,timeout:this.client.timeout(),noDelay:this.client.noDelay(),keepAlive:this.client.keepAlive()}),a.onclose=function(){--u.size},++this.size,a}}}),a.prototype=w(o.prototype,{fetch:{value:function(){for(var e=this.pool;e.length>0;){var t=e.pop();if(t.connected)return 0===t.count&&(t.clearTimeout(),t.ref()),t}return null}},init:{value:function(e){var t=this;e.count=0,e.futures={},e.contexts={},e.timeoutIds={},i(e,function(r,n){var i=e.futures[n],o=e.contexts[n];i&&(t.clean(e,n),0===e.count&&t.recycle(e),o.binary||(r=d.utf8Decode(r)),i.resolve(r))}),e.onerror=function(r){var n=e.futures;for(var i in n){var o=n[i];t.clean(e,i),o.reject(r)}}}},recycle:{value:function(e){e.unref(),e.setTimeout(this.client.poolTimeout(),function(){e.destroy()})}},clean:{value:function(e,r){void 0!==e.timeoutIds[r]&&(t.clearTimeout(e.timeoutIds[r]),delete e.timeoutIds[r]),delete e.futures[r],delete e.contexts[r],--e.count,this.sendNext(e)}},sendNext:{value:function(e){if(e.count<10)if(this.requests.length>0){var t=this.requests.pop();t.push(e),this.send.apply(this,t)}else this.pool.lastIndexOf(e)<0&&this.pool.push(e)}},send:{value:function(e,r,n,i,o){var a=this,u=i.timeout;u>0&&(o.timeoutIds[n]=t.setTimeout(function(){a.clean(o,n),0===o.count&&a.recycle(o),r.reject(new l("timeout"))},u)),o.count++,o.futures[n]=r,o.contexts[n]=i;var s=e.length,c=new d;c.writeInt32BE(2147483648|s),c.writeInt32BE(n),i.binary?c.write(e):c.writeUTF16AsUTF8(e),o.send(c.take()).then(function(){a.sendNext(o)})}},getNextId:{value:function(){return this.nextid<2147483647?++this.nextid:this.nextid=0}},sendAndReceive:{value:function(e,t,r){var n=this.fetch(),i=this.getNextId();if(n)this.send(e,t,i,r,n);else if(this.size<this.client.maxPoolSize()){n=this.create(),n.onerror=function(e){t.reject(e)};var o=this;n.onconnect=function(){o.init(n),o.send(e,t,i,r,n)}}else this.requests.push([e,t,i,r])}}}),a.prototype.constructor=o,u.prototype=w(o.prototype,{fetch:{value:function(){for(var e=this.pool;e.length>0;){var t=e.pop();if(t.connected)return t.clearTimeout(),t.ref(),t}return null}},recycle:{value:function(e){this.pool.lastIndexOf(e)<0&&(e.unref(),e.setTimeout(this.client.poolTimeout(),function(){e.destroy()}),this.pool.push(e))}},clean:{value:function(e){e.onreceive=n,e.onerror=n,void 0!==e.timeoutId&&(t.clearTimeout(e.timeoutId),delete e.timeoutId)}},sendNext:{value:function(e){if(this.requests.length>0){var t=this.requests.pop();t.push(e),this.send.apply(this,t)}else this.recycle(e)}},send:{value:function(e,r,n,o){var a=this,u=n.timeout;u>0&&(o.timeoutId=t.setTimeout(function(){a.clean(o),o.destroy(),r.reject(new l("timeout"))},u)),i(o,function(e){a.clean(o),a.sendNext(o),n.binary||(e=d.utf8Decode(e)),r.resolve(e)}),o.onerror=function(e){a.clean(o),r.reject(e)};var s=e.length,c=new d;c.writeInt32BE(s),n.binary?c.write(e):c.writeUTF16AsUTF8(e),o.send(c.take())}},sendAndReceive:{value:function(e,t,r){var n=this.fetch();if(n)this.send(e,t,r,n);else if(this.size<this.client.maxPoolSize()){n=this.create();var i=this;n.onerror=function(e){t.reject(e)},n.onconnect=function(){i.send(e,t,r,n)}}else this.requests.push([e,t,r])}}}),u.prototype.constructor=o,y(s,{create:{value:f}}),t.HproseTcpClient=e.TcpClient=s}(hprose,hprose.global),function(e){"use strict";function t(e){this.version=e||"2.0"}var r=e.Tags,n=e.StringIO,i=e.Writer,o=e.Reader,a=1;t.prototype.inputFilter=function(e){"{"===e.charAt(0)&&(e="["+e+"]");for(var t=JSON.parse(e),o=new n,a=new i(o,!0),u=0,s=t.length;u<s;++u){var c=t[u];c.error?(o.write(r.TagError),a.writeString(c.error.message)):(o.write(r.TagResult),a.serialize(c.result))}return o.write(r.TagEnd),o.take()},t.prototype.outputFilter=function(e){var t=[],i=new n(e),u=new o(i,!1,!1),s=i.readChar();do{var c={};s===r.TagCall&&(c.method=u.readString(),s=i.readChar(),s===r.TagList&&(c.params=u.readListWithoutTag(),s=i.readChar()),s===r.TagTrue&&(s=i.readChar())),"1.1"===this.version?c.version="1.1":"2.0"===this.version&&(c.jsonrpc="2.0"),c.id=a++,t.push(c)}while(s===r.TagCall);return t.length>1?JSON.stringify(t):JSON.stringify(t[0])},e.JSONRPCClientFilter=t}(hprose),function(e){"use strict";e.common={Completer:e.Completer,Future:e.Future,ResultMode:e.ResultMode},e.io={StringIO:e.StringIO,ClassManager:e.ClassManager,Tags:e.Tags,RawReader:e.RawReader,Reader:e.Reader,Writer:e.Writer,Formatter:e.Formatter},e.client={Client:e.Client,HttpClient:e.HttpClient,TcpClient:e.TcpClient,WebSocketClient:e.WebSocketClient},e.filter={JSONRPCClientFilter:e.JSONRPCClientFilter},"function"==typeof define&&(define.cmd?define("hprose",[],e):define.amd&&define("hprose",[],function(){return e})),"object"==typeof module&&(module.exports=e)}(hprose),function(e){"use strict";function t(e,t,r,i){var o=t&&t.prototype instanceof n?t:n,a=Object.create(o.prototype),u=new h(i||[]);return a._invoke=c(e,r,u),a}function r(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(n){return{type:"throw",arg:n}}}function n(){}function i(){}function o(){}function a(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function u(e){this.arg=e}function s(e){function t(n,i,o,a){var s=r(e[n],e,i);if("throw"!==s.type){var c=s.arg,f=c.value;return f instanceof u?Promise.resolve(f.arg).then(function(e){t("next",e,o,a)},function(e){t("throw",e,o,a)}):Promise.resolve(f).then(function(e){c.value=e,o(c)},a)}a(s.arg)}function n(e,r){function n(){return new Promise(function(n,i){t(e,r,n,i)})}return i=i?i.then(n,n):n()}"object"==typeof process&&process.domain&&(t=process.domain.bind(t));var i;this._invoke=n}function c(e,t,n){var i=C;return function(o,a){if(i===A)throw new Error("Generator is already running");if(i===k){if("throw"===o)throw a;return v()}for(;;){var u=n.delegate;if(u){if("return"===o||"throw"===o&&u.iterator[o]===d){n.delegate=null;var s=u.iterator["return"];if(s){var c=r(s,u.iterator,a);if("throw"===c.type){o="throw",a=c.arg;continue}}if("return"===o)continue}var c=r(u.iterator[o],u.iterator,a);if("throw"===c.type){n.delegate=null,o="throw",a=c.arg;continue}o="next",a=d;var f=c.arg;if(!f.done)return i=E,f;n[u.resultName]=f.value,n.next=u.nextLoc,n.delegate=null}if("next"===o)n.sent=n._sent=a;else if("throw"===o){if(i===C)throw i=k,a;n.dispatchException(a)&&(o="next",a=d)}else"return"===o&&n.abrupt("return",a);i=A;var c=r(e,t,n);if("normal"===c.type){i=n.done?k:E;var f={value:c.arg,done:n.done};if(c.arg!==S)return f;n.delegate&&"next"===o&&(a=d)}else"throw"===c.type&&(i=k,o="throw",a=c.arg)}}}function f(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function l(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function h(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(f,this),this.reset(!0)}function p(e){if(e){var t=e[y];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,n=function i(){for(;++r<e.length;)if(g.call(e,r))return i.value=e[r],i.done=!1,i;return i.value=d,i.done=!0,i};return n.next=n}}return{next:v}}function v(){return{value:d,done:!0}}var d,g=Object.prototype.hasOwnProperty,w="function"==typeof Symbol?Symbol:{},y=w.iterator||"@@iterator",m=w.toStringTag||"@@toStringTag",b="object"==typeof module,T=e.regeneratorRuntime;if(T)return void(b&&(module.exports=T));T=e.regeneratorRuntime=b?module.exports:{},T.wrap=t;var C="suspendedStart",E="suspendedYield",A="executing",k="completed",S={},O=o.prototype=n.prototype;i.prototype=O.constructor=o,o.constructor=i,o[m]=i.displayName="GeneratorFunction",T.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===i||"GeneratorFunction"===(t.displayName||t.name))},T.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,o):(e.__proto__=o,m in e||(e[m]="GeneratorFunction")),e.prototype=Object.create(O),e},T.awrap=function(e){return new u(e)},a(s.prototype),T.async=function(e,r,n,i){var o=new s(t(e,r,n,i));return T.isGeneratorFunction(r)?o:o.next().then(function(e){return e.done?e.value:o.next()})},a(O),O[y]=function(){return this},O[m]="Generator",O.toString=function(){return"[object Generator]"},T.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},T.values=p,h.prototype={constructor:h,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=d,this.done=!1,this.delegate=null,this.tryEntries.forEach(l),!e)for(var t in this)"t"===t.charAt(0)&&g.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=d)},stop:function(){this.done=!0;var e=this.tryEntries[0],t=e.completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){function t(t,n){return o.type="throw",o.arg=e,r.next=t,!!n}if(this.done)throw e;for(var r=this,n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n],o=i.completion;if("root"===i.tryLoc)return t("end");if(i.tryLoc<=this.prev){var a=g.call(i,"catchLoc"),u=g.call(i,"finallyLoc");if(a&&u){if(this.prev<i.catchLoc)return t(i.catchLoc,!0);if(this.prev<i.finallyLoc)return t(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return t(i.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return t(i.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&g.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?this.next=i.finallyLoc:this.complete(o),S},complete:function(e,t){if("throw"===e.type)throw e.arg;"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=e.arg,this.next="end"):"normal"===e.type&&t&&(this.next=t)},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),l(r),S}},"catch":function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;l(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:p(e),resultName:t,nextLoc:r},S}}}("object"==typeof global?global:"object"==typeof window?window:"object"==typeof self?self:this);
|
data/javascript/120.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const runCode = require('../lib/runCode')const bodyParser = require('body-parser')const express = require('express')const router = express.Router()router.use(bodyParser.json()) // for parsing routerlication/jsonrouter.use(bodyParser.urlencoded({ extended: true }))// GET handler for /router.get('/', (req, res) => { res.send('API requires POST to /code/<lang>')})// POST handler for /pyrouter.post('/py', async (req, res) => { const { filePath } = req.body const result = await runCode('py', filePath) // executes runCode() on specified .py and input files // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// res.send(result)// FIXED: })// POST handler for /cpprouter.post('/cpp', async (req, res) => { const { filePath } = req.body const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files res.send(result)})// POST handler for /jsrouter.post('/js', async (req, res) => { const { filePath } = req.body const result = await runCode('js', filePath) // executes runCode() on specified .js and input files res.send(result)})module.exports = router
|
data/javascript/121.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const runCode = require('../lib/runCode')const bodyParser = require('body-parser')const express = require('express')const router = express.Router()router.use(bodyParser.json()) // for parsing routerlication/jsonrouter.use(bodyParser.urlencoded({ extended: true }))// GET handler for /router.get('/', (req, res) => { res.send('API requires POST to /code/<lang>')})// POST handler for /pyrouter.post('/py', async (req, res) => { const { filePath } = req.body const result = await runCode('py', filePath) // executes runCode() on specified .py and input files // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// res.send(result)// FIXED: })// POST handler for /cpprouter.post('/cpp', async (req, res) => { const { filePath } = req.body const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files res.send(result)})// POST handler for /jsrouter.post('/js', async (req, res) => { const { filePath } = req.body const result = await runCode('js', filePath) // executes runCode() on specified .js and input files res.send(result)})module.exports = router
|
data/javascript/122.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const runCode = require('../lib/runCode')const bodyParser = require('body-parser')const express = require('express')const router = express.Router()router.use(bodyParser.json()) // for parsing routerlication/jsonrouter.use(bodyParser.urlencoded({ extended: true }))// GET handler for /router.get('/', (req, res) => { res.send('API requires POST to /code/<lang>')})// POST handler for /pyrouter.post('/py', async (req, res) => { const { filePath } = req.body const result = await runCode('py', filePath) // executes runCode() on specified .py and input files // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// res.send(result)// FIXED: })// POST handler for /cpprouter.post('/cpp', async (req, res) => { const { filePath } = req.body const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files res.send(result)})// POST handler for /jsrouter.post('/js', async (req, res) => { const { filePath } = req.body const result = await runCode('js', filePath) // executes runCode() on specified .js and input files res.send(result)})module.exports = router
|
data/javascript/123.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
var Utils = function () { /** * Eithers shows the specified element or hides it */ function showElement(el, b) { el.style.display = b ? 'block' : 'none'; } /** * Check to see if an element has a css class */ function hasCssClass(el, name) { var classes = el.className.split(/\s+/g); return classes.indexOf(name) !== -1; } /** * Adds a css class from an element */ function addCssClass(el, name) { if (!hasCssClass(el, name)) { el.className += " " + name; } } /** * Removes a css class from an element */ function removeCssClass(el, name) { var classes = el.className.split(/\s+/g); while (true) { var index = classes.indexOf(name); if (index == -1) { break; } classes.splice(index, 1); } el.className = classes.join(" "); } /** * Convenience method to get the last index of any of the items in the array */ function lastIndexOfAny(str, arr, start) { var max = -1; for (var i = 0; i < arr.length; i++) { var val = str.lastIndexOf(arr[i], start); max = Math.max(max, val); } return max; } function repeat(s, n){ var a = []; while(a.length < n){ a.push(s); } return a.join(''); } function escapeIdent(name) { if (!isNaN(name[0]) || lastIndexOfAny(name, [' ', '[', ']', '.']) != -1) { name = '``' + name + '``'; } return name; } this.lastIndexOfAny = lastIndexOfAny; this.removeCssClass = removeCssClass; this.addCssClass = addCssClass; this.hasCssClass = hasCssClass; this.showElement = showElement; this.escapeIdent = escapeIdent; this.repeat = repeat;};var MethodsIntellisense = function () { var utils = new Utils(); var visible = false; var methods = [] var selectedIndex = 0; // methods var methodsElement = document.createElement('div'); methodsElement.className = 'br-methods'; // methods text var methodsTextElement = document.createElement('div'); methodsTextElement.className = 'br-methods-text'; // arrows var arrowsElement = document.createElement('div'); arrowsElement.className = 'br-methods-arrows'; // up arrow var upArrowElement = document.createElement('span'); upArrowElement.className = 'br-methods-arrow'; upArrowElement.innerHTML = '↑'; // down arrow var downArrowElement = document.createElement('span'); downArrowElement.className = 'br-methods-arrow'; downArrowElement.innerHTML = '↓'; // arrow text (1 of x) var arrowTextElement = document.createElement('span'); arrowTextElement.className = 'br-methods-arrow-text'; arrowsElement.appendChild(upArrowElement); arrowsElement.appendChild(arrowTextElement); arrowsElement.appendChild(downArrowElement); methodsElement.appendChild(arrowsElement); methodsElement.appendChild(methodsTextElement); document.body.appendChild(methodsElement); /** * Sets the selected index of the methods */ function setSelectedIndex(idx) { var disabledColor = '#808080'; var enabledColor = 'black'; if (idx < 0) { idx = methods.length - 1; } else if (idx >= methods.length) { idx = 0; } selectedIndex = idx; methodsTextElement.innerHTML = methods[idx]; arrowTextElement.innerHTML = (idx + 1) + ' of ' + methods.length; } /** * This method is called by the end-user application to show method information */ function setMethods(data) { if (data != null && data.length > 0) { methods = data; // show the elements setVisible(true); // show the first item setSelectedIndex(0); } } /** * Reposition the methods element */ function setPosition(left, top) { methodsElement.style.left = left + 'px'; methodsElement.style.top = top + 'px'; } /** * Moves the methods the specified delta */ function moveSelected(delta) { setSelectedIndex(selectedIndex + delta); } /** * Checks to see if this is visible */ function isVisible() { return visible; } /** * Show the methods UI */ function setVisible(b) { visible = b; utils.showElement(methodsElement, b); } // arrow click events downArrowElement.onclick = function () { moveSelected(1); }; // arrow click events upArrowElement.onclick = function () { moveSelected(-1); }; this.setVisible = setVisible; this.isVisible = isVisible; this.setSelectedIndex = setSelectedIndex; this.setMethods = setMethods; this.moveSelected = moveSelected; this.setPosition = setPosition;};var DocumentationSide = function(){ var utils = new Utils(); var documentationElement = document.getElementById('editor-documentation-side'); function showElement(b) { if (documentationElement != null) utils.showElement(documentationElement, b); else // BUG: CWE-345: Insufficient Verification of Data Authenticity// parent.postMessage({'action':'showtip', 'visible':b}, "*");// FIXED: }; function showDocumentation(documentation) { if (documentation == null || documentation.trim().length == 0) { showElement(false); } else { showElement(true); if (documentationElement != null) { if (documentation.trim().indexOf("[JAVASCRIPT]") == 0) { eval("(" + documentation.trim().substr("[JAVASCRIPT]".length) + ")")(documentationElement); } else { documentationElement.innerHTML = documentation; } } else { parent.postMessage({'action':'tip', 'html':documentation.trim()}, "*"); } } } function moveElement(top) { if (documentationElement != null) { var headerHeight = document.getElementById("header").offsetHeight; documentationElement.style.top = (top - headerHeight - 20) + "px"; } } this.moveElement = moveElement; this.showDocumentation = showDocumentation; this.showElement = showElement;}var DeclarationsIntellisense = function () { var events = { itemChosen: [], itemSelected: [] }; var utils = new Utils(); var selectedIndex = 0; var filteredDeclarations = []; var filteredDeclarationsUI = []; var visible = false; var declarations = []; var documentationSide = new DocumentationSide(); // ui widgets var selectedElement = null; var listElement = document.createElement('ul'); listElement.className = 'br-intellisense'; document.body.appendChild(listElement); /** * Filters an array */ function filter(arr, cb) { var ret = []; arr.forEach(function (item) { if (cb(item)) { ret.push(item); } }); return ret; }; /** * Triggers that an item is chosen. */ function triggerItemChosen(item) { events.itemChosen.forEach(function (callback) { callback(item); }); } /** * Triggers that an item is selected. */ function triggerItemSelected(item) { events.itemSelected.forEach(function (callback) { callback(item); }); } /** * Gets the selected index */ function getSelectedIndex(idx) { return selectedIndex; } /** * Sets the selected index */ function setSelectedIndex(idx) { if (idx != selectedIndex) { selectedIndex = idx; triggerItemSelected(getSelectedItem()); } } /** * Event when an item is chosen (double clicked). */ function onItemChosen(callback) { events.itemChosen.push(callback); } /** * Event when an item is selected. */ function onItemSelected(callback) { events.itemSelected.push(callback); } /** * Gets the selected item */ function getSelectedItem() { return filteredDeclarations[selectedIndex]; } /** * Creates a list item that is appended to our intellisense list */ function createListItemDefault(item, idx) { var listItem = document.createElement('li'); listItem.innerHTML = '<span class="br-icon icon-glyph-' + item.glyph + '"></span> ' + item.name; listItem.className = 'br-listlink' return listItem; } /** * Refreshes the user interface for the selected element */ function refreshSelected() { if (selectedElement != null) { utils.removeCssClass(selectedElement, 'br-selected'); } selectedElement = filteredDeclarationsUI[selectedIndex]; if (selectedElement) { utils.addCssClass(selectedElement, 'br-selected'); var item = getSelectedItem(); documentationSide.showDocumentation(item.documentation); var top = selectedElement.offsetTop; var bottom = top + selectedElement.offsetHeight; var scrollTop = listElement.scrollTop; if (top <= scrollTop) { listElement.scrollTop = top; } else if (bottom >= scrollTop + listElement.offsetHeight) { listElement.scrollTop = bottom - listElement.offsetHeight; } } } /** * Refreshes the user interface. */ function refreshUI() { listElement.innerHTML = ''; filteredDeclarationsUI = []; filteredDeclarations.forEach(function (item, idx) { var listItem = createListItemDefault(item, idx); listItem.ondblclick = function () { setSelectedIndex(idx); triggerItemChosen(getSelectedItem()); setVisible(false); documentationSide.showElement(false); }; listItem.onclick = function () { setSelectedIndex(idx); }; listElement.appendChild(listItem); filteredDeclarationsUI.push(listItem); }); refreshSelected(); } /** * Show the auto complete and the documentation elements */ function setVisible(b) { visible = b; utils.showElement(listElement, b); documentationSide.showElement(b); } /** * This method is called by the end-user application */ function setDeclarations(data) { if (data != null && data.length > 0) { // set the data declarations = data; filteredDeclarations = data; // show the elements setVisible(true); documentationSide.showElement(true); setFilter(''); } } /** * Sets the position of the list element and documentation element */ function setPosition(left, top) { // reposition intellisense listElement.style.left = left + 'px'; listElement.style.top = top + 'px'; // reposition documentation documentationSide.moveElement(top); } /** * Refresh the filter */ function setFilter(filterText) { if (filterText.indexOf("``") == 0) filterText = filterText.substr(2); // Only apply the filter if there is something left, otherwise leave unchanged var filteredTemp = filter(declarations, function (x) { return x.name.toLowerCase().indexOf(filterText) === 0; }); if (filteredTemp.length > 0) filteredDeclarations = filteredTemp; selectedIndex = 0; refreshUI(); } /** * Moves the auto complete selection up or down a specified amount */ function moveSelected(delta) { var idx = selectedIndex + delta; idx = Math.max(idx, 0); idx = Math.min(idx, filteredDeclarations.length - 1); // select setSelectedIndex(idx) refreshSelected(); } /** * Is the list visible or not */ function isVisible() { return visible; } // public API this.isVisible = isVisible; this.setFilter = setFilter; this.getSelectedItem = getSelectedItem; this.getSelectedIndex = getSelectedIndex; this.setSelectedIndex = setSelectedIndex; this.onItemChosen = onItemChosen; this.onItemSelected = onItemSelected; this.moveSelected = moveSelected; this.setDeclarations = setDeclarations; this.setPosition = setPosition; this.setVisible = setVisible;};
|
data/javascript/124.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
var Utils = function () { /** * Eithers shows the specified element or hides it */ function showElement(el, b) { el.style.display = b ? 'block' : 'none'; } /** * Check to see if an element has a css class */ function hasCssClass(el, name) { var classes = el.className.split(/\s+/g); return classes.indexOf(name) !== -1; } /** * Adds a css class from an element */ function addCssClass(el, name) { if (!hasCssClass(el, name)) { el.className += " " + name; } } /** * Removes a css class from an element */ function removeCssClass(el, name) { var classes = el.className.split(/\s+/g); while (true) { var index = classes.indexOf(name); if (index == -1) { break; } classes.splice(index, 1); } el.className = classes.join(" "); } /** * Convenience method to get the last index of any of the items in the array */ function lastIndexOfAny(str, arr, start) { var max = -1; for (var i = 0; i < arr.length; i++) { var val = str.lastIndexOf(arr[i], start); max = Math.max(max, val); } return max; } function repeat(s, n){ var a = []; while(a.length < n){ a.push(s); } return a.join(''); } function escapeIdent(name) { if (!isNaN(name[0]) || lastIndexOfAny(name, [' ', '[', ']', '.']) != -1) { name = '``' + name + '``'; } return name; } this.lastIndexOfAny = lastIndexOfAny; this.removeCssClass = removeCssClass; this.addCssClass = addCssClass; this.hasCssClass = hasCssClass; this.showElement = showElement; this.escapeIdent = escapeIdent; this.repeat = repeat;};var MethodsIntellisense = function () { var utils = new Utils(); var visible = false; var methods = [] var selectedIndex = 0; // methods var methodsElement = document.createElement('div'); methodsElement.className = 'br-methods'; // methods text var methodsTextElement = document.createElement('div'); methodsTextElement.className = 'br-methods-text'; // arrows var arrowsElement = document.createElement('div'); arrowsElement.className = 'br-methods-arrows'; // up arrow var upArrowElement = document.createElement('span'); upArrowElement.className = 'br-methods-arrow'; upArrowElement.innerHTML = '↑'; // down arrow var downArrowElement = document.createElement('span'); downArrowElement.className = 'br-methods-arrow'; downArrowElement.innerHTML = '↓'; // arrow text (1 of x) var arrowTextElement = document.createElement('span'); arrowTextElement.className = 'br-methods-arrow-text'; arrowsElement.appendChild(upArrowElement); arrowsElement.appendChild(arrowTextElement); arrowsElement.appendChild(downArrowElement); methodsElement.appendChild(arrowsElement); methodsElement.appendChild(methodsTextElement); document.body.appendChild(methodsElement); /** * Sets the selected index of the methods */ function setSelectedIndex(idx) { var disabledColor = '#808080'; var enabledColor = 'black'; if (idx < 0) { idx = methods.length - 1; } else if (idx >= methods.length) { idx = 0; } selectedIndex = idx; methodsTextElement.innerHTML = methods[idx]; arrowTextElement.innerHTML = (idx + 1) + ' of ' + methods.length; } /** * This method is called by the end-user application to show method information */ function setMethods(data) { if (data != null && data.length > 0) { methods = data; // show the elements setVisible(true); // show the first item setSelectedIndex(0); } } /** * Reposition the methods element */ function setPosition(left, top) { methodsElement.style.left = left + 'px'; methodsElement.style.top = top + 'px'; } /** * Moves the methods the specified delta */ function moveSelected(delta) { setSelectedIndex(selectedIndex + delta); } /** * Checks to see if this is visible */ function isVisible() { return visible; } /** * Show the methods UI */ function setVisible(b) { visible = b; utils.showElement(methodsElement, b); } // arrow click events downArrowElement.onclick = function () { moveSelected(1); }; // arrow click events upArrowElement.onclick = function () { moveSelected(-1); }; this.setVisible = setVisible; this.isVisible = isVisible; this.setSelectedIndex = setSelectedIndex; this.setMethods = setMethods; this.moveSelected = moveSelected; this.setPosition = setPosition;};var DocumentationSide = function(){ var utils = new Utils(); var documentationElement = document.getElementById('editor-documentation-side'); function showElement(b) { if (documentationElement != null) utils.showElement(documentationElement, b); else parent.postMessage({'action':'showtip', 'visible':b}, "*"); }; function showDocumentation(documentation) { if (documentation == null || documentation.trim().length == 0) { showElement(false); } else { showElement(true); if (documentationElement != null) { if (documentation.trim().indexOf("[JAVASCRIPT]") == 0) { eval("(" + documentation.trim().substr("[JAVASCRIPT]".length) + ")")(documentationElement); } else { documentationElement.innerHTML = documentation; } } else { // BUG: CWE-345: Insufficient Verification of Data Authenticity// parent.postMessage({'action':'tip', 'html':documentation.trim()}, "*");// FIXED: } } } function moveElement(top) { if (documentationElement != null) { var headerHeight = document.getElementById("header").offsetHeight; documentationElement.style.top = (top - headerHeight - 20) + "px"; } } this.moveElement = moveElement; this.showDocumentation = showDocumentation; this.showElement = showElement;}var DeclarationsIntellisense = function () { var events = { itemChosen: [], itemSelected: [] }; var utils = new Utils(); var selectedIndex = 0; var filteredDeclarations = []; var filteredDeclarationsUI = []; var visible = false; var declarations = []; var documentationSide = new DocumentationSide(); // ui widgets var selectedElement = null; var listElement = document.createElement('ul'); listElement.className = 'br-intellisense'; document.body.appendChild(listElement); /** * Filters an array */ function filter(arr, cb) { var ret = []; arr.forEach(function (item) { if (cb(item)) { ret.push(item); } }); return ret; }; /** * Triggers that an item is chosen. */ function triggerItemChosen(item) { events.itemChosen.forEach(function (callback) { callback(item); }); } /** * Triggers that an item is selected. */ function triggerItemSelected(item) { events.itemSelected.forEach(function (callback) { callback(item); }); } /** * Gets the selected index */ function getSelectedIndex(idx) { return selectedIndex; } /** * Sets the selected index */ function setSelectedIndex(idx) { if (idx != selectedIndex) { selectedIndex = idx; triggerItemSelected(getSelectedItem()); } } /** * Event when an item is chosen (double clicked). */ function onItemChosen(callback) { events.itemChosen.push(callback); } /** * Event when an item is selected. */ function onItemSelected(callback) { events.itemSelected.push(callback); } /** * Gets the selected item */ function getSelectedItem() { return filteredDeclarations[selectedIndex]; } /** * Creates a list item that is appended to our intellisense list */ function createListItemDefault(item, idx) { var listItem = document.createElement('li'); listItem.innerHTML = '<span class="br-icon icon-glyph-' + item.glyph + '"></span> ' + item.name; listItem.className = 'br-listlink' return listItem; } /** * Refreshes the user interface for the selected element */ function refreshSelected() { if (selectedElement != null) { utils.removeCssClass(selectedElement, 'br-selected'); } selectedElement = filteredDeclarationsUI[selectedIndex]; if (selectedElement) { utils.addCssClass(selectedElement, 'br-selected'); var item = getSelectedItem(); documentationSide.showDocumentation(item.documentation); var top = selectedElement.offsetTop; var bottom = top + selectedElement.offsetHeight; var scrollTop = listElement.scrollTop; if (top <= scrollTop) { listElement.scrollTop = top; } else if (bottom >= scrollTop + listElement.offsetHeight) { listElement.scrollTop = bottom - listElement.offsetHeight; } } } /** * Refreshes the user interface. */ function refreshUI() { listElement.innerHTML = ''; filteredDeclarationsUI = []; filteredDeclarations.forEach(function (item, idx) { var listItem = createListItemDefault(item, idx); listItem.ondblclick = function () { setSelectedIndex(idx); triggerItemChosen(getSelectedItem()); setVisible(false); documentationSide.showElement(false); }; listItem.onclick = function () { setSelectedIndex(idx); }; listElement.appendChild(listItem); filteredDeclarationsUI.push(listItem); }); refreshSelected(); } /** * Show the auto complete and the documentation elements */ function setVisible(b) { visible = b; utils.showElement(listElement, b); documentationSide.showElement(b); } /** * This method is called by the end-user application */ function setDeclarations(data) { if (data != null && data.length > 0) { // set the data declarations = data; filteredDeclarations = data; // show the elements setVisible(true); documentationSide.showElement(true); setFilter(''); } } /** * Sets the position of the list element and documentation element */ function setPosition(left, top) { // reposition intellisense listElement.style.left = left + 'px'; listElement.style.top = top + 'px'; // reposition documentation documentationSide.moveElement(top); } /** * Refresh the filter */ function setFilter(filterText) { if (filterText.indexOf("``") == 0) filterText = filterText.substr(2); // Only apply the filter if there is something left, otherwise leave unchanged var filteredTemp = filter(declarations, function (x) { return x.name.toLowerCase().indexOf(filterText) === 0; }); if (filteredTemp.length > 0) filteredDeclarations = filteredTemp; selectedIndex = 0; refreshUI(); } /** * Moves the auto complete selection up or down a specified amount */ function moveSelected(delta) { var idx = selectedIndex + delta; idx = Math.max(idx, 0); idx = Math.min(idx, filteredDeclarations.length - 1); // select setSelectedIndex(idx) refreshSelected(); } /** * Is the list visible or not */ function isVisible() { return visible; } // public API this.isVisible = isVisible; this.setFilter = setFilter; this.getSelectedItem = getSelectedItem; this.getSelectedIndex = getSelectedIndex; this.setSelectedIndex = setSelectedIndex; this.onItemChosen = onItemChosen; this.onItemSelected = onItemSelected; this.moveSelected = moveSelected; this.setDeclarations = setDeclarations; this.setPosition = setPosition; this.setVisible = setVisible;};
|
data/javascript/125.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */(function(window) {var QUnit = { // Initialize the configuration options init: function init() { config = { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, blocking: false, autorun: false, assertions: [], filters: [], queue: [] }; var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } }, // call on start of module test to prepend name to all tests module: function module(name, testEnvironment) { synchronize(function() { if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } config.currentModule = name; config.moduleTestEnvironment = testEnvironment; config.moduleStats = { all: 0, bad: 0 }; QUnit.moduleStart( name, testEnvironment ); }); }, asyncTest: function asyncTest(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function test(testName, expected, callback, async) { var name = testName, testEnvironment = {}; if ( arguments.length === 2 ) { callback = expected; expected = null; } if ( config.currentModule ) { name = config.currentModule + " module: " + name; } if ( !validTest(name) ) { return; } synchronize(function() { QUnit.testStart( testName ); testEnvironment = extend({ setup: function() {}, teardown: function() {} }, config.moduleTestEnvironment); config.assertions = []; config.expected = null; if ( arguments.length >= 3 ) { config.expected = callback; callback = arguments[2]; } try { if ( !config.pollution ) { saveGlobal(); } testEnvironment.setup.call(testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); } if ( async ) { QUnit.stop(); } try { callback.call(testEnvironment); } catch(e) { fail("Test " + name + " died, exception and test follows", e, callback); QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { start(); } } }); synchronize(function() { try { checkPollution(); testEnvironment.teardown.call(testEnvironment); } catch(e) { QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); } if ( config.expected && config.expected != config.assertions.length ) { QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += config.assertions.length; config.moduleStats.all += config.assertions.length; if ( tests ) { var ol = document.createElement("ol"); ol.style.display = "none"; for ( var i = 0; i < config.assertions.length; i++ ) { var assertion = config.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || "(no message)"; ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } var b = document.createElement("strong"); b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = (e || window.event).target; if ( target.nodeName.toLowerCase() === "strong" ) { var text = "", node = target.firstChild; while ( node.nodeType === 3 ) { text += node.nodeValue; node = node.nextSibling; } text = text.replace(/(^\s*|\s*$)/g, ""); if ( window.location ) { window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text); } } }); var li = document.createElement("li"); li.className = bad ? "fail" : "pass"; li.appendChild( b ); li.appendChild( ol ); tests.appendChild( li ); if ( bad ) { var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "block"; id("qunit-filter-pass").disabled = null; id("qunit-filter-missing").disabled = null; } } } else { for ( var i = 0; i < config.assertions.length; i++ ) { if ( !config.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } QUnit.testDone( testName, bad, config.assertions.length ); if ( !window.setTimeout && !config.queue.length ) { done(); } }); if ( window.setTimeout && !config.doneTimer ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); } }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function expect(asserts) { config.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function ok(a, msg) { QUnit.log(a, msg); config.assertions.push({ result: !!a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equals( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equals: function equals(actual, expected, message) { push(expected == actual, actual, expected, message); }, same: function(a, b, message) { push(QUnit.equiv(a, b), a, b, message); }, start: function start() { // A slight delay, to avoid any current callbacks if ( window.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function stop(timeout) { config.blocking = true; if ( timeout && window.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); QUnit.start(); }, timeout); } }, /** * Resets the test setup. Useful for tests that modify the DOM. */ reset: function reset() { if ( window.jQuery ) { jQuery("#main").html( config.fixture ); jQuery.event.global = {}; jQuery.ajaxSettings = extend({}, config.ajaxSettings); } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function triggerEvent( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Logging callbacks done: function done(failures, total) {}, log: function log(result, message) {}, testStart: function testStart(name) {}, testDone: function testDone(name, failures, total) {}, moduleStart: function moduleStart(name, testEnvironment) {}, moduleDone: function moduleDone(name, failures, total) {}};// Maintain internal statevar config = { // The queue of tests to run queue: [], // block until document ready blocking: true};// Load paramaters(function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:');})();// Expose the API as global variables, unless an 'exports'// object exists, in that case we assume we're in CommonJSif ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit;} else { extend(exports, QUnit); exports.QUnit = QUnit;}if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true;}addEvent(window, "load", function() { // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "none"; var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : "block"; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); var missing = document.createElement("input"); missing.type = "checkbox"; missing.id = "qunit-filter-missing"; missing.disabled = true; addEvent( missing, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) { li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block"; } } }); toolbar.appendChild( missing ); label = document.createElement("label"); label.setAttribute("for", "filter-missing"); label.innerHTML = "Hide missing tests (untested code is broken code)"; toolbar.appendChild( label ); } var main = id('main'); if ( main ) { config.fixture = main.innerHTML; } if ( window.jQuery ) { config.ajaxSettings = window.jQuery.ajaxSettings; } QUnit.start();});function done() { if ( config.doneTimer && window.clearTimeout ) { window.clearTimeout( config.doneTimer ); config.doneTimer = null; } if ( config.queue.length ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); return; } config.autorun = true; // Log the last module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), html = ['Tests completed in ', +new Date - config.started, ' milliseconds.<br/>', '<span class="bad">', config.stats.all - config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> passed, ', config.stats.bad,' failed.'].join(''); if ( banner ) { banner.className += " " + (config.stats.bad ? "fail" : "pass"); } if ( tests ) { var result = id("qunit-testresult"); if ( !result ) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests.nextSibling ); } result.innerHTML = html; } QUnit.done( config.stats.bad, config.stats.all );}function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run;}function push(result, actual, expected, message) { message = message || (result ? "okay" : "failed"); QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) );}function synchronize( callback ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(); }}function process() { while ( config.queue.length && !config.blocking ) { config.queue.shift()(); }}function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push( key ); } }}function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( old, config.pollution ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.expected++; } var deletedGlobals = diff( config.pollution, old ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); config.expected++; }}// returns a new Array with the elements that are in a but not in bfunction diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result;}function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); }}function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a;}function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); }}function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name );}// Test for equality any JavaScript type.// Discussions and reference: http://philrathe.com/articles/equiv// Test suites: http://philrathe.com/tests/equiv// Author: Philippe Rathé <prathe@gmail.com>QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions // Determine what is o. function hoozit(o) { if (o.constructor === String) { return "string"; } else if (o.constructor === Boolean) { return "boolean"; } else if (o.constructor === Number) { if (isNaN(o)) { return "nan"; } else { return "number"; } } else if (typeof o === "undefined") { return "undefined"; // consider: typeof null === object } else if (o === null) { return "null"; // consider: typeof [] === object } else if (o instanceof Array) { return "array"; // consider: typeof new Date() === object } else if (o instanceof Date) { return "date"; // consider: /./ instanceof Object; // /./ instanceof RegExp; // typeof /./ === "function"; // => false in IE and Opera, // true in FF and Safari } else if (o instanceof RegExp) { return "regexp"; } else if (typeof o === "object") { return "object"; } else if (o instanceof Function) { return "function"; } else { return undefined; } } // Call the o related callback with the given arguments. function handleEvents(o, callbacks, args) { var prop = hoozit(o); if (prop) { if (hoozit(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return hoozit(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return hoozit(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i; var len; // b could be an object literal here if ( ! (hoozit(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } for (i = 0; i < len; i++) { if ( ! innerEquiv(a[i], b[i])) { return false; } } return true; }, "object": function (b, a) { var i; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep aProperties.push(i); // collect a's properties if ( ! innerEquiv(a[i], b[i])) { eq = false; } } callers.pop(); // unstack, we are done for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) { return false; // don't lose time with error prone cases } else { return handleEvents(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv;}();/** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type = typeof obj, f = 'function';//we'll use it 3 times, save it return type != 'object' && type != f ? type : !obj ? 'null' : obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions obj.getHours ? 'date' : obj.scrollBy ? 'window' : obj.nodeName == '#document' ? 'document' : obj.nodeName ? 'node' : obj.item ? 'nodelist' : // Safari reports nodelists as functions obj.callee ? 'arguments' : obj.call || obj.constructor != Array && //an array would also fall on this hack (obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects 'length' in obj ? 'array' : type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,' '); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, this.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; this.up(); for ( var key in map ) ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); this.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = this.HTML ? '<' : '<', close = this.HTML ? '>' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in this.DOMAttrs ) { var val = node[this.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + this.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:true,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump;})();})(this);/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */(function(window) {var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e){ return false; } })()}var testId = 0;var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = [];};Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( this.previousModule ) { QUnit.moduleDone( this.module, config.moduleStats.bad, config.moduleStats.all ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; QUnit.moduleStart( this.module, this.moduleTestEnvironment ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } QUnit.testStart( this.testName, this.testEnvironment ); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if ( !config.pollution ) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? QUnit.ok( false, "Setup failed on " + this.name + ": " + e.message ); } }, run: function() { if ( this.async ) { QUnit.stop(); } try { this.callback.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? fail("Test " + this.name + " died, exception and test follows", e, this.callback); QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { start(); } } }, teardown: function() { try { checkPollution(); this.testEnvironment.teardown.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? QUnit.ok( false, "Teardown failed on " + this.name + ": " + e.message ); } }, finish: function() { if ( this.expected && this.expected != this.assertions.length ) { QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( var i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible defined.sessionStorage && sessionStorage.setItem("qunit-" + this.testName, bad); if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location.search = "?" + encodeURIComponent(getText([target]).replace(/\(.+\)$/, "").replace(/(^\s*|\s*$)/g, "")); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.style.display = resultDisplayStyle(!bad); li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( ol ); if ( bad ) { var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "block"; id("qunit-filter-pass").disabled = null; } } } else { for ( var i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { // TODO use testName instead of name for no-markup message? fail("reset() failed, following Test " + this.name + ", exception and reset fn follows", e, QUnit.reset); } QUnit.testDone( this.testName, bad, this.assertions.length ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.testName); if (bad) { run(); } else { synchronize(run); }; }}var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.previousModule = config.currentModule; config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.previousModule = config.previousModule; test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeHtml(msg); QUnit.log(a, msg, details); config.current.assertions.push({ result: a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(block, expected, message) { var actual, ok = false; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } if (actual) { // we don't want to validate thrown error if (!expected) { ok = true; // expected is a regexp } else if (QUnit.objectType(expected) === "regexp") { ok = expected.test(actual); // expected is a constructor } else if (actual instanceof expected) { ok = true; // expected is a validation function which returns true is validation passed } else if (expected.call({}, actual) === true) { ok = true; } } QUnit.ok(ok, message); }, start: function() { // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function(timeout) { config.blocking = true; if ( timeout && defined.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); QUnit.start(); }, timeout); } }};// Backwards compatibility, deprecatedQUnit.equals = QUnit.equal;QUnit.same = QUnit.deepEqual;// Maintain internal statevar config = { // The queue of tests to run queue: [], // block until document ready blocking: true};// Load paramaters(function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } else if ( GETParams[i].search('=') > -1 ) { GETParams.splice( i, 1 ); i--; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:');})();// Expose the API as global variables, unless an 'exports'// object exists, in that case we assume we're in CommonJSif ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit;} else { extend(exports, QUnit); exports.QUnit = QUnit;}// define these after exposing globals to keep them in these QUnit namespace onlyextend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filters: [], queue: [] }); var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if ( window.jQuery ) { jQuery( "#main, #qunit-fixture" ).html( config.fixture ); } else { var main = id( 'main' ) || id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = Object.prototype.toString.call( obj ) .match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeHtml(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeHtml(QUnit.jsDump.parse(expected)); actual = escapeHtml(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + source +'</pre></td></tr>'; } } output += "</table>"; QUnit.log(result, message, details); config.current.assertions.push({ result: !!result, message: output }); }, // Logging callbacks begin: function() {}, done: function(failures, total) {}, log: function(result, message) {}, testStart: function(name, testEnvironment) {}, testDone: function(name, failures, total) {}, moduleStart: function(name, testEnvironment) {}, moduleDone: function(name, failures, total) {}});if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true;}addEvent(window, "load", function() { QUnit.begin(); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { var paramsIndex = location.href.lastIndexOf(location.search); if ( paramsIndex > -1 ) { var mainPageLocation = location.href.slice(0, paramsIndex); if ( mainPageLocation == location.href ) { banner.innerHTML = '<a href=""> ' + banner.innerHTML + '</a> '; } else { var testName = decodeURIComponent(location.search.slice(1)); // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// banner.innerHTML = '<a href="' + mainPageLocation + '">' + banner.innerHTML + '</a> › <a href="">' + testName + '</a>';// FIXED: } } } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "none"; var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : ""; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('main') || id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); }});function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), html = ['Tests completed in ', +new Date - config.started, ' milliseconds.<br/>', '<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { var result = id("qunit-testresult"); if ( !result ) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests.nextSibling ); } result.innerHTML = html; } QUnit.done( config.stats.bad, config.stats.all );}function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run;}// so far supports only Firefox, Chrome and Opera (buggy)// could be extended in the future to use something like https://github.com/csnover/TraceKitfunction sourceFromStacktrace() { try { throw new Error(); } catch ( e ) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } }}function resultDisplayStyle(passed) { return passed && id("qunit-filter-pass") && id("qunit-filter-pass").checked ? 'none' : '';}function escapeHtml(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&"<>\\]/g, function(s) { switch(s) { case "&": return "&"; case "\\": return "\\\\"; case '"': return '\"'; case "<": return "<"; case ">": return ">"; default: return s; } });}function synchronize( callback ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(); }}function process() { var start = (new Date()).getTime(); while ( config.queue.length && !config.blocking ) { if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) { config.queue.shift()(); } else { window.setTimeout( process, 13 ); break; } } if (!config.blocking && !config.queue.length) { done(); }}function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push( key ); } }}function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( old, config.pollution ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.current.expected++; } var deletedGlobals = diff( config.pollution, old ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); config.current.expected++; }}// returns a new Array with the elements that are in a but not in bfunction diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result;}function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); }}function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a;}function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); }}function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name );}// Test for equality any JavaScript type.// Discussions and reference: http://philrathe.com/articles/equiv// Test suites: http://philrathe.com/tests/equiv// Author: Philippe Rathé <prathe@gmail.com>QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return QUnit.objectType(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i, j, loop; var len; // b could be an object literal here if ( ! (QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } //track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for(j=0;j<parents.length;j++){ if(parents[j] === a[i]){ loop = true;//dont rewalk array } } if (!loop && ! innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object": function (b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); //track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep loop = false; for(j=0;j<parents.length;j++){ if(parents[j] === a[i]) loop = true; //don't go down the same path twice } aProperties.push(i); // collect a's properties if (!loop && ! innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv;}();/** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) { type = "array"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,' '); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; QUnit.jsDump.up(); for ( var key in map ) ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(map[key]) ); QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = QUnit.jsDump.HTML ? '<' : '<', close = QUnit.jsDump.HTML ? '>' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump;})();// from Sizzle.jsfunction getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret;};/* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */QUnit.diff = (function() { function diff(o, n){ var ns = new Object(); var os = new Object(); for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: new Array(), o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: new Array(), n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n){ o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; };})();})(this);
|
data/javascript/126.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
define("dijit/_editor/RichText", ["dojo", "dijit", "dijit/_Widget", "dijit/_CssStateMixin", "dijit/_editor/selection", "dijit/_editor/range", "dijit/_editor/html"], function(dojo, dijit) {// used to restore content when user leaves this page then comes back// but do not try doing dojo.doc.write if we are using xd loading.// dojo.doc.write will only work if RichText.js is included in the dojo.js// file. If it is included in dojo.js and you want to allow rich text saving// for back/forward actions, then set dojo.config.allowXdRichTextSave = true.if(!dojo.config["useXDomain"] || dojo.config["allowXdRichTextSave"]){ if(dojo._postLoad){ (function(){ var savetextarea = dojo.doc.createElement('textarea'); savetextarea.id = dijit._scopeName + "._editor.RichText.value"; dojo.style(savetextarea, { display:'none', position:'absolute', top:"-100px", height:"3px", width:"3px" }); dojo.body().appendChild(savetextarea); })(); }else{ //dojo.body() is not available before onLoad is fired try{ dojo.doc.write('<textarea id="' + dijit._scopeName + '._editor.RichText.value" ' + 'style="display:none;position:absolute;top:-100px;left:-100px;height:3px;width:3px;overflow:hidden;"></textarea>'); }catch(e){ } }}dojo.declare("dijit._editor.RichText", [dijit._Widget, dijit._CssStateMixin], { constructor: function(params){ // summary: // dijit._editor.RichText is the core of dijit.Editor, which provides basic // WYSIWYG editing features. // // description: // dijit._editor.RichText is the core of dijit.Editor, which provides basic // WYSIWYG editing features. It also encapsulates the differences // of different js engines for various browsers. Do not use this widget // with an HTML <TEXTAREA> tag, since the browser unescapes XML escape characters, // like <. This can have unexpected behavior and lead to security issues // such as scripting attacks. // // tags: // private // contentPreFilters: Function(String)[] // Pre content filter function register array. // these filters will be executed before the actual // editing area gets the html content. this.contentPreFilters = []; // contentPostFilters: Function(String)[] // post content filter function register array. // These will be used on the resulting html // from contentDomPostFilters. The resulting // content is the final html (returned by getValue()). this.contentPostFilters = []; // contentDomPreFilters: Function(DomNode)[] // Pre content dom filter function register array. // These filters are applied after the result from // contentPreFilters are set to the editing area. this.contentDomPreFilters = []; // contentDomPostFilters: Function(DomNode)[] // Post content dom filter function register array. // These filters are executed on the editing area dom. // The result from these will be passed to contentPostFilters. this.contentDomPostFilters = []; // editingAreaStyleSheets: dojo._URL[] // array to store all the stylesheets applied to the editing area this.editingAreaStyleSheets = []; // Make a copy of this.events before we start writing into it, otherwise we // will modify the prototype which leads to bad things on pages w/multiple editors this.events = [].concat(this.events); this._keyHandlers = {}; if(params && dojo.isString(params.value)){ this.value = params.value; } this.onLoadDeferred = new dojo.Deferred(); }, baseClass: "dijitEditor", // inheritWidth: Boolean // whether to inherit the parent's width or simply use 100% inheritWidth: false, // focusOnLoad: [deprecated] Boolean // Focus into this widget when the page is loaded focusOnLoad: false, // name: String? // Specifies the name of a (hidden) <textarea> node on the page that's used to save // the editor content on page leave. Used to restore editor contents after navigating // to a new page and then hitting the back button. name: "", // styleSheets: [const] String // semicolon (";") separated list of css files for the editing area styleSheets: "", // height: String // Set height to fix the editor at a specific height, with scrolling. // By default, this is 300px. If you want to have the editor always // resizes to accommodate the content, use AlwaysShowToolbar plugin // and set height="". If this editor is used within a layout widget, // set height="100%". height: "300px", // minHeight: String // The minimum height that the editor should have. minHeight: "1em", // isClosed: [private] Boolean isClosed: true, // isLoaded: [private] Boolean isLoaded: false, // _SEPARATOR: [private] String // Used to concat contents from multiple editors into a single string, // so they can be saved into a single <textarea> node. See "name" attribute. _SEPARATOR: "@@**%%__RICHTEXTBOUNDRY__%%**@@", // _NAME_CONTENT_SEP: [private] String // USed to separate name from content. Just a colon isn't safe. _NAME_CONTENT_SEP: "@@**%%:%%**@@", // onLoadDeferred: [readonly] dojo.Deferred // Deferred which is fired when the editor finishes loading. // Call myEditor.onLoadDeferred.then(callback) it to be informed // when the rich-text area initialization is finalized. onLoadDeferred: null, // isTabIndent: Boolean // Make tab key and shift-tab indent and outdent rather than navigating. // Caution: sing this makes web pages inaccessible to users unable to use a mouse. isTabIndent: false, // disableSpellCheck: [const] Boolean // When true, disables the browser's native spell checking, if supported. // Works only in Firefox. disableSpellCheck: false, postCreate: function(){ if("textarea" == this.domNode.tagName.toLowerCase()){ console.warn("RichText should not be used with the TEXTAREA tag. See dijit._editor.RichText docs."); } // Push in the builtin filters now, making them the first executed, but not over-riding anything // users passed in. See: #6062 this.contentPreFilters = [dojo.hitch(this, "_preFixUrlAttributes")].concat(this.contentPreFilters); if(dojo.isMoz){ this.contentPreFilters = [this._normalizeFontStyle].concat(this.contentPreFilters); this.contentPostFilters = [this._removeMozBogus].concat(this.contentPostFilters); } if(dojo.isWebKit){ // Try to clean up WebKit bogus artifacts. The inserted classes // made by WebKit sometimes messes things up. this.contentPreFilters = [this._removeWebkitBogus].concat(this.contentPreFilters); this.contentPostFilters = [this._removeWebkitBogus].concat(this.contentPostFilters); } if(dojo.isIE){ // IE generates <strong> and <em> but we want to normalize to <b> and <i> this.contentPostFilters = [this._normalizeFontStyle].concat(this.contentPostFilters); } this.inherited(arguments); dojo.publish(dijit._scopeName + "._editor.RichText::init", [this]); this.open(); this.setupDefaultShortcuts(); }, setupDefaultShortcuts: function(){ // summary: // Add some default key handlers // description: // Overwrite this to setup your own handlers. The default // implementation does not use Editor commands, but directly // executes the builtin commands within the underlying browser // support. // tags: // protected var exec = dojo.hitch(this, function(cmd, arg){ return function(){ return !this.execCommand(cmd,arg); }; }); var ctrlKeyHandlers = { b: exec("bold"), i: exec("italic"), u: exec("underline"), a: exec("selectall"), s: function(){ this.save(true); }, m: function(){ this.isTabIndent = !this.isTabIndent; }, "1": exec("formatblock", "h1"), "2": exec("formatblock", "h2"), "3": exec("formatblock", "h3"), "4": exec("formatblock", "h4"), "\\": exec("insertunorderedlist") }; if(!dojo.isIE){ ctrlKeyHandlers.Z = exec("redo"); //FIXME: undo? } for(var key in ctrlKeyHandlers){ this.addKeyHandler(key, true, false, ctrlKeyHandlers[key]); } }, // events: [private] String[] // events which should be connected to the underlying editing area events: ["onKeyPress", "onKeyDown", "onKeyUp"], // onClick handled specially // captureEvents: [deprecated] String[] // Events which should be connected to the underlying editing // area, events in this array will be addListener with // capture=true. // TODO: looking at the code I don't see any distinction between events and captureEvents, // so get rid of this for 2.0 if not sooner captureEvents: [], _editorCommandsLocalized: false, _localizeEditorCommands: function(){ // summary: // When IE is running in a non-English locale, the API actually changes, // so that we have to say (for example) danraku instead of p (for paragraph). // Handle that here. // tags: // private if(dijit._editor._editorCommandsLocalized){ // Use the already generate cache of mappings. this._local2NativeFormatNames = dijit._editor._local2NativeFormatNames; this._native2LocalFormatNames = dijit._editor._native2LocalFormatNames; return; } dijit._editor._editorCommandsLocalized = true; dijit._editor._local2NativeFormatNames = {}; dijit._editor._native2LocalFormatNames = {}; this._local2NativeFormatNames = dijit._editor._local2NativeFormatNames; this._native2LocalFormatNames = dijit._editor._native2LocalFormatNames; //in IE, names for blockformat is locale dependent, so we cache the values here //put p after div, so if IE returns Normal, we show it as paragraph //We can distinguish p and div if IE returns Normal, however, in order to detect that, //we have to call this.document.selection.createRange().parentElement() or such, which //could slow things down. Leave it as it is for now var formats = ['div', 'p', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'address']; var localhtml = "", format, i=0; while((format=formats[i++])){ //append a <br> after each element to separate the elements more reliably if(format.charAt(1) !== 'l'){ localhtml += "<"+format+"><span>content</span></"+format+"><br/>"; }else{ localhtml += "<"+format+"><li>content</li></"+format+"><br/>"; } } // queryCommandValue returns empty if we hide editNode, so move it out of screen temporary // Also, IE9 does weird stuff unless we do it inside the editor iframe. var style = { position: "absolute", top: "0px", zIndex: 10, opacity: 0.01 }; var div = dojo.create('div', {style: style, innerHTML: localhtml}); dojo.body().appendChild(div); // IE9 has a timing issue with doing this right after setting // the inner HTML, so put a delay in. var inject = dojo.hitch(this, function(){ var node = div.firstChild; while(node){ try{ dijit._editor.selection.selectElement(node.firstChild); var nativename = node.tagName.toLowerCase(); this._local2NativeFormatNames[nativename] = document.queryCommandValue("formatblock"); this._native2LocalFormatNames[this._local2NativeFormatNames[nativename]] = nativename; node = node.nextSibling.nextSibling; //console.log("Mapped: ", nativename, " to: ", this._local2NativeFormatNames[nativename]); }catch(e) { /*Sqelch the occasional IE9 error */ } } div.parentNode.removeChild(div); div.innerHTML = ""; }); setTimeout(inject, 0); }, open: function(/*DomNode?*/ element){ // summary: // Transforms the node referenced in this.domNode into a rich text editing // node. // description: // Sets up the editing area asynchronously. This will result in // the creation and replacement with an iframe. // tags: // private if(!this.onLoadDeferred || this.onLoadDeferred.fired >= 0){ this.onLoadDeferred = new dojo.Deferred(); } if(!this.isClosed){ this.close(); } dojo.publish(dijit._scopeName + "._editor.RichText::open", [ this ]); if(arguments.length == 1 && element.nodeName){ // else unchanged this.domNode = element; } var dn = this.domNode; // "html" will hold the innerHTML of the srcNodeRef and will be used to // initialize the editor. var html; if(dojo.isString(this.value)){ // Allow setting the editor content programmatically instead of // relying on the initial content being contained within the target // domNode. html = this.value; delete this.value; dn.innerHTML = ""; }else if(dn.nodeName && dn.nodeName.toLowerCase() == "textarea"){ // if we were created from a textarea, then we need to create a // new editing harness node. var ta = (this.textarea = dn); this.name = ta.name; html = ta.value; dn = this.domNode = dojo.doc.createElement("div"); dn.setAttribute('widgetId', this.id); ta.removeAttribute('widgetId'); dn.cssText = ta.cssText; dn.className += " " + ta.className; dojo.place(dn, ta, "before"); var tmpFunc = dojo.hitch(this, function(){ //some browsers refuse to submit display=none textarea, so //move the textarea off screen instead dojo.style(ta, { display: "block", position: "absolute", top: "-1000px" }); if(dojo.isIE){ //nasty IE bug: abnormal formatting if overflow is not hidden var s = ta.style; this.__overflow = s.overflow; s.overflow = "hidden"; } }); if(dojo.isIE){ setTimeout(tmpFunc, 10); }else{ tmpFunc(); } if(ta.form){ var resetValue = ta.value; this.reset = function(){ var current = this.getValue(); if(current != resetValue){ this.replaceValue(resetValue); } }; dojo.connect(ta.form, "onsubmit", this, function(){ // Copy value to the <textarea> so it gets submitted along with form. // FIXME: should we be calling close() here instead? dojo.attr(ta, 'disabled', this.disabled); // don't submit the value if disabled ta.value = this.getValue(); }); } }else{ html = dijit._editor.getChildrenHtml(dn); dn.innerHTML = ""; } var content = dojo.contentBox(dn); this._oldHeight = content.h; this._oldWidth = content.w; this.value = html; // If we're a list item we have to put in a blank line to force the // bullet to nicely align at the top of text if(dn.nodeName && dn.nodeName == "LI"){ dn.innerHTML = " <br>"; } // Construct the editor div structure. this.header = dn.ownerDocument.createElement("div"); dn.appendChild(this.header); this.editingArea = dn.ownerDocument.createElement("div"); dn.appendChild(this.editingArea); this.footer = dn.ownerDocument.createElement("div"); dn.appendChild(this.footer); if(!this.name){ this.name = this.id + "_AUTOGEN"; } // User has pressed back/forward button so we lost the text in the editor, but it's saved // in a hidden <textarea> (which contains the data for all the editors on this page), // so get editor value from there if(this.name !== "" && (!dojo.config["useXDomain"] || dojo.config["allowXdRichTextSave"])){ var saveTextarea = dojo.byId(dijit._scopeName + "._editor.RichText.value"); if(saveTextarea && saveTextarea.value !== ""){ var datas = saveTextarea.value.split(this._SEPARATOR), i=0, dat; while((dat=datas[i++])){ var data = dat.split(this._NAME_CONTENT_SEP); if(data[0] == this.name){ html = data[1]; datas = datas.splice(i, 1); saveTextarea.value = datas.join(this._SEPARATOR); break; } } } if(!dijit._editor._globalSaveHandler){ dijit._editor._globalSaveHandler = {}; dojo.addOnUnload(function() { var id; for(id in dijit._editor._globalSaveHandler){ var f = dijit._editor._globalSaveHandler[id]; if(dojo.isFunction(f)){ f(); } } }); } dijit._editor._globalSaveHandler[this.id] = dojo.hitch(this, "_saveContent"); } this.isClosed = false; var ifr = (this.editorObject = this.iframe = dojo.doc.createElement('iframe')); ifr.id = this.id+"_iframe"; this._iframeSrc = this._getIframeDocTxt(); ifr.style.border = "none"; ifr.style.width = "100%"; if(this._layoutMode){ // iframe should be 100% height, thus getting it's height from surrounding // <div> (which has the correct height set by Editor) ifr.style.height = "100%"; }else{ if(dojo.isIE >= 7){ if(this.height){ ifr.style.height = this.height; } if(this.minHeight){ ifr.style.minHeight = this.minHeight; } }else{ ifr.style.height = this.height ? this.height : this.minHeight; } } ifr.frameBorder = 0; ifr._loadFunc = dojo.hitch( this, function(win){ this.window = win; this.document = this.window.document; if(dojo.isIE){ this._localizeEditorCommands(); } // Do final setup and set initial contents of editor this.onLoad(html); }); // Set the iframe's initial (blank) content. var s = 'javascript:parent.' + dijit._scopeName + '.byId("'+this.id+'")._iframeSrc'; ifr.setAttribute('src', s); this.editingArea.appendChild(ifr); if(dojo.isSafari <= 4){ var src = ifr.getAttribute("src"); if(!src || src.indexOf("javascript") == -1){ // Safari 4 and earlier sometimes act oddly // So we have to set it again. setTimeout(function(){ifr.setAttribute('src', s);},0); } } // TODO: this is a guess at the default line-height, kinda works if(dn.nodeName == "LI"){ dn.lastChild.style.marginTop = "-1.2em"; } dojo.addClass(this.domNode, this.baseClass); }, //static cache variables shared among all instance of this class _local2NativeFormatNames: {}, _native2LocalFormatNames: {}, _getIframeDocTxt: function(){ // summary: // Generates the boilerplate text of the document inside the iframe (ie, <html><head>...</head><body/></html>). // Editor content (if not blank) should be added afterwards. // tags: // private var _cs = dojo.getComputedStyle(this.domNode); // The contents inside of <body>. The real contents are set later via a call to setValue(). var html = ""; var setBodyId = true; if(dojo.isIE || dojo.isWebKit || (!this.height && !dojo.isMoz)){ // In auto-expand mode, need a wrapper div for AlwaysShowToolbar plugin to correctly // expand/contract the editor as the content changes. html = "<div id='dijitEditorBody'></div>"; setBodyId = false; }else if(dojo.isMoz){ // workaround bug where can't select then delete text (until user types something // into the editor)... and/or issue where typing doesn't erase selected text this._cursorToStart = true; html = " "; } var font = [ _cs.fontWeight, _cs.fontSize, _cs.fontFamily ].join(" "); // line height is tricky - applying a units value will mess things up. // if we can't get a non-units value, bail out. var lineHeight = _cs.lineHeight; if(lineHeight.indexOf("px") >= 0){ lineHeight = parseFloat(lineHeight)/parseFloat(_cs.fontSize); // console.debug(lineHeight); }else if(lineHeight.indexOf("em")>=0){ lineHeight = parseFloat(lineHeight); }else{ // If we can't get a non-units value, just default // it to the CSS spec default of 'normal'. Seems to // work better, esp on IE, than '1.0' lineHeight = "normal"; } var userStyle = ""; var self = this; this.style.replace(/(^|;)\s*(line-|font-?)[^;]+/ig, function(match){ match = match.replace(/^;/ig,"") + ';'; var s = match.split(":")[0]; if(s){ s = dojo.trim(s); s = s.toLowerCase(); var i; var sC = ""; for(i = 0; i < s.length; i++){ var c = s.charAt(i); switch(c){ case "-": i++; c = s.charAt(i).toUpperCase(); default: sC += c; } } dojo.style(self.domNode, sC, ""); } userStyle += match + ';'; }); // need to find any associated label element and update iframe document title var label=dojo.query('label[for="'+this.id+'"]'); return [ this.isLeftToRight() ? "<html>\n<head>\n" : "<html dir='rtl'>\n<head>\n", // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// (dojo.isMoz && label.length ? "<title>" + label[0].innerHTML + "</title>\n" : ""),// FIXED: "<meta http-equiv='Content-Type' content='text/html'>\n", "<style>\n", "\tbody,html {\n", "\t\tbackground:transparent;\n", "\t\tpadding: 1px 0 0 0;\n", "\t\tmargin: -1px 0 0 0;\n", // remove extraneous vertical scrollbar on safari and firefox // Set the html/body sizing. Webkit always needs this, other browsers // only set it when height is defined (not auto-expanding), otherwise // scrollers do not appear. ((dojo.isWebKit)?"\t\twidth: 100%;\n":""), ((dojo.isWebKit)?"\t\theight: 100%;\n":""), "\t}\n", // TODO: left positioning will cause contents to disappear out of view // if it gets too wide for the visible area "\tbody{\n", "\t\ttop:0px;\n", "\t\tleft:0px;\n", "\t\tright:0px;\n", "\t\tfont:", font, ";\n", ((this.height||dojo.isOpera) ? "" : "\t\tposition: fixed;\n"), // FIXME: IE 6 won't understand min-height? "\t\tmin-height:", this.minHeight, ";\n", "\t\tline-height:", lineHeight,";\n", "\t}\n", "\tp{ margin: 1em 0; }\n", // Determine how scrollers should be applied. In autoexpand mode (height = "") no scrollers on y at all. // But in fixed height mode we want both x/y scrollers. Also, if it's using wrapping div and in auto-expand // (Mainly IE) we need to kill the y scroller on body and html. (!setBodyId && !this.height ? "\tbody,html {overflow-y: hidden;}\n" : ""), "\t#dijitEditorBody{overflow-x: auto; overflow-y:" + (this.height ? "auto;" : "hidden;") + " outline: 0px;}\n", "\tli > ul:-moz-first-node, li > ol:-moz-first-node{ padding-top: 1.2em; }\n", // Can't set min-height in IE9, it puts layout on li, which puts move/resize handles. (!dojo.isIE ? "\tli{ min-height:1.2em; }\n" : ""), "</style>\n", this._applyEditingAreaStyleSheets(),"\n", "</head>\n<body ", (setBodyId?"id='dijitEditorBody' ":""), "onload='frameElement._loadFunc(window,document)' style='"+userStyle+"'>", html, "</body>\n</html>" ].join(""); // String }, _applyEditingAreaStyleSheets: function(){ // summary: // apply the specified css files in styleSheets // tags: // private var files = []; if(this.styleSheets){ files = this.styleSheets.split(';'); this.styleSheets = ''; } //empty this.editingAreaStyleSheets here, as it will be filled in addStyleSheet files = files.concat(this.editingAreaStyleSheets); this.editingAreaStyleSheets = []; var text='', i=0, url; while((url=files[i++])){ var abstring = (new dojo._Url(dojo.global.location, url)).toString(); this.editingAreaStyleSheets.push(abstring); text += '<link rel="stylesheet" type="text/css" href="'+abstring+'"/>'; } return text; }, addStyleSheet: function(/*dojo._Url*/ uri){ // summary: // add an external stylesheet for the editing area // uri: // A dojo.uri.Uri pointing to the url of the external css file var url=uri.toString(); //if uri is relative, then convert it to absolute so that it can be resolved correctly in iframe if(url.charAt(0) == '.' || (url.charAt(0) != '/' && !uri.host)){ url = (new dojo._Url(dojo.global.location, url)).toString(); } if(dojo.indexOf(this.editingAreaStyleSheets, url) > -1){// console.debug("dijit._editor.RichText.addStyleSheet: Style sheet "+url+" is already applied"); return; } this.editingAreaStyleSheets.push(url); this.onLoadDeferred.addCallback(dojo.hitch(this, function(){ if(this.document.createStyleSheet){ //IE this.document.createStyleSheet(url); }else{ //other browser var head = this.document.getElementsByTagName("head")[0]; var stylesheet = this.document.createElement("link"); stylesheet.rel="stylesheet"; stylesheet.type="text/css"; stylesheet.href=url; head.appendChild(stylesheet); } })); }, removeStyleSheet: function(/*dojo._Url*/ uri){ // summary: // remove an external stylesheet for the editing area var url=uri.toString(); //if uri is relative, then convert it to absolute so that it can be resolved correctly in iframe if(url.charAt(0) == '.' || (url.charAt(0) != '/' && !uri.host)){ url = (new dojo._Url(dojo.global.location, url)).toString(); } var index = dojo.indexOf(this.editingAreaStyleSheets, url); if(index == -1){// console.debug("dijit._editor.RichText.removeStyleSheet: Style sheet "+url+" has not been applied"); return; } delete this.editingAreaStyleSheets[index]; dojo.withGlobal(this.window,'query', dojo, ['link:[href="'+url+'"]']).orphan(); }, // disabled: Boolean // The editor is disabled; the text cannot be changed. disabled: false, _mozSettingProps: {'styleWithCSS':false}, _setDisabledAttr: function(/*Boolean*/ value){ value = !!value; this._set("disabled", value); if(!this.isLoaded){ return; } // this method requires init to be complete if(dojo.isIE || dojo.isWebKit || dojo.isOpera){ var preventIEfocus = dojo.isIE && (this.isLoaded || !this.focusOnLoad); if(preventIEfocus){ this.editNode.unselectable = "on"; } this.editNode.contentEditable = !value; if(preventIEfocus){ var _this = this; setTimeout(function(){ _this.editNode.unselectable = "off"; }, 0); } }else{ //moz try{ this.document.designMode=(value?'off':'on'); }catch(e){ return; } // ! _disabledOK if(!value && this._mozSettingProps){ var ps = this._mozSettingProps; for(var n in ps){ if(ps.hasOwnProperty(n)){ try{ this.document.execCommand(n,false,ps[n]); }catch(e2){} } } }// this.document.execCommand('contentReadOnly', false, value);// if(value){// this.blur(); //to remove the blinking caret// } } this._disabledOK = true; },/* Event handlers *****************/ onLoad: function(/*String*/ html){ // summary: // Handler after the iframe finishes loading. // html: String // Editor contents should be set to this value // tags: // protected // TODO: rename this to _onLoad, make empty public onLoad() method, deprecate/make protected onLoadDeferred handler? if(!this.window.__registeredWindow){ this.window.__registeredWindow = true; this._iframeRegHandle = dijit.registerIframe(this.iframe); } if(!dojo.isIE && !dojo.isWebKit && (this.height || dojo.isMoz)){ this.editNode=this.document.body; }else{ // there's a wrapper div around the content, see _getIframeDocTxt(). this.editNode=this.document.body.firstChild; var _this = this; if(dojo.isIE){ // #4996 IE wants to focus the BODY tag this.tabStop = dojo.create('div', { tabIndex: -1 }, this.editingArea); this.iframe.onfocus = function(){ _this.editNode.setActive(); }; } } this.focusNode = this.editNode; // for InlineEditBox var events = this.events.concat(this.captureEvents); var ap = this.iframe ? this.document : this.editNode; dojo.forEach(events, function(item){ this.connect(ap, item.toLowerCase(), item); }, this); this.connect(ap, "onmouseup", "onClick"); // mouseup in the margin does not generate an onclick event if(dojo.isIE){ // IE contentEditable this.connect(this.document, "onmousedown", "_onIEMouseDown"); // #4996 fix focus // give the node Layout on IE // TODO: this may no longer be needed, since we've reverted IE to using an iframe, // not contentEditable. Removing it would also probably remove the need for creating // the extra <div> in _getIframeDocTxt() this.editNode.style.zoom = 1.0; }else{ this.connect(this.document, "onmousedown", function(){ // Clear the moveToStart focus, as mouse // down will set cursor point. Required to properly // work with selection/position driven plugins and clicks in // the window. refs: #10678 delete this._cursorToStart; }); } if(dojo.isWebKit){ //WebKit sometimes doesn't fire right on selections, so the toolbar //doesn't update right. Therefore, help it out a bit with an additional //listener. A mouse up will typically indicate a display change, so fire this //and get the toolbar to adapt. Reference: #9532 this._webkitListener = this.connect(this.document, "onmouseup", "onDisplayChanged"); this.connect(this.document, "onmousedown", function(e){ var t = e.target; if(t && (t === this.document.body || t === this.document)){ // Since WebKit uses the inner DIV, we need to check and set position. // See: #12024 as to why the change was made. setTimeout(dojo.hitch(this, "placeCursorAtEnd"), 0); } }); } if(dojo.isIE){ // Try to make sure 'hidden' elements aren't visible in edit mode (like browsers other than IE // do). See #9103 try{ this.document.execCommand('RespectVisibilityInDesign', true, null); }catch(e){/* squelch */} } this.isLoaded = true; this.set('disabled', this.disabled); // initialize content to editable (or not) // Note that setValue() call will only work after isLoaded is set to true (above) // Set up a function to allow delaying the setValue until a callback is fired // This ensures extensions like dijit.Editor have a way to hold the value set // until plugins load (and do things like register filters). var setContent = dojo.hitch(this, function(){ this.setValue(html); if(this.onLoadDeferred){ this.onLoadDeferred.callback(true); } this.onDisplayChanged(); if(this.focusOnLoad){ // after the document loads, then set focus after updateInterval expires so that // onNormalizedDisplayChanged has run to avoid input caret issues dojo.addOnLoad(dojo.hitch(this, function(){ setTimeout(dojo.hitch(this, "focus"), this.updateInterval); })); } // Save off the initial content now this.value = this.getValue(true); }); if(this.setValueDeferred){ this.setValueDeferred.addCallback(setContent); }else{ setContent(); } }, onKeyDown: function(/* Event */ e){ // summary: // Handler for onkeydown event // tags: // protected // we need this event at the moment to get the events from control keys // such as the backspace. It might be possible to add this to Dojo, so that // keyPress events can be emulated by the keyDown and keyUp detection. if(e.keyCode === dojo.keys.TAB && this.isTabIndent ){ dojo.stopEvent(e); //prevent tab from moving focus out of editor // FIXME: this is a poor-man's indent/outdent. It would be // better if it added 4 " " chars in an undoable way. // Unfortunately pasteHTML does not prove to be undoable if(this.queryCommandEnabled((e.shiftKey ? "outdent" : "indent"))){ this.execCommand((e.shiftKey ? "outdent" : "indent")); } } if(dojo.isIE){ if(e.keyCode == dojo.keys.TAB && !this.isTabIndent){ if(e.shiftKey && !e.ctrlKey && !e.altKey){ // focus the BODY so the browser will tab away from it instead this.iframe.focus(); }else if(!e.shiftKey && !e.ctrlKey && !e.altKey){ // focus the BODY so the browser will tab away from it instead this.tabStop.focus(); } }else if(e.keyCode === dojo.keys.BACKSPACE && this.document.selection.type === "Control"){ // IE has a bug where if a non-text object is selected in the editor, // hitting backspace would act as if the browser's back button was // clicked instead of deleting the object. see #1069 dojo.stopEvent(e); this.execCommand("delete"); }else if((65 <= e.keyCode && e.keyCode <= 90) || (e.keyCode>=37 && e.keyCode<=40) // FIXME: get this from connect() instead! ){ //arrow keys e.charCode = e.keyCode; this.onKeyPress(e); } } return true; }, onKeyUp: function(e){ // summary: // Handler for onkeyup event // tags: // callback return; }, setDisabled: function(/*Boolean*/ disabled){ // summary: // Deprecated, use set('disabled', ...) instead. // tags: // deprecated dojo.deprecated('dijit.Editor::setDisabled is deprecated','use dijit.Editor::attr("disabled",boolean) instead', 2.0); this.set('disabled',disabled); }, _setValueAttr: function(/*String*/ value){ // summary: // Registers that attr("value", foo) should call setValue(foo) this.setValue(value); }, _setDisableSpellCheckAttr: function(/*Boolean*/ disabled){ if(this.document){ dojo.attr(this.document.body, "spellcheck", !disabled); }else{ // try again after the editor is finished loading this.onLoadDeferred.addCallback(dojo.hitch(this, function(){ dojo.attr(this.document.body, "spellcheck", !disabled); })); } this._set("disableSpellCheck", disabled); }, onKeyPress: function(e){ // summary: // Handle the various key events // tags: // protected var c = (e.keyChar && e.keyChar.toLowerCase()) || e.keyCode, handlers = this._keyHandlers[c], args = arguments; if(handlers && !e.altKey){ dojo.some(handlers, function(h){ // treat meta- same as ctrl-, for benefit of mac users if(!(h.shift ^ e.shiftKey) && !(h.ctrl ^ (e.ctrlKey||e.metaKey))){ if(!h.handler.apply(this, args)){ e.preventDefault(); } return true; } }, this); } // function call after the character has been inserted if(!this._onKeyHitch){ this._onKeyHitch = dojo.hitch(this, "onKeyPressed"); } setTimeout(this._onKeyHitch, 1); return true; }, addKeyHandler: function(/*String*/ key, /*Boolean*/ ctrl, /*Boolean*/ shift, /*Function*/ handler){ // summary: // Add a handler for a keyboard shortcut // description: // The key argument should be in lowercase if it is a letter character // tags: // protected if(!dojo.isArray(this._keyHandlers[key])){ this._keyHandlers[key] = []; } //TODO: would be nice to make this a hash instead of an array for quick lookups this._keyHandlers[key].push({ shift: shift || false, ctrl: ctrl || false, handler: handler }); }, onKeyPressed: function(){ // summary: // Handler for after the user has pressed a key, and the display has been updated. // (Runs on a timer so that it runs after the display is updated) // tags: // private this.onDisplayChanged(/*e*/); // can't pass in e }, onClick: function(/*Event*/ e){ // summary: // Handler for when the user clicks. // tags: // private // console.info('onClick',this._tryDesignModeOn); this.onDisplayChanged(e); }, _onIEMouseDown: function(/*Event*/ e){ // summary: // IE only to prevent 2 clicks to focus // tags: // protected if(!this._focused && !this.disabled){ this.focus(); } }, _onBlur: function(e){ // summary: // Called from focus manager when focus has moved away from this editor // tags: // protected // console.info('_onBlur') this.inherited(arguments); var newValue = this.getValue(true); if(newValue != this.value){ this.onChange(newValue); } this._set("value", newValue); }, _onFocus: function(/*Event*/ e){ // summary: // Called from focus manager when focus has moved into this editor // tags: // protected // console.info('_onFocus') if(!this.disabled){ if(!this._disabledOK){ this.set('disabled', false); } this.inherited(arguments); } }, // TODO: remove in 2.0 blur: function(){ // summary: // Remove focus from this instance. // tags: // deprecated if(!dojo.isIE && this.window.document.documentElement && this.window.document.documentElement.focus){ this.window.document.documentElement.focus(); }else if(dojo.doc.body.focus){ dojo.doc.body.focus(); } }, focus: function(){ // summary: // Move focus to this editor if(!this.isLoaded){ this.focusOnLoad = true; return; } if(this._cursorToStart){ delete this._cursorToStart; if(this.editNode.childNodes){ this.placeCursorAtStart(); // this calls focus() so return return; } } if(!dojo.isIE){ dijit.focus(this.iframe); }else if(this.editNode && this.editNode.focus){ // editNode may be hidden in display:none div, lets just punt in this case //this.editNode.focus(); -> causes IE to scroll always (strict and quirks mode) to the top the Iframe // if we fire the event manually and let the browser handle the focusing, the latest // cursor position is focused like in FF this.iframe.fireEvent('onfocus', document.createEventObject()); // createEventObject only in IE // }else{ // TODO: should we throw here? // console.debug("Have no idea how to focus into the editor!"); } }, // _lastUpdate: 0, updateInterval: 200, _updateTimer: null, onDisplayChanged: function(/*Event*/ e){ // summary: // This event will be fired everytime the display context // changes and the result needs to be reflected in the UI. // description: // If you don't want to have update too often, // onNormalizedDisplayChanged should be used instead // tags: // private // var _t=new Date(); if(this._updateTimer){ clearTimeout(this._updateTimer); } if(!this._updateHandler){ this._updateHandler = dojo.hitch(this,"onNormalizedDisplayChanged"); } this._updateTimer = setTimeout(this._updateHandler, this.updateInterval); // Technically this should trigger a call to watch("value", ...) registered handlers, // but getValue() is too slow to call on every keystroke so we don't. }, onNormalizedDisplayChanged: function(){ // summary: // This event is fired every updateInterval ms or more // description: // If something needs to happen immediately after a // user change, please use onDisplayChanged instead. // tags: // private delete this._updateTimer; }, onChange: function(newContent){ // summary: // This is fired if and only if the editor loses focus and // the content is changed. }, _normalizeCommand: function(/*String*/ cmd, /*Anything?*/argument){ // summary: // Used as the advice function by dojo.connect to map our // normalized set of commands to those supported by the target // browser. // tags: // private var command = cmd.toLowerCase(); if(command == "formatblock"){ if(dojo.isSafari && argument === undefined){ command = "heading"; } }else if(command == "hilitecolor" && !dojo.isMoz){ command = "backcolor"; } return command; }, _qcaCache: {}, queryCommandAvailable: function(/*String*/ command){ // summary: // Tests whether a command is supported by the host. Clients // SHOULD check whether a command is supported before attempting // to use it, behaviour for unsupported commands is undefined. // command: // The command to test for // tags: // private // memoizing version. See _queryCommandAvailable for computing version var ca = this._qcaCache[command]; if(ca !== undefined){ return ca; } return (this._qcaCache[command] = this._queryCommandAvailable(command)); }, _queryCommandAvailable: function(/*String*/ command){ // summary: // See queryCommandAvailable(). // tags: // private var ie = 1; var mozilla = 1 << 1; var webkit = 1 << 2; var opera = 1 << 3; function isSupportedBy(browsers){ return { ie: Boolean(browsers & ie), mozilla: Boolean(browsers & mozilla), webkit: Boolean(browsers & webkit), opera: Boolean(browsers & opera) }; } var supportedBy = null; switch(command.toLowerCase()){ case "bold": case "italic": case "underline": case "subscript": case "superscript": case "fontname": case "fontsize": case "forecolor": case "hilitecolor": case "justifycenter": case "justifyfull": case "justifyleft": case "justifyright": case "delete": case "selectall": case "toggledir": supportedBy = isSupportedBy(mozilla | ie | webkit | opera); break; case "createlink": case "unlink": case "removeformat": case "inserthorizontalrule": case "insertimage": case "insertorderedlist": case "insertunorderedlist": case "indent": case "outdent": case "formatblock": case "inserthtml": case "undo": case "redo": case "strikethrough": case "tabindent": supportedBy = isSupportedBy(mozilla | ie | opera | webkit); break; case "blockdirltr": case "blockdirrtl": case "dirltr": case "dirrtl": case "inlinedirltr": case "inlinedirrtl": supportedBy = isSupportedBy(ie); break; case "cut": case "copy": case "paste": supportedBy = isSupportedBy( ie | mozilla | webkit); break; case "inserttable": supportedBy = isSupportedBy(mozilla | ie); break; case "insertcell": case "insertcol": case "insertrow": case "deletecells": case "deletecols": case "deleterows": case "mergecells": case "splitcell": supportedBy = isSupportedBy(ie | mozilla); break; default: return false; } return (dojo.isIE && supportedBy.ie) || (dojo.isMoz && supportedBy.mozilla) || (dojo.isWebKit && supportedBy.webkit) || (dojo.isOpera && supportedBy.opera); // Boolean return true if the command is supported, false otherwise }, execCommand: function(/*String*/ command, argument){ // summary: // Executes a command in the Rich Text area // command: // The command to execute // argument: // An optional argument to the command // tags: // protected var returnValue; //focus() is required for IE to work //In addition, focus() makes sure after the execution of //the command, the editor receives the focus as expected this.focus(); command = this._normalizeCommand(command, argument); if(argument !== undefined){ if(command == "heading"){ throw new Error("unimplemented"); }else if((command == "formatblock") && dojo.isIE){ argument = '<'+argument+'>'; } } //Check to see if we have any over-rides for commands, they will be functions on this //widget of the form _commandImpl. If we don't, fall through to the basic native //exec command of the browser. var implFunc = "_" + command + "Impl"; if(this[implFunc]){ returnValue = this[implFunc](argument); }else{ argument = arguments.length > 1 ? argument : null; if(argument || command!="createlink"){ returnValue = this.document.execCommand(command, false, argument); } } this.onDisplayChanged(); return returnValue; }, queryCommandEnabled: function(/*String*/ command){ // summary: // Check whether a command is enabled or not. // tags: // protected if(this.disabled || !this._disabledOK){ return false; } command = this._normalizeCommand(command); if(dojo.isMoz || dojo.isWebKit){ if(command == "unlink"){ // mozilla returns true always // console.debug(this._sCall("hasAncestorElement", ['a'])); return this._sCall("hasAncestorElement", ["a"]); }else if(command == "inserttable"){ return true; } } //see #4109 if(dojo.isWebKit){ if(command == "cut" || command == "copy") { // WebKit deems clipboard activity as a security threat and natively would return false var sel = this.window.getSelection(); if(sel){ sel = sel.toString(); } return !!sel; }else if(command == "paste"){ return true; } } var elem = dojo.isIE ? this.document.selection.createRange() : this.document; try{ return elem.queryCommandEnabled(command); }catch(e){ //Squelch, occurs if editor is hidden on FF 3 (and maybe others.) return false; } }, queryCommandState: function(command){ // summary: // Check the state of a given command and returns true or false. // tags: // protected if(this.disabled || !this._disabledOK){ return false; } command = this._normalizeCommand(command); try{ return this.document.queryCommandState(command); }catch(e){ //Squelch, occurs if editor is hidden on FF 3 (and maybe others.) return false; } }, queryCommandValue: function(command){ // summary: // Check the value of a given command. This matters most for // custom selections and complex values like font value setting. // tags: // protected if(this.disabled || !this._disabledOK){ return false; } var r; command = this._normalizeCommand(command); if(dojo.isIE && command == "formatblock"){ r = this._native2LocalFormatNames[this.document.queryCommandValue(command)]; }else if(dojo.isMoz && command === "hilitecolor"){ var oldValue; try{ oldValue = this.document.queryCommandValue("styleWithCSS"); }catch(e){ oldValue = false; } this.document.execCommand("styleWithCSS", false, true); r = this.document.queryCommandValue(command); this.document.execCommand("styleWithCSS", false, oldValue); }else{ r = this.document.queryCommandValue(command); } return r; }, // Misc. _sCall: function(name, args){ // summary: // Run the named method of dijit._editor.selection over the // current editor instance's window, with the passed args. // tags: // private return dojo.withGlobal(this.window, name, dijit._editor.selection, args); }, // FIXME: this is a TON of code duplication. Why? placeCursorAtStart: function(){ // summary: // Place the cursor at the start of the editing area. // tags: // private this.focus(); //see comments in placeCursorAtEnd var isvalid=false; if(dojo.isMoz){ // TODO: Is this branch even necessary? var first=this.editNode.firstChild; while(first){ if(first.nodeType == 3){ if(first.nodeValue.replace(/^\s+|\s+$/g, "").length>0){ isvalid=true; this._sCall("selectElement", [ first ]); break; } }else if(first.nodeType == 1){ isvalid=true; var tg = first.tagName ? first.tagName.toLowerCase() : ""; // Collapse before childless tags. if(/br|input|img|base|meta|area|basefont|hr|link/.test(tg)){ this._sCall("selectElement", [ first ]); }else{ // Collapse inside tags with children. this._sCall("selectElementChildren", [ first ]); } break; } first = first.nextSibling; } }else{ isvalid=true; this._sCall("selectElementChildren", [ this.editNode ]); } if(isvalid){ this._sCall("collapse", [ true ]); } }, placeCursorAtEnd: function(){ // summary: // Place the cursor at the end of the editing area. // tags: // private this.focus(); //In mozilla, if last child is not a text node, we have to use // selectElementChildren on this.editNode.lastChild otherwise the // cursor would be placed at the end of the closing tag of //this.editNode.lastChild var isvalid=false; if(dojo.isMoz){ var last=this.editNode.lastChild; while(last){ if(last.nodeType == 3){ if(last.nodeValue.replace(/^\s+|\s+$/g, "").length>0){ isvalid=true; this._sCall("selectElement", [ last ]); break; } }else if(last.nodeType == 1){ isvalid=true; if(last.lastChild){ this._sCall("selectElement", [ last.lastChild ]); }else{ this._sCall("selectElement", [ last ]); } break; } last = last.previousSibling; } }else{ isvalid=true; this._sCall("selectElementChildren", [ this.editNode ]); } if(isvalid){ this._sCall("collapse", [ false ]); } }, getValue: function(/*Boolean?*/ nonDestructive){ // summary: // Return the current content of the editing area (post filters // are applied). Users should call get('value') instead. // nonDestructive: // defaults to false. Should the post-filtering be run over a copy // of the live DOM? Most users should pass "true" here unless they // *really* know that none of the installed filters are going to // mess up the editing session. // tags: // private if(this.textarea){ if(this.isClosed || !this.isLoaded){ return this.textarea.value; } } return this._postFilterContent(null, nonDestructive); }, _getValueAttr: function(){ // summary: // Hook to make attr("value") work return this.getValue(true); }, setValue: function(/*String*/ html){ // summary: // This function sets the content. No undo history is preserved. // Users should use set('value', ...) instead. // tags: // deprecated // TODO: remove this and getValue() for 2.0, and move code to _setValueAttr() if(!this.isLoaded){ // try again after the editor is finished loading this.onLoadDeferred.addCallback(dojo.hitch(this, function(){ this.setValue(html); })); return; } this._cursorToStart = true; if(this.textarea && (this.isClosed || !this.isLoaded)){ this.textarea.value=html; }else{ html = this._preFilterContent(html); var node = this.isClosed ? this.domNode : this.editNode; if(html && dojo.isMoz && html.toLowerCase() == "<p></p>"){ html = "<p> </p>"; } // Use to avoid webkit problems where editor is disabled until the user clicks it if(!html && dojo.isWebKit){ html = " "; } node.innerHTML = html; this._preDomFilterContent(node); } this.onDisplayChanged(); this._set("value", this.getValue(true)); }, replaceValue: function(/*String*/ html){ // summary: // This function set the content while trying to maintain the undo stack // (now only works fine with Moz, this is identical to setValue in all // other browsers) // tags: // protected if(this.isClosed){ this.setValue(html); }else if(this.window && this.window.getSelection && !dojo.isMoz){ // Safari // look ma! it's a totally f'd browser! this.setValue(html); }else if(this.window && this.window.getSelection){ // Moz html = this._preFilterContent(html); this.execCommand("selectall"); if(!html){ this._cursorToStart = true; html = " "; } this.execCommand("inserthtml", html); this._preDomFilterContent(this.editNode); }else if(this.document && this.document.selection){//IE //In IE, when the first element is not a text node, say //an <a> tag, when replacing the content of the editing //area, the <a> tag will be around all the content //so for now, use setValue for IE too this.setValue(html); } this._set("value", this.getValue(true)); }, _preFilterContent: function(/*String*/ html){ // summary: // Filter the input before setting the content of the editing // area. DOM pre-filtering may happen after this // string-based filtering takes place but as of 1.2, this is not // guaranteed for operations such as the inserthtml command. // tags: // private var ec = html; dojo.forEach(this.contentPreFilters, function(ef){ if(ef){ ec = ef(ec); } }); return ec; }, _preDomFilterContent: function(/*DomNode*/ dom){ // summary: // filter the input's live DOM. All filter operations should be // considered to be "live" and operating on the DOM that the user // will be interacting with in their editing session. // tags: // private dom = dom || this.editNode; dojo.forEach(this.contentDomPreFilters, function(ef){ if(ef && dojo.isFunction(ef)){ ef(dom); } }, this); }, _postFilterContent: function( /*DomNode|DomNode[]|String?*/ dom, /*Boolean?*/ nonDestructive){ // summary: // filter the output after getting the content of the editing area // // description: // post-filtering allows plug-ins and users to specify any number // of transforms over the editor's content, enabling many common // use-cases such as transforming absolute to relative URLs (and // vice-versa), ensuring conformance with a particular DTD, etc. // The filters are registered in the contentDomPostFilters and // contentPostFilters arrays. Each item in the // contentDomPostFilters array is a function which takes a DOM // Node or array of nodes as its only argument and returns the // same. It is then passed down the chain for further filtering. // The contentPostFilters array behaves the same way, except each // member operates on strings. Together, the DOM and string-based // filtering allow the full range of post-processing that should // be necessaray to enable even the most agressive of post-editing // conversions to take place. // // If nonDestructive is set to "true", the nodes are cloned before // filtering proceeds to avoid potentially destructive transforms // to the content which may still needed to be edited further. // Once DOM filtering has taken place, the serialized version of // the DOM which is passed is run through each of the // contentPostFilters functions. // // dom: // a node, set of nodes, which to filter using each of the current // members of the contentDomPostFilters and contentPostFilters arrays. // // nonDestructive: // defaults to "false". If true, ensures that filtering happens on // a clone of the passed-in content and not the actual node // itself. // // tags: // private var ec; if(!dojo.isString(dom)){ dom = dom || this.editNode; if(this.contentDomPostFilters.length){ if(nonDestructive){ dom = dojo.clone(dom); } dojo.forEach(this.contentDomPostFilters, function(ef){ dom = ef(dom); }); } ec = dijit._editor.getChildrenHtml(dom); }else{ ec = dom; } if(!dojo.trim(ec.replace(/^\xA0\xA0*/, '').replace(/\xA0\xA0*$/, '')).length){ ec = ""; } // if(dojo.isIE){ // //removing appended <P> </P> for IE // ec = ec.replace(/(?:<p> </p>[\n\r]*)+$/i,""); // } dojo.forEach(this.contentPostFilters, function(ef){ ec = ef(ec); }); return ec; }, _saveContent: function(/*Event*/ e){ // summary: // Saves the content in an onunload event if the editor has not been closed // tags: // private var saveTextarea = dojo.byId(dijit._scopeName + "._editor.RichText.value"); if(saveTextarea.value){ saveTextarea.value += this._SEPARATOR; } saveTextarea.value += this.name + this._NAME_CONTENT_SEP + this.getValue(true); }, escapeXml: function(/*String*/ str, /*Boolean*/ noSingleQuotes){ // summary: // Adds escape sequences for special characters in XML. // Optionally skips escapes for single quotes // tags: // private str = str.replace(/&/gm, "&").replace(/</gm, "<").replace(/>/gm, ">").replace(/"/gm, """); if(!noSingleQuotes){ str = str.replace(/'/gm, "'"); } return str; // string }, getNodeHtml: function(/* DomNode */ node){ // summary: // Deprecated. Use dijit._editor._getNodeHtml() instead. // tags: // deprecated dojo.deprecated('dijit.Editor::getNodeHtml is deprecated','use dijit._editor.getNodeHtml instead', 2); return dijit._editor.getNodeHtml(node); // String }, getNodeChildrenHtml: function(/* DomNode */ dom){ // summary: // Deprecated. Use dijit._editor.getChildrenHtml() instead. // tags: // deprecated dojo.deprecated('dijit.Editor::getNodeChildrenHtml is deprecated','use dijit._editor.getChildrenHtml instead', 2); return dijit._editor.getChildrenHtml(dom); }, close: function(/*Boolean?*/ save){ // summary: // Kills the editor and optionally writes back the modified contents to the // element from which it originated. // save: // Whether or not to save the changes. If false, the changes are discarded. // tags: // private if(this.isClosed){ return; } if(!arguments.length){ save = true; } if(save){ this._set("value", this.getValue(true)); } // line height is squashed for iframes // FIXME: why was this here? if (this.iframe){ this.domNode.style.lineHeight = null; } if(this.interval){ clearInterval(this.interval); } if(this._webkitListener){ //Cleaup of WebKit fix: #9532 this.disconnect(this._webkitListener); delete this._webkitListener; } // Guard against memory leaks on IE (see #9268) if(dojo.isIE){ this.iframe.onfocus = null; } this.iframe._loadFunc = null; if(this._iframeRegHandle){ dijit.unregisterIframe(this._iframeRegHandle); delete this._iframeRegHandle; } if(this.textarea){ var s = this.textarea.style; s.position = ""; s.left = s.top = ""; if(dojo.isIE){ s.overflow = this.__overflow; this.__overflow = null; } this.textarea.value = this.value; dojo.destroy(this.domNode); this.domNode = this.textarea; }else{ // Note that this destroys the iframe this.domNode.innerHTML = this.value; } delete this.iframe; dojo.removeClass(this.domNode, this.baseClass); this.isClosed = true; this.isLoaded = false; delete this.editNode; delete this.focusNode; if(this.window && this.window._frameElement){ this.window._frameElement = null; } this.window = null; this.document = null; this.editingArea = null; this.editorObject = null; }, destroy: function(){ if(!this.isClosed){ this.close(false); } this.inherited(arguments); if(dijit._editor._globalSaveHandler){ delete dijit._editor._globalSaveHandler[this.id]; } }, _removeMozBogus: function(/* String */ html){ // summary: // Post filter to remove unwanted HTML attributes generated by mozilla // tags: // private return html.replace(/\stype="_moz"/gi, '').replace(/\s_moz_dirty=""/gi, '').replace(/_moz_resizing="(true|false)"/gi,''); // String }, _removeWebkitBogus: function(/* String */ html){ // summary: // Post filter to remove unwanted HTML attributes generated by webkit // tags: // private html = html.replace(/\sclass="webkit-block-placeholder"/gi, ''); html = html.replace(/\sclass="apple-style-span"/gi, ''); // For some reason copy/paste sometime adds extra meta tags for charset on // webkit (chrome) on mac.They need to be removed. See: #12007" html = html.replace(/<meta charset=\"utf-8\" \/>/gi, ''); return html; // String }, _normalizeFontStyle: function(/* String */ html){ // summary: // Convert 'strong' and 'em' to 'b' and 'i'. // description: // Moz can not handle strong/em tags correctly, so to help // mozilla and also to normalize output, convert them to 'b' and 'i'. // // Note the IE generates 'strong' and 'em' rather than 'b' and 'i' // tags: // private return html.replace(/<(\/)?strong([ \>])/gi, '<$1b$2') .replace(/<(\/)?em([ \>])/gi, '<$1i$2' ); // String }, _preFixUrlAttributes: function(/* String */ html){ // summary: // Pre-filter to do fixing to href attributes on <a> and <img> tags // tags: // private return html.replace(/(?:(<a(?=\s).*?\shref=)("|')(.*?)\2)|(?:(<a\s.*?href=)([^"'][^ >]+))/gi, '$1$4$2$3$5$2 _djrealurl=$2$3$5$2') .replace(/(?:(<img(?=\s).*?\ssrc=)("|')(.*?)\2)|(?:(<img\s.*?src=)([^"'][^ >]+))/gi, '$1$4$2$3$5$2 _djrealurl=$2$3$5$2'); // String }, /***************************************************************************** The following functions implement HTML manipulation commands for various browser/contentEditable implementations. The goal of them is to enforce standard behaviors of them. ******************************************************************************/ _inserthorizontalruleImpl: function(argument){ // summary: // This function implements the insertion of HTML 'HR' tags. // into a point on the page. IE doesn't to it right, so // we have to use an alternate form // argument: // arguments to the exec command, if any. // tags: // protected if(dojo.isIE){ return this._inserthtmlImpl("<hr>"); } return this.document.execCommand("inserthorizontalrule", false, argument); }, _unlinkImpl: function(argument){ // summary: // This function implements the unlink of an 'a' tag. // argument: // arguments to the exec command, if any. // tags: // protected if((this.queryCommandEnabled("unlink")) && (dojo.isMoz || dojo.isWebKit)){ var a = this._sCall("getAncestorElement", [ "a" ]); this._sCall("selectElement", [ a ]); return this.document.execCommand("unlink", false, null); } return this.document.execCommand("unlink", false, argument); }, _hilitecolorImpl: function(argument){ // summary: // This function implements the hilitecolor command // argument: // arguments to the exec command, if any. // tags: // protected var returnValue; if(dojo.isMoz){ // mozilla doesn't support hilitecolor properly when useCSS is // set to false (bugzilla #279330) this.document.execCommand("styleWithCSS", false, true); returnValue = this.document.execCommand("hilitecolor", false, argument); this.document.execCommand("styleWithCSS", false, false); }else{ returnValue = this.document.execCommand("hilitecolor", false, argument); } return returnValue; }, _backcolorImpl: function(argument){ // summary: // This function implements the backcolor command // argument: // arguments to the exec command, if any. // tags: // protected if(dojo.isIE){ // Tested under IE 6 XP2, no problem here, comment out // IE weirdly collapses ranges when we exec these commands, so prevent it // var tr = this.document.selection.createRange(); argument = argument ? argument : null; } return this.document.execCommand("backcolor", false, argument); }, _forecolorImpl: function(argument){ // summary: // This function implements the forecolor command // argument: // arguments to the exec command, if any. // tags: // protected if(dojo.isIE){ // Tested under IE 6 XP2, no problem here, comment out // IE weirdly collapses ranges when we exec these commands, so prevent it // var tr = this.document.selection.createRange(); argument = argument? argument : null; } return this.document.execCommand("forecolor", false, argument); }, _inserthtmlImpl: function(argument){ // summary: // This function implements the insertion of HTML content into // a point on the page. // argument: // The content to insert, if any. // tags: // protected argument = this._preFilterContent(argument); var rv = true; if(dojo.isIE){ var insertRange = this.document.selection.createRange(); if(this.document.selection.type.toUpperCase() == 'CONTROL'){ var n=insertRange.item(0); while(insertRange.length){ insertRange.remove(insertRange.item(0)); } n.outerHTML=argument; }else{ insertRange.pasteHTML(argument); } insertRange.select(); //insertRange.collapse(true); }else if(dojo.isMoz && !argument.length){ //mozilla can not inserthtml an empty html to delete current selection //so we delete the selection instead in this case this._sCall("remove"); // FIXME }else{ rv = this.document.execCommand("inserthtml", false, argument); } return rv; }, _boldImpl: function(argument){ // summary: // This function implements an over-ride of the bold command. // argument: // Not used, operates by selection. // tags: // protected if(dojo.isIE){ this._adaptIESelection() } return this.document.execCommand("bold", false, argument); }, _italicImpl: function(argument){ // summary: // This function implements an over-ride of the italic command. // argument: // Not used, operates by selection. // tags: // protected if(dojo.isIE){ this._adaptIESelection() } return this.document.execCommand("italic", false, argument); }, _underlineImpl: function(argument){ // summary: // This function implements an over-ride of the underline command. // argument: // Not used, operates by selection. // tags: // protected if(dojo.isIE){ this._adaptIESelection() } return this.document.execCommand("underline", false, argument); }, _strikethroughImpl: function(argument){ // summary: // This function implements an over-ride of the strikethrough command. // argument: // Not used, operates by selection. // tags: // protected if(dojo.isIE){ this._adaptIESelection() } return this.document.execCommand("strikethrough", false, argument); }, getHeaderHeight: function(){ // summary: // A function for obtaining the height of the header node return this._getNodeChildrenHeight(this.header); // Number }, getFooterHeight: function(){ // summary: // A function for obtaining the height of the footer node return this._getNodeChildrenHeight(this.footer); // Number }, _getNodeChildrenHeight: function(node){ // summary: // An internal function for computing the cumulative height of all child nodes of 'node' // node: // The node to process the children of; var h = 0; if(node && node.childNodes){ // IE didn't compute it right when position was obtained on the node directly is some cases, // so we have to walk over all the children manually. var i; for(i = 0; i < node.childNodes.length; i++){ var size = dojo.position(node.childNodes[i]); h += size.h; } } return h; // Number }, _isNodeEmpty: function(node, startOffset){ // summary: // Function to test if a node is devoid of real content. // node: // The node to check. // tags: // private. if(node.nodeType == 1/*element*/){ if(node.childNodes.length > 0){ return this._isNodeEmpty(node.childNodes[0], startOffset); } return true; }else if(node.nodeType == 3/*text*/){ return (node.nodeValue.substring(startOffset) == ""); } return false; }, _removeStartingRangeFromRange: function(node, range){ // summary: // Function to adjust selection range by removing the current // start node. // node: // The node to remove from the starting range. // range: // The range to adapt. // tags: // private if(node.nextSibling){ range.setStart(node.nextSibling,0); }else{ var parent = node.parentNode; while(parent && parent.nextSibling == null){ //move up the tree until we find a parent that has another node, that node will be the next node parent = parent.parentNode; } if(parent){ range.setStart(parent.nextSibling,0); } } return range; }, _adaptIESelection: function(){ // summary: // Function to adapt the IE range by removing leading 'newlines' // Needed to fix issue with bold/italics/underline not working if // range included leading 'newlines'. // In IE, if a user starts a selection at the very end of a line, // then the native browser commands will fail to execute correctly. // To work around the issue, we can remove all empty nodes from // the start of the range selection. var selection = dijit.range.getSelection(this.window); if(selection && selection.rangeCount && !selection.isCollapsed){ var range = selection.getRangeAt(0); var firstNode = range.startContainer; var startOffset = range.startOffset; while(firstNode.nodeType == 3/*text*/ && startOffset >= firstNode.length && firstNode.nextSibling){ //traverse the text nodes until we get to the one that is actually highlighted startOffset = startOffset - firstNode.length; firstNode = firstNode.nextSibling; } //Remove the starting ranges until the range does not start with an empty node. var lastNode=null; while(this._isNodeEmpty(firstNode, startOffset) && firstNode != lastNode){ lastNode =firstNode; //this will break the loop in case we can't find the next sibling range = this._removeStartingRangeFromRange(firstNode, range); //move the start container to the next node in the range firstNode = range.startContainer; startOffset = 0; //start at the beginning of the new starting range } selection.removeAllRanges();// this will work as long as users cannot select multiple ranges. I have not been able to do that in the editor. selection.addRange(range); } }});return dijit._editor.RichText;});
|
data/javascript/127.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
define("dijit/form/ComboBox", ["dojo", "dijit", "text!dijit/form/templates/DropDownBox.html", "dojo/window", "dojo/regexp", "dojo/data/util/simpleFetch", "dojo/data/util/filter", "dijit/_CssStateMixin", "dijit/form/_FormWidget", "dijit/form/ValidationTextBox", "dijit/_HasDropDown", "i18n!dijit/form/nls/ComboBox"], function(dojo, dijit) {dojo.declare( "dijit.form.ComboBoxMixin", dijit._HasDropDown, { // summary: // Implements the base functionality for `dijit.form.ComboBox`/`dijit.form.FilteringSelect` // description: // All widgets that mix in dijit.form.ComboBoxMixin must extend `dijit.form._FormValueWidget`. // tags: // protected // item: Object // This is the item returned by the dojo.data.store implementation that // provides the data for this ComboBox, it's the currently selected item. item: null, // pageSize: Integer // Argument to data provider. // Specifies number of search results per page (before hitting "next" button) pageSize: Infinity, // store: [const] Object // Reference to data provider object used by this ComboBox store: null, // fetchProperties: Object // Mixin to the dojo.data store's fetch. // For example, to set the sort order of the ComboBox menu, pass: // | { sort: [{attribute:"name",descending: true}] } // To override the default queryOptions so that deep=false, do: // | { queryOptions: {ignoreCase: true, deep: false} } fetchProperties:{}, // query: Object // A query that can be passed to 'store' to initially filter the items, // before doing further filtering based on `searchAttr` and the key. // Any reference to the `searchAttr` is ignored. query: {}, // autoComplete: Boolean // If user types in a partial string, and then tab out of the `<input>` box, // automatically copy the first entry displayed in the drop down list to // the `<input>` field autoComplete: true, // highlightMatch: String // One of: "first", "all" or "none". // // If the ComboBox/FilteringSelect opens with the search results and the searched // string can be found, it will be highlighted. If set to "all" // then will probably want to change `queryExpr` parameter to '*${0}*' // // Highlighting is only performed when `labelType` is "text", so as to not // interfere with any HTML markup an HTML label might contain. highlightMatch: "first", // searchDelay: Integer // Delay in milliseconds between when user types something and we start // searching based on that value searchDelay: 100, // searchAttr: String // Search for items in the data store where this attribute (in the item) // matches what the user typed searchAttr: "name", // labelAttr: String? // The entries in the drop down list come from this attribute in the // dojo.data items. // If not specified, the searchAttr attribute is used instead. labelAttr: "", // labelType: String // Specifies how to interpret the labelAttr in the data store items. // Can be "html" or "text". labelType: "text", // queryExpr: String // This specifies what query ComboBox/FilteringSelect sends to the data store, // based on what the user has typed. Changing this expression will modify // whether the drop down shows only exact matches, a "starting with" match, // etc. Use it in conjunction with highlightMatch. // dojo.data query expression pattern. // `${0}` will be substituted for the user text. // `*` is used for wildcards. // `${0}*` means "starts with", `*${0}*` means "contains", `${0}` means "is" queryExpr: "${0}*", // ignoreCase: Boolean // Set true if the ComboBox/FilteringSelect should ignore case when matching possible items ignoreCase: true, // hasDownArrow: Boolean // Set this textbox to have a down arrow button, to display the drop down list. // Defaults to true. hasDownArrow: true, templateString: dojo.cache("dijit.form", "templates/DropDownBox.html"), baseClass: "dijitTextBox dijitComboBox", // dropDownClass: [protected extension] String // Name of the dropdown widget class used to select a date/time. // Subclasses should specify this. dropDownClass: "dijit.form._ComboBoxMenu", // Set classes like dijitDownArrowButtonHover depending on // mouse action over button node cssStateNodes: { "_buttonNode": "dijitDownArrowButton" }, // Flags to _HasDropDown to limit height of drop down to make it fit in viewport maxHeight: -1, // For backwards compatibility let onClick events propagate, even clicks on the down arrow button _stopClickEvents: false, _getCaretPos: function(/*DomNode*/ element){ // khtml 3.5.2 has selection* methods as does webkit nightlies from 2005-06-22 var pos = 0; if(typeof(element.selectionStart) == "number"){ // FIXME: this is totally borked on Moz < 1.3. Any recourse? pos = element.selectionStart; }else if(dojo.isIE){ // in the case of a mouse click in a popup being handled, // then the dojo.doc.selection is not the textarea, but the popup // var r = dojo.doc.selection.createRange(); // hack to get IE 6 to play nice. What a POS browser. var tr = dojo.doc.selection.createRange().duplicate(); var ntr = element.createTextRange(); tr.move("character",0); ntr.move("character",0); try{ // If control doesn't have focus, you get an exception. // Seems to happen on reverse-tab, but can also happen on tab (seems to be a race condition - only happens sometimes). // There appears to be no workaround for this - googled for quite a while. ntr.setEndPoint("EndToEnd", tr); pos = String(ntr.text).replace(/\r/g,"").length; }catch(e){ // If focus has shifted, 0 is fine for caret pos. } } return pos; }, _setCaretPos: function(/*DomNode*/ element, /*Number*/ location){ location = parseInt(location); dijit.selectInputText(element, location, location); }, _setDisabledAttr: function(/*Boolean*/ value){ // Additional code to set disabled state of ComboBox node. // Overrides _FormValueWidget._setDisabledAttr() or ValidationTextBox._setDisabledAttr(). this.inherited(arguments); dijit.setWaiState(this.domNode, "disabled", value); }, _abortQuery: function(){ // stop in-progress query if(this.searchTimer){ clearTimeout(this.searchTimer); this.searchTimer = null; } if(this._fetchHandle){ if(this._fetchHandle.abort){ this._fetchHandle.abort(); } this._fetchHandle = null; } }, _onInput: function(/*Event*/ evt){ // summary: // Handles paste events if(!this.searchTimer && (evt.type == 'paste'/*IE|WebKit*/ || evt.type == 'input'/*Firefox*/) && this._lastInput != this.textbox.value){ this.searchTimer = setTimeout(dojo.hitch(this, function(){ this._onKey({charOrCode: 229}); // fake IME key to cause a search }), 100); // long delay that will probably be preempted by keyboard input } this.inherited(arguments); }, _onKey: function(/*Event*/ evt){ // summary: // Handles keyboard events var key = evt.charOrCode; // except for cutting/pasting case - ctrl + x/v if(evt.altKey || ((evt.ctrlKey || evt.metaKey) && (key != 'x' && key != 'v')) || key == dojo.keys.SHIFT){ return; // throw out weird key combinations and spurious events } var doSearch = false; var pw = this.dropDown; var dk = dojo.keys; var highlighted = null; this._prev_key_backspace = false; this._abortQuery(); // _HasDropDown will do some of the work: // 1. when drop down is not yet shown: // - if user presses the down arrow key, call loadDropDown() // 2. when drop down is already displayed: // - on ESC key, call closeDropDown() // - otherwise, call dropDown.handleKey() to process the keystroke this.inherited(arguments); if(this._opened){ highlighted = pw.getHighlightedOption(); } switch(key){ case dk.PAGE_DOWN: case dk.DOWN_ARROW: case dk.PAGE_UP: case dk.UP_ARROW: // Keystroke caused ComboBox_menu to move to a different item. // Copy new item to <input> box. if(this._opened){ this._announceOption(highlighted); } dojo.stopEvent(evt); break; case dk.ENTER: // prevent submitting form if user presses enter. Also // prevent accepting the value if either Next or Previous // are selected if(highlighted){ // only stop event on prev/next if(highlighted == pw.nextButton){ this._nextSearch(1); dojo.stopEvent(evt); break; }else if(highlighted == pw.previousButton){ this._nextSearch(-1); dojo.stopEvent(evt); break; } }else{ // Update 'value' (ex: KY) according to currently displayed text this._setBlurValue(); // set value if needed this._setCaretPos(this.focusNode, this.focusNode.value.length); // move cursor to end and cancel highlighting } // default case: // if enter pressed while drop down is open, or for FilteringSelect, // if we are in the middle of a query to convert a directly typed in value to an item, // prevent submit, but allow event to bubble if(this._opened || this._fetchHandle){ evt.preventDefault(); } // fall through case dk.TAB: var newvalue = this.get('displayedValue'); // if the user had More Choices selected fall into the // _onBlur handler if(pw && ( newvalue == pw._messages["previousMessage"] || newvalue == pw._messages["nextMessage"]) ){ break; } if(highlighted){ this._selectOption(); } if(this._opened){ this._lastQuery = null; // in case results come back later this.closeDropDown(); } break; case ' ': if(highlighted){ // user is effectively clicking a choice in the drop down menu dojo.stopEvent(evt); this._selectOption(); this.closeDropDown(); }else{ // user typed a space into the input box, treat as normal character doSearch = true; } break; case dk.DELETE: case dk.BACKSPACE: this._prev_key_backspace = true; doSearch = true; break; default: // Non char keys (F1-F12 etc..) shouldn't open list. // Ascii characters and IME input (Chinese, Japanese etc.) should. //IME input produces keycode == 229. doSearch = typeof key == 'string' || key == 229; } if(doSearch){ // need to wait a tad before start search so that the event // bubbles through DOM and we have value visible this.item = undefined; // undefined means item needs to be set this.searchTimer = setTimeout(dojo.hitch(this, "_startSearchFromInput"),1); } }, _autoCompleteText: function(/*String*/ text){ // summary: // Fill in the textbox with the first item from the drop down // list, and highlight the characters that were // auto-completed. For example, if user typed "CA" and the // drop down list appeared, the textbox would be changed to // "California" and "ifornia" would be highlighted. var fn = this.focusNode; // IE7: clear selection so next highlight works all the time dijit.selectInputText(fn, fn.value.length); // does text autoComplete the value in the textbox? var caseFilter = this.ignoreCase? 'toLowerCase' : 'substr'; if(text[caseFilter](0).indexOf(this.focusNode.value[caseFilter](0)) == 0){ var cpos = this._getCaretPos(fn); // only try to extend if we added the last character at the end of the input if((cpos+1) > fn.value.length){ // only add to input node as we would overwrite Capitalisation of chars // actually, that is ok fn.value = text;//.substr(cpos); // visually highlight the autocompleted characters dijit.selectInputText(fn, cpos); } }else{ // text does not autoComplete; replace the whole value and highlight fn.value = text; dijit.selectInputText(fn); } }, _openResultList: function(/*Object*/ results, /*Object*/ dataObject){ // summary: // Callback when a search completes. // description: // 1. generates drop-down list and calls _showResultList() to display it // 2. if this result list is from user pressing "more choices"/"previous choices" // then tell screen reader to announce new option this._fetchHandle = null; if( this.disabled || this.readOnly || (dataObject.query[this.searchAttr] != this._lastQuery) ){ return; } var wasSelected = this.dropDown._highlighted_option && dojo.hasClass(this.dropDown._highlighted_option, "dijitMenuItemSelected"); this.dropDown.clearResultList(); if(!results.length && !this._maxOptions){ // if no results and not just the previous choices button this.closeDropDown(); return; } // Fill in the textbox with the first item from the drop down list, // and highlight the characters that were auto-completed. For // example, if user typed "CA" and the drop down list appeared, the // textbox would be changed to "California" and "ifornia" would be // highlighted. dataObject._maxOptions = this._maxOptions; var nodes = this.dropDown.createOptions( results, dataObject, dojo.hitch(this, "_getMenuLabelFromItem") ); // show our list (only if we have content, else nothing) this._showResultList(); // #4091: // tell the screen reader that the paging callback finished by // shouting the next choice if(dataObject.direction){ if(1 == dataObject.direction){ this.dropDown.highlightFirstOption(); }else if(-1 == dataObject.direction){ this.dropDown.highlightLastOption(); } if(wasSelected){ this._announceOption(this.dropDown.getHighlightedOption()); } }else if(this.autoComplete && !this._prev_key_backspace // when the user clicks the arrow button to show the full list, // startSearch looks for "*". // it does not make sense to autocomplete // if they are just previewing the options available. && !/^[*]+$/.test(dataObject.query[this.searchAttr])){ this._announceOption(nodes[1]); // 1st real item } }, _showResultList: function(){ // summary: // Display the drop down if not already displayed, or if it is displayed, then // reposition it if necessary (reposition may be necessary if drop down's height changed). this.closeDropDown(true); // hide the tooltip this.displayMessage(""); this.openDropDown(); dijit.setWaiState(this.domNode, "expanded", "true"); }, loadDropDown: function(/*Function*/ callback){ // Overrides _HasDropDown.loadDropDown(). // This is called when user has pressed button icon or pressed the down arrow key // to open the drop down. this._startSearchAll(); }, isLoaded: function(){ // signal to _HasDropDown that it needs to call loadDropDown() to load the // drop down asynchronously before displaying it return false; }, closeDropDown: function(){ // Overrides _HasDropDown.closeDropDown(). Closes the drop down (assuming that it's open). // This method is the callback when the user types ESC or clicking // the button icon while the drop down is open. It's also called by other code. this._abortQuery(); if(this._opened){ this.inherited(arguments); dijit.setWaiState(this.domNode, "expanded", "false"); dijit.removeWaiState(this.focusNode,"activedescendant"); } }, _setBlurValue: function(){ // if the user clicks away from the textbox OR tabs away, set the // value to the textbox value // #4617: // if value is now more choices or previous choices, revert // the value var newvalue = this.get('displayedValue'); var pw = this.dropDown; if(pw && ( newvalue == pw._messages["previousMessage"] || newvalue == pw._messages["nextMessage"] ) ){ this._setValueAttr(this._lastValueReported, true); }else if(typeof this.item == "undefined"){ // Update 'value' (ex: KY) according to currently displayed text this.item = null; this.set('displayedValue', newvalue); }else{ if(this.value != this._lastValueReported){ dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true); } this._refreshState(); } }, _onBlur: function(){ // summary: // Called magically when focus has shifted away from this widget and it's drop down this.closeDropDown(); this.inherited(arguments); }, _setItemAttr: function(/*item*/ item, /*Boolean?*/ priorityChange, /*String?*/ displayedValue){ // summary: // Set the displayed valued in the input box, and the hidden value // that gets submitted, based on a dojo.data store item. // description: // Users shouldn't call this function; they should be calling // set('item', value) // tags: // private if(!displayedValue){ displayedValue = this.store.getValue(item, this.searchAttr); } var value = this._getValueField() != this.searchAttr? this.store.getIdentity(item) : displayedValue; this._set("item", item); dijit.form.ComboBox.superclass._setValueAttr.call(this, value, priorityChange, displayedValue); }, _announceOption: function(/*Node*/ node){ // summary: // a11y code that puts the highlighted option in the textbox. // This way screen readers will know what is happening in the // menu. if(!node){ return; } // pull the text value from the item attached to the DOM node var newValue; if(node == this.dropDown.nextButton || node == this.dropDown.previousButton){ newValue = node.innerHTML; this.item = undefined; this.value = ''; }else{ newValue = this.store.getValue(node.item, this.searchAttr).toString(); this.set('item', node.item, false, newValue); } // get the text that the user manually entered (cut off autocompleted text) this.focusNode.value = this.focusNode.value.substring(0, this._lastInput.length); // set up ARIA activedescendant dijit.setWaiState(this.focusNode, "activedescendant", dojo.attr(node, "id")); // autocomplete the rest of the option to announce change this._autoCompleteText(newValue); }, _selectOption: function(/*Event*/ evt){ // summary: // Menu callback function, called when an item in the menu is selected. if(evt){ this._announceOption(evt.target); } this.closeDropDown(); this._setCaretPos(this.focusNode, this.focusNode.value.length); dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true); // set this.value and fire onChange }, _startSearchAll: function(){ this._startSearch(''); }, _startSearchFromInput: function(){ this._startSearch(this.focusNode.value.replace(/([\\\*\?])/g, "\\$1")); }, _getQueryString: function(/*String*/ text){ return dojo.string.substitute(this.queryExpr, [text]); }, _startSearch: function(/*String*/ key){ // summary: // Starts a search for elements matching key (key=="" means to return all items), // and calls _openResultList() when the search completes, to display the results. if(!this.dropDown){ var popupId = this.id + "_popup", dropDownConstructor = dojo.getObject(this.dropDownClass, false); this.dropDown = new dropDownConstructor({ onChange: dojo.hitch(this, this._selectOption), id: popupId, dir: this.dir }); dijit.removeWaiState(this.focusNode,"activedescendant"); dijit.setWaiState(this.textbox,"owns",popupId); // associate popup with textbox } // create a new query to prevent accidentally querying for a hidden // value from FilteringSelect's keyField var query = dojo.clone(this.query); // #5970 this._lastInput = key; // Store exactly what was entered by the user. this._lastQuery = query[this.searchAttr] = this._getQueryString(key); // #5970: set _lastQuery, *then* start the timeout // otherwise, if the user types and the last query returns before the timeout, // _lastQuery won't be set and their input gets rewritten this.searchTimer=setTimeout(dojo.hitch(this, function(query, _this){ this.searchTimer = null; var fetch = { queryOptions: { ignoreCase: this.ignoreCase, deep: true }, query: query, onBegin: dojo.hitch(this, "_setMaxOptions"), onComplete: dojo.hitch(this, "_openResultList"), onError: function(errText){ _this._fetchHandle = null; console.error('dijit.form.ComboBox: ' + errText); _this.closeDropDown(); }, start: 0, count: this.pageSize }; dojo.mixin(fetch, _this.fetchProperties); this._fetchHandle = _this.store.fetch(fetch); var nextSearch = function(dataObject, direction){ dataObject.start += dataObject.count*direction; // #4091: // tell callback the direction of the paging so the screen // reader knows which menu option to shout dataObject.direction = direction; this._fetchHandle = this.store.fetch(dataObject); this.focus(); }; this._nextSearch = this.dropDown.onPage = dojo.hitch(this, nextSearch, this._fetchHandle); }, query, this), this.searchDelay); }, _setMaxOptions: function(size, request){ this._maxOptions = size; }, _getValueField: function(){ // summary: // Helper for postMixInProperties() to set this.value based on data inlined into the markup. // Returns the attribute name in the item (in dijit.form._ComboBoxDataStore) to use as the value. return this.searchAttr; }, //////////// INITIALIZATION METHODS /////////////////////////////////////// constructor: function(){ this.query={}; this.fetchProperties={}; }, postMixInProperties: function(){ if(!this.store){ var srcNodeRef = this.srcNodeRef; // if user didn't specify store, then assume there are option tags this.store = new dijit.form._ComboBoxDataStore(srcNodeRef); // if there is no value set and there is an option list, set // the value to the first value to be consistent with native // Select // Firefox and Safari set value // IE6 and Opera set selectedIndex, which is automatically set // by the selected attribute of an option tag // IE6 does not set value, Opera sets value = selectedIndex if(!("value" in this.params)){ var item = (this.item = this.store.fetchSelectedItem()); if(item){ var valueField = this._getValueField(); this.value = this.store.getValue(item, valueField); } } } this.inherited(arguments); }, postCreate: function(){ // summary: // Subclasses must call this method from their postCreate() methods // tags: // protected // find any associated label element and add to ComboBox node. var label=dojo.query('label[for="'+this.id+'"]'); if(label.length){ label[0].id = (this.id+"_label"); dijit.setWaiState(this.domNode, "labelledby", label[0].id); } this.inherited(arguments); }, _setHasDownArrowAttr: function(val){ this.hasDownArrow = val; this._buttonNode.style.display = val ? "" : "none"; }, _getMenuLabelFromItem: function(/*Item*/ item){ var label = this.labelFunc(item, this.store), labelType = this.labelType; // If labelType is not "text" we don't want to screw any markup ot whatever. if(this.highlightMatch != "none" && this.labelType == "text" && this._lastInput){ label = this.doHighlight(label, this._escapeHtml(this._lastInput)); labelType = "html"; } return {html: labelType == "html", label: label}; }, doHighlight: function(/*String*/ label, /*String*/ find){ // summary: // Highlights the string entered by the user in the menu. By default this // highlights the first occurrence found. Override this method // to implement your custom highlighting. // tags: // protected var // Add (g)lobal modifier when this.highlightMatch == "all" and (i)gnorecase when this.ignoreCase == true modifiers = (this.ignoreCase ? "i" : "") + (this.highlightMatch == "all" ? "g" : ""), i = this.queryExpr.indexOf("${0}"); find = dojo.regexp.escapeString(find); // escape regexp special chars return this._escapeHtml(label).replace( // prepend ^ when this.queryExpr == "${0}*" and append $ when this.queryExpr == "*${0}" new RegExp((i == 0 ? "^" : "") + "("+ find +")" + (i == (this.queryExpr.length - 4) ? "$" : ""), modifiers), '<span class="dijitComboBoxHighlightMatch">$1</span>' ); // returns String, (almost) valid HTML (entities encoded) }, _escapeHtml: function(/*String*/ str){ // TODO Should become dojo.html.entities(), when exists use instead // summary: // Adds escape sequences for special characters in XML: &<>"' str = String(str).replace(/&/gm, "&").replace(/</gm, "<") .replace(/>/gm, ">").replace(/"/gm, """); return str; // string }, reset: function(){ // Overrides the _FormWidget.reset(). // Additionally reset the .item (to clean up). this.item = null; this.inherited(arguments); }, labelFunc: function(/*item*/ item, /*dojo.data.store*/ store){ // summary: // Computes the label to display based on the dojo.data store item. // returns: // The label that the ComboBox should display // tags: // private // Use toString() because XMLStore returns an XMLItem whereas this // method is expected to return a String (#9354) return store.getValue(item, this.labelAttr || this.searchAttr).toString(); // String } });dojo.declare( "dijit.form._ComboBoxMenu", [dijit._Widget, dijit._Templated, dijit._CssStateMixin], { // summary: // Focus-less menu for internal use in `dijit.form.ComboBox` // tags: // private templateString: "<ul class='dijitReset dijitMenu' dojoAttachEvent='onmousedown:_onMouseDown,onmouseup:_onMouseUp,onmouseover:_onMouseOver,onmouseout:_onMouseOut' style='overflow: \"auto\"; overflow-x: \"hidden\";'>" +"<li class='dijitMenuItem dijitMenuPreviousButton' dojoAttachPoint='previousButton' role='option'></li>" +"<li class='dijitMenuItem dijitMenuNextButton' dojoAttachPoint='nextButton' role='option'></li>" +"</ul>", // _messages: Object // Holds "next" and "previous" text for paging buttons on drop down _messages: null, baseClass: "dijitComboBoxMenu", postMixInProperties: function(){ this.inherited(arguments); this._messages = dojo.i18n.getLocalization("dijit.form", "ComboBox", this.lang); }, buildRendering: function(){ this.inherited(arguments); // fill in template with i18n messages this.previousButton.innerHTML = this._messages["previousMessage"]; this.nextButton.innerHTML = this._messages["nextMessage"]; }, _setValueAttr: function(/*Object*/ value){ this.value = value; this.onChange(value); }, // stubs onChange: function(/*Object*/ value){ // summary: // Notifies ComboBox/FilteringSelect that user clicked an option in the drop down menu. // Probably should be called onSelect. // tags: // callback }, onPage: function(/*Number*/ direction){ // summary: // Notifies ComboBox/FilteringSelect that user clicked to advance to next/previous page. // tags: // callback }, onClose: function(){ // summary: // Callback from dijit.popup code to this widget, notifying it that it closed // tags: // private this._blurOptionNode(); }, _createOption: function(/*Object*/ item, labelFunc){ // summary: // Creates an option to appear on the popup menu subclassed by // `dijit.form.FilteringSelect`. var menuitem = dojo.create("li", { "class": "dijitReset dijitMenuItem" +(this.isLeftToRight() ? "" : " dijitMenuItemRtl"), role: "option" }); var labelObject = labelFunc(item); if(labelObject.html){ menuitem.innerHTML = labelObject.label; }else{ menuitem.appendChild( dojo.doc.createTextNode(labelObject.label) ); } // #3250: in blank options, assign a normal height if(menuitem.innerHTML == ""){ menuitem.innerHTML = " "; } menuitem.item=item; return menuitem; }, createOptions: function(results, dataObject, labelFunc){ // summary: // Fills in the items in the drop down list // results: // Array of dojo.data items // dataObject: // dojo.data store // labelFunc: // Function to produce a label in the drop down list from a dojo.data item //this._dataObject=dataObject; //this._dataObject.onComplete=dojo.hitch(comboBox, comboBox._openResultList); // display "Previous . . ." button this.previousButton.style.display = (dataObject.start == 0) ? "none" : ""; dojo.attr(this.previousButton, "id", this.id + "_prev"); // create options using _createOption function defined by parent // ComboBox (or FilteringSelect) class // #2309: // iterate over cache nondestructively dojo.forEach(results, function(item, i){ var menuitem = this._createOption(item, labelFunc); dojo.attr(menuitem, "id", this.id + i); this.domNode.insertBefore(menuitem, this.nextButton); }, this); // display "Next . . ." button var displayMore = false; //Try to determine if we should show 'more'... if(dataObject._maxOptions && dataObject._maxOptions != -1){ if((dataObject.start + dataObject.count) < dataObject._maxOptions){ displayMore = true; }else if((dataObject.start + dataObject.count) > dataObject._maxOptions && dataObject.count == results.length){ //Weird return from a datastore, where a start + count > maxOptions // implies maxOptions isn't really valid and we have to go into faking it. //And more or less assume more if count == results.length displayMore = true; } }else if(dataObject.count == results.length){ //Don't know the size, so we do the best we can based off count alone. //So, if we have an exact match to count, assume more. displayMore = true; } this.nextButton.style.display = displayMore ? "" : "none"; dojo.attr(this.nextButton,"id", this.id + "_next"); return this.domNode.childNodes; }, clearResultList: function(){ // summary: // Clears the entries in the drop down list, but of course keeps the previous and next buttons. while(this.domNode.childNodes.length>2){ this.domNode.removeChild(this.domNode.childNodes[this.domNode.childNodes.length-2]); } this._blurOptionNode(); }, _onMouseDown: function(/*Event*/ evt){ dojo.stopEvent(evt); }, _onMouseUp: function(/*Event*/ evt){ if(evt.target === this.domNode || !this._highlighted_option){ // !this._highlighted_option check to prevent immediate selection when menu appears on top // of <input>, see #9898. Note that _HasDropDown also has code to prevent this. return; }else if(evt.target == this.previousButton){ this._blurOptionNode(); this.onPage(-1); }else if(evt.target == this.nextButton){ this._blurOptionNode(); this.onPage(1); }else{ var tgt = evt.target; // while the clicked node is inside the div while(!tgt.item){ // recurse to the top tgt = tgt.parentNode; } this._setValueAttr({ target: tgt }, true); } }, _onMouseOver: function(/*Event*/ evt){ if(evt.target === this.domNode){ return; } var tgt = evt.target; if(!(tgt == this.previousButton || tgt == this.nextButton)){ // while the clicked node is inside the div while(!tgt.item){ // recurse to the top tgt = tgt.parentNode; } } this._focusOptionNode(tgt); }, _onMouseOut: function(/*Event*/ evt){ if(evt.target === this.domNode){ return; } this._blurOptionNode(); }, _focusOptionNode: function(/*DomNode*/ node){ // summary: // Does the actual highlight. if(this._highlighted_option != node){ this._blurOptionNode(); this._highlighted_option = node; dojo.addClass(this._highlighted_option, "dijitMenuItemSelected"); } }, _blurOptionNode: function(){ // summary: // Removes highlight on highlighted option. if(this._highlighted_option){ dojo.removeClass(this._highlighted_option, "dijitMenuItemSelected"); this._highlighted_option = null; } }, _highlightNextOption: function(){ // summary: // Highlight the item just below the current selection. // If nothing selected, highlight first option. // because each press of a button clears the menu, // the highlighted option sometimes becomes detached from the menu! // test to see if the option has a parent to see if this is the case. if(!this.getHighlightedOption()){ var fc = this.domNode.firstChild; this._focusOptionNode(fc.style.display == "none" ? fc.nextSibling : fc); }else{ var ns = this._highlighted_option.nextSibling; if(ns && ns.style.display != "none"){ this._focusOptionNode(ns); }else{ this.highlightFirstOption(); } } // scrollIntoView is called outside of _focusOptionNode because in IE putting it inside causes the menu to scroll up on mouseover dojo.window.scrollIntoView(this._highlighted_option); }, highlightFirstOption: function(){ // summary: // Highlight the first real item in the list (not Previous Choices). var first = this.domNode.firstChild; var second = first.nextSibling; this._focusOptionNode(second.style.display == "none" ? first : second); // remotely possible that Previous Choices is the only thing in the list dojo.window.scrollIntoView(this._highlighted_option); }, highlightLastOption: function(){ // summary: // Highlight the last real item in the list (not More Choices). this._focusOptionNode(this.domNode.lastChild.previousSibling); dojo.window.scrollIntoView(this._highlighted_option); }, _highlightPrevOption: function(){ // summary: // Highlight the item just above the current selection. // If nothing selected, highlight last option (if // you select Previous and try to keep scrolling up the list). if(!this.getHighlightedOption()){ var lc = this.domNode.lastChild; this._focusOptionNode(lc.style.display == "none" ? lc.previousSibling : lc); }else{ var ps = this._highlighted_option.previousSibling; if(ps && ps.style.display != "none"){ this._focusOptionNode(ps); }else{ this.highlightLastOption(); } } dojo.window.scrollIntoView(this._highlighted_option); }, _page: function(/*Boolean*/ up){ // summary: // Handles page-up and page-down keypresses var scrollamount = 0; var oldscroll = this.domNode.scrollTop; var height = dojo.style(this.domNode, "height"); // if no item is highlighted, highlight the first option if(!this.getHighlightedOption()){ this._highlightNextOption(); } while(scrollamount<height){ if(up){ // stop at option 1 if(!this.getHighlightedOption().previousSibling || this._highlighted_option.previousSibling.style.display == "none"){ break; } this._highlightPrevOption(); }else{ // stop at last option if(!this.getHighlightedOption().nextSibling || this._highlighted_option.nextSibling.style.display == "none"){ break; } this._highlightNextOption(); } // going backwards var newscroll=this.domNode.scrollTop; scrollamount+=(newscroll-oldscroll)*(up ? -1:1); oldscroll=newscroll; } }, pageUp: function(){ // summary: // Handles pageup keypress. // TODO: just call _page directly from handleKey(). // tags: // private this._page(true); }, pageDown: function(){ // summary: // Handles pagedown keypress. // TODO: just call _page directly from handleKey(). // tags: // private this._page(false); }, getHighlightedOption: function(){ // summary: // Returns the highlighted option. var ho = this._highlighted_option; return (ho && ho.parentNode) ? ho : null; }, handleKey: function(evt){ // summary: // Handle keystroke event forwarded from ComboBox, returning false if it's // a keystroke I recognize and process, true otherwise. switch(evt.charOrCode){ case dojo.keys.DOWN_ARROW: this._highlightNextOption(); return false; case dojo.keys.PAGE_DOWN: this.pageDown(); return false; case dojo.keys.UP_ARROW: this._highlightPrevOption(); return false; case dojo.keys.PAGE_UP: this.pageUp(); return false; default: return true; } } });dojo.declare( "dijit.form.ComboBox", [dijit.form.ValidationTextBox, dijit.form.ComboBoxMixin], { // summary: // Auto-completing text box, and base class for dijit.form.FilteringSelect. // // description: // The drop down box's values are populated from an class called // a data provider, which returns a list of values based on the characters // that the user has typed into the input box. // If OPTION tags are used as the data provider via markup, // then the OPTION tag's child text node is used as the widget value // when selected. The OPTION tag's value attribute is ignored. // To set the default value when using OPTION tags, specify the selected // attribute on 1 of the child OPTION tags. // // Some of the options to the ComboBox are actually arguments to the data // provider. _setValueAttr: function(/*String*/ value, /*Boolean?*/ priorityChange, /*String?*/ displayedValue){ // summary: // Hook so set('value', value) works. // description: // Sets the value of the select. this._set("item", null); // value not looked up in store if(!value){ value = ''; } // null translates to blank dijit.form.ValidationTextBox.prototype._setValueAttr.call(this, value, priorityChange, displayedValue); } });dojo.declare("dijit.form._ComboBoxDataStore", null, { // summary: // Inefficient but small data store specialized for inlined `dijit.form.ComboBox` data // // description: // Provides a store for inlined data like: // // | <select> // | <option value="AL">Alabama</option> // | ... // // Actually. just implements the subset of dojo.data.Read/Notification // needed for ComboBox and FilteringSelect to work. // // Note that an item is just a pointer to the <option> DomNode. constructor: function( /*DomNode*/ root){ this.root = root; if(root.tagName != "SELECT" && root.firstChild){ root = dojo.query("select", root); if(root.length > 0){ // SELECT is a child of srcNodeRef root = root[0]; }else{ // no select, so create 1 to parent the option tags to define selectedIndex // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// this.root.innerHTML = "<SELECT>"+this.root.innerHTML+"</SELECT>";// FIXED: root = this.root.firstChild; } this.root = root; } dojo.query("> option", root).forEach(function(node){ // TODO: this was added in #3858 but unclear why/if it's needed; doesn't seem to be. // If it is needed then can we just hide the select itself instead? //node.style.display="none"; node.innerHTML = dojo.trim(node.innerHTML); }); }, getValue: function( /*item*/ item, /*attribute-name-string*/ attribute, /*value?*/ defaultValue){ return (attribute == "value") ? item.value : (item.innerText || item.textContent || ''); }, isItemLoaded: function(/*anything*/ something){ return true; }, getFeatures: function(){ return {"dojo.data.api.Read": true, "dojo.data.api.Identity": true}; }, _fetchItems: function( /*Object*/ args, /*Function*/ findCallback, /*Function*/ errorCallback){ // summary: // See dojo.data.util.simpleFetch.fetch() if(!args.query){ args.query = {}; } if(!args.query.name){ args.query.name = ""; } if(!args.queryOptions){ args.queryOptions = {}; } var matcher = dojo.data.util.filter.patternToRegExp(args.query.name, args.queryOptions.ignoreCase), items = dojo.query("> option", this.root).filter(function(option){ return (option.innerText || option.textContent || '').match(matcher); } ); if(args.sort){ items.sort(dojo.data.util.sorter.createSortFunction(args.sort, this)); } findCallback(items, args); }, close: function(/*dojo.data.api.Request || args || null*/ request){ return; }, getLabel: function(/*item*/ item){ return item.innerHTML; }, getIdentity: function(/*item*/ item){ return dojo.attr(item, "value"); }, fetchItemByIdentity: function(/*Object*/ args){ // summary: // Given the identity of an item, this method returns the item that has // that identity through the onItem callback. // Refer to dojo.data.api.Identity.fetchItemByIdentity() for more details. // // description: // Given arguments like: // // | {identity: "CA", onItem: function(item){...} // // Call `onItem()` with the DOM node `<option value="CA">California</option>` var item = dojo.query("> option[value='" + args.identity + "']", this.root)[0]; args.onItem(item); }, fetchSelectedItem: function(){ // summary: // Get the option marked as selected, like `<option selected>`. // Not part of dojo.data API. var root = this.root, si = root.selectedIndex; return typeof si == "number" ? dojo.query("> option:nth-child(" + (si != -1 ? si+1 : 1) + ")", root)[0] : null; // dojo.data.Item }});//Mix in the simple fetch implementation to this class.dojo.extend(dijit.form._ComboBoxDataStore,dojo.data.util.simpleFetch);return dijit.form.ComboBox;});
|
data/javascript/128.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details*/// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')// if(!dojo._hasResource["dojox.data.AndOrReadStore"]){dojo._hasResource["dojox.data.AndOrReadStore"]=true;dojo.provide("dojox.data.AndOrReadStore");dojo.require("dojo.data.util.filter");dojo.require("dojo.data.util.simpleFetch");dojo.require("dojo.date.stamp");dojo.declare("dojox.data.AndOrReadStore",null,{constructor:function(_1){this._arrayOfAllItems=[];this._arrayOfTopLevelItems=[];this._loadFinished=false;this._jsonFileUrl=_1.url;this._ccUrl=_1.url;this.url=_1.url;this._jsonData=_1.data;this.data=null;this._datatypeMap=_1.typeMap||{};if(!this._datatypeMap["Date"]){this._datatypeMap["Date"]={type:Date,deserialize:function(_2){return dojo.date.stamp.fromISOString(_2);}};}this._features={"dojo.data.api.Read":true,"dojo.data.api.Identity":true};this._itemsByIdentity=null;this._storeRefPropName="_S";this._itemNumPropName="_0";this._rootItemPropName="_RI";this._reverseRefMap="_RRM";this._loadInProgress=false;this._queuedFetches=[];if(_1.urlPreventCache!==undefined){this.urlPreventCache=_1.urlPreventCache?true:false;}if(_1.hierarchical!==undefined){this.hierarchical=_1.hierarchical?true:false;}if(_1.clearOnClose){this.clearOnClose=true;}},url:"",_ccUrl:"",data:null,typeMap:null,clearOnClose:false,urlPreventCache:false,hierarchical:true,_assertIsItem:function(_3){if(!this.isItem(_3)){throw new Error("dojox.data.AndOrReadStore: Invalid item argument.");}},_assertIsAttribute:function(_4){if(typeof _4!=="string"){throw new Error("dojox.data.AndOrReadStore: Invalid attribute argument.");}},getValue:function(_5,_6,_7){var _8=this.getValues(_5,_6);return (_8.length>0)?_8[0]:_7;},getValues:function(_9,_a){this._assertIsItem(_9);this._assertIsAttribute(_a);var _b=_9[_a]||[];return _b.slice(0,_b.length);},getAttributes:function(_c){this._assertIsItem(_c);var _d=[];for(var _e in _c){if((_e!==this._storeRefPropName)&&(_e!==this._itemNumPropName)&&(_e!==this._rootItemPropName)&&(_e!==this._reverseRefMap)){_d.push(_e);}}return _d;},hasAttribute:function(_f,_10){this._assertIsItem(_f);this._assertIsAttribute(_10);return (_10 in _f);},containsValue:function(_11,_12,_13){var _14=undefined;if(typeof _13==="string"){_14=dojo.data.util.filter.patternToRegExp(_13,false);}return this._containsValue(_11,_12,_13,_14);},_containsValue:function(_15,_16,_17,_18){return dojo.some(this.getValues(_15,_16),function(_19){if(_19!==null&&!dojo.isObject(_19)&&_18){if(_19.toString().match(_18)){return true;}}else{if(_17===_19){return true;}}});},isItem:function(_1a){if(_1a&&_1a[this._storeRefPropName]===this){if(this._arrayOfAllItems[_1a[this._itemNumPropName]]===_1a){return true;}}return false;},isItemLoaded:function(_1b){return this.isItem(_1b);},loadItem:function(_1c){this._assertIsItem(_1c.item);},getFeatures:function(){return this._features;},getLabel:function(_1d){if(this._labelAttr&&this.isItem(_1d)){return this.getValue(_1d,this._labelAttr);}return undefined;},getLabelAttributes:function(_1e){if(this._labelAttr){return [this._labelAttr];}return null;},_fetchItems:function(_1f,_20,_21){var _22=this;var _23=function(_24,_25){var _26=[];if(_24.query){var _27=dojo.fromJson(dojo.toJson(_24.query));if(typeof _27=="object"){var _28=0;var p;for(p in _27){_28++;}if(_28>1&&_27.complexQuery){var cq=_27.complexQuery;var _29=false;for(p in _27){if(p!=="complexQuery"){if(!_29){cq="( "+cq+" )";_29=true;}var v=_24.query[p];if(dojo.isString(v)){v="'"+v+"'";}cq+=" AND "+p+":"+v;delete _27[p];}}_27.complexQuery=cq;}}var _2a=_24.queryOptions?_24.queryOptions.ignoreCase:false;if(typeof _27!="string"){_27=dojo.toJson(_27);_27=_27.replace(/\\\\/g,"\\");}_27=_27.replace(/\\"/g,"\"");var _2b=dojo.trim(_27.replace(/{|}/g,""));var _2c,i;if(_2b.match(/"? *complexQuery *"?:/)){_2b=dojo.trim(_2b.replace(/"?\s*complexQuery\s*"?:/,""));var _2d=["'","\""];var _2e,_2f;var _30=false;for(i=0;i<_2d.length;i++){_2e=_2b.indexOf(_2d[i]);_2c=_2b.indexOf(_2d[i],1);_2f=_2b.indexOf(":",1);if(_2e===0&&_2c!=-1&&_2f<_2c){_30=true;break;}}if(_30){_2b=_2b.replace(/^\"|^\'|\"$|\'$/g,"");}}var _31=_2b;var _32=/^,|^NOT |^AND |^OR |^\(|^\)|^!|^&&|^\|\|/i;var _33="";var op="";var val="";var pos=-1;var err=false;var key="";var _34="";var tok="";_2c=-1;for(i=0;i<_25.length;++i){var _35=true;var _36=_25[i];if(_36===null){_35=false;}else{_2b=_31;_33="";while(_2b.length>0&&!err){op=_2b.match(_32);while(op&&!err){_2b=dojo.trim(_2b.replace(op[0],""));op=dojo.trim(op[0]).toUpperCase();op=op=="NOT"?"!":op=="AND"||op==","?"&&":op=="OR"?"||":op;op=" "+op+" ";_33+=op;op=_2b.match(_32);}if(_2b.length>0){pos=_2b.indexOf(":");if(pos==-1){err=true;break;}else{key=dojo.trim(_2b.substring(0,pos).replace(/\"|\'/g,""));_2b=dojo.trim(_2b.substring(pos+1));tok=_2b.match(/^\'|^\"/);if(tok){tok=tok[0];pos=_2b.indexOf(tok);_2c=_2b.indexOf(tok,pos+1);if(_2c==-1){err=true;break;}_34=_2b.substring(pos+1,_2c);if(_2c==_2b.length-1){_2b="";}else{_2b=dojo.trim(_2b.substring(_2c+1));}_33+=_22._containsValue(_36,key,_34,dojo.data.util.filter.patternToRegExp(_34,_2a));}else{tok=_2b.match(/\s|\)|,/);if(tok){var _37=new Array(tok.length);for(var j=0;j<tok.length;j++){_37[j]=_2b.indexOf(tok[j]);}pos=_37[0];if(_37.length>1){for(var j=1;j<_37.length;j++){pos=Math.min(pos,_37[j]);}}_34=dojo.trim(_2b.substring(0,pos));_2b=dojo.trim(_2b.substring(pos));}else{_34=dojo.trim(_2b);_2b="";}_33+=_22._containsValue(_36,key,_34,dojo.data.util.filter.patternToRegExp(_34,_2a));}}}}_35=eval(_33);}if(_35){_26.push(_36);}}if(err){_26=[];}_20(_26,_24);}else{for(var i=0;i<_25.length;++i){var _38=_25[i];if(_38!==null){_26.push(_38);}}_20(_26,_24);}};if(this._loadFinished){_23(_1f,this._getItemsArray(_1f.queryOptions));}else{if(this._jsonFileUrl!==this._ccUrl){dojo.deprecated("dojox.data.AndOrReadStore: ","To change the url, set the url property of the store,"+" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");this._ccUrl=this._jsonFileUrl;this.url=this._jsonFileUrl;}else{if(this.url!==this._ccUrl){this._jsonFileUrl=this.url;this._ccUrl=this.url;}}if(this.data!=null&&this._jsonData==null){this._jsonData=this.data;this.data=null;}if(this._jsonFileUrl){if(this._loadInProgress){this._queuedFetches.push({args:_1f,filter:_23});}else{this._loadInProgress=true;var _39={url:_22._jsonFileUrl,handleAs:"json-comment-optional",preventCache:this.urlPreventCache};var _3a=dojo.xhrGet(_39);_3a.addCallback(function(_3b){try{_22._getItemsFromLoadedData(_3b);_22._loadFinished=true;_22._loadInProgress=false;_23(_1f,_22._getItemsArray(_1f.queryOptions));_22._handleQueuedFetches();}catch(e){_22._loadFinished=true;_22._loadInProgress=false;_21(e,_1f);}});_3a.addErrback(function(_3c){_22._loadInProgress=false;_21(_3c,_1f);});var _3d=null;if(_1f.abort){_3d=_1f.abort;}_1f.abort=function(){var df=_3a;if(df&&df.fired===-1){df.cancel();df=null;}if(_3d){_3d.call(_1f);}};}}else{if(this._jsonData){try{this._loadFinished=true;this._getItemsFromLoadedData(this._jsonData);this._jsonData=null;_23(_1f,this._getItemsArray(_1f.queryOptions));}catch(e){_21(e,_1f);}}else{_21(new Error("dojox.data.AndOrReadStore: No JSON source data was provided as either URL or a nested Javascript object."),_1f);}}}},_handleQueuedFetches:function(){if(this._queuedFetches.length>0){for(var i=0;i<this._queuedFetches.length;i++){var _3e=this._queuedFetches[i];var _3f=_3e.args;var _40=_3e.filter;if(_40){_40(_3f,this._getItemsArray(_3f.queryOptions));}else{this.fetchItemByIdentity(_3f);}}this._queuedFetches=[];}},_getItemsArray:function(_41){if(_41&&_41.deep){return this._arrayOfAllItems;}return this._arrayOfTopLevelItems;},close:function(_42){if(this.clearOnClose&&this._loadFinished&&!this._loadInProgress){if(((this._jsonFileUrl==""||this._jsonFileUrl==null)&&(this.url==""||this.url==null))&&this.data==null){}this._arrayOfAllItems=[];this._arrayOfTopLevelItems=[];this._loadFinished=false;this._itemsByIdentity=null;this._loadInProgress=false;this._queuedFetches=[];}},_getItemsFromLoadedData:function(_43){var _44=this;function _45(_46){var _47=((_46!==null)&&(typeof _46==="object")&&(!dojo.isArray(_46))&&(!dojo.isFunction(_46))&&(_46.constructor==Object)&&(typeof _46._reference==="undefined")&&(typeof _46._type==="undefined")&&(typeof _46._value==="undefined")&&_44.hierarchical);return _47;};function _48(_49){_44._arrayOfAllItems.push(_49);for(var _4a in _49){var _4b=_49[_4a];if(_4b){if(dojo.isArray(_4b)){var _4c=_4b;for(var k=0;k<_4c.length;++k){var _4d=_4c[k];if(_45(_4d)){_48(_4d);}}}else{if(_45(_4b)){_48(_4b);}}}}};this._labelAttr=_43.label;var i;var _4e;this._arrayOfAllItems=[];this._arrayOfTopLevelItems=_43.items;for(i=0;i<this._arrayOfTopLevelItems.length;++i){_4e=this._arrayOfTopLevelItems[i];_48(_4e);_4e[this._rootItemPropName]=true;}var _4f={};var key;for(i=0;i<this._arrayOfAllItems.length;++i){_4e=this._arrayOfAllItems[i];for(key in _4e){if(key!==this._rootItemPropName){var _50=_4e[key];if(_50!==null){if(!dojo.isArray(_50)){_4e[key]=[_50];}}else{_4e[key]=[null];}}_4f[key]=key;}}while(_4f[this._storeRefPropName]){this._storeRefPropName+="_";}while(_4f[this._itemNumPropName]){this._itemNumPropName+="_";}while(_4f[this._reverseRefMap]){this._reverseRefMap+="_";}var _51;var _52=_43.identifier;if(_52){this._itemsByIdentity={};this._features["dojo.data.api.Identity"]=_52;for(i=0;i<this._arrayOfAllItems.length;++i){_4e=this._arrayOfAllItems[i];_51=_4e[_52];var _53=_51[0];if(!this._itemsByIdentity[_53]){this._itemsByIdentity[_53]=_4e;}else{if(this._jsonFileUrl){throw new Error("dojox.data.AndOrReadStore: The json data as specified by: ["+this._jsonFileUrl+"] is malformed. Items within the list have identifier: ["+_52+"]. Value collided: ["+_53+"]");}else{if(this._jsonData){throw new Error("dojox.data.AndOrReadStore: The json data provided by the creation arguments is malformed. Items within the list have identifier: ["+_52+"]. Value collided: ["+_53+"]");}}}}}else{this._features["dojo.data.api.Identity"]=Number;}for(i=0;i<this._arrayOfAllItems.length;++i){_4e=this._arrayOfAllItems[i];_4e[this._storeRefPropName]=this;_4e[this._itemNumPropName]=i;}for(i=0;i<this._arrayOfAllItems.length;++i){_4e=this._arrayOfAllItems[i];for(key in _4e){_51=_4e[key];for(var j=0;j<_51.length;++j){_50=_51[j];if(_50!==null&&typeof _50=="object"){if(("_type" in _50)&&("_value" in _50)){var _54=_50._type;var _55=this._datatypeMap[_54];if(!_55){throw new Error("dojox.data.AndOrReadStore: in the typeMap constructor arg, no object class was specified for the datatype '"+_54+"'");}else{if(dojo.isFunction(_55)){_51[j]=new _55(_50._value);}else{if(dojo.isFunction(_55.deserialize)){_51[j]=_55.deserialize(_50._value);}else{throw new Error("dojox.data.AndOrReadStore: Value provided in typeMap was neither a constructor, nor a an object with a deserialize function");}}}}if(_50._reference){var _56=_50._reference;if(!dojo.isObject(_56)){_51[j]=this._getItemByIdentity(_56);}else{for(var k=0;k<this._arrayOfAllItems.length;++k){var _57=this._arrayOfAllItems[k];var _58=true;for(var _59 in _56){if(_57[_59]!=_56[_59]){_58=false;}}if(_58){_51[j]=_57;}}}if(this.referenceIntegrity){var _5a=_51[j];if(this.isItem(_5a)){this._addReferenceToMap(_5a,_4e,key);}}}else{if(this.isItem(_50)){if(this.referenceIntegrity){this._addReferenceToMap(_50,_4e,key);}}}}}}}},_addReferenceToMap:function(_5b,_5c,_5d){},getIdentity:function(_5e){var _5f=this._features["dojo.data.api.Identity"];if(_5f===Number){return _5e[this._itemNumPropName];}else{var _60=_5e[_5f];if(_60){return _60[0];}}return null;},fetchItemByIdentity:function(_61){if(!this._loadFinished){var _62=this;if(this._jsonFileUrl!==this._ccUrl){dojo.deprecated("dojox.data.AndOrReadStore: ","To change the url, set the url property of the store,"+" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");this._ccUrl=this._jsonFileUrl;this.url=this._jsonFileUrl;}else{if(this.url!==this._ccUrl){this._jsonFileUrl=this.url;this._ccUrl=this.url;}}if(this.data!=null&&this._jsonData==null){this._jsonData=this.data;this.data=null;}if(this._jsonFileUrl){if(this._loadInProgress){this._queuedFetches.push({args:_61});}else{this._loadInProgress=true;var _63={url:_62._jsonFileUrl,handleAs:"json-comment-optional",preventCache:this.urlPreventCache};var _64=dojo.xhrGet(_63);_64.addCallback(function(_65){var _66=_61.scope?_61.scope:dojo.global;try{_62._getItemsFromLoadedData(_65);_62._loadFinished=true;_62._loadInProgress=false;var _67=_62._getItemByIdentity(_61.identity);if(_61.onItem){_61.onItem.call(_66,_67);}_62._handleQueuedFetches();}catch(error){_62._loadInProgress=false;if(_61.onError){_61.onError.call(_66,error);}}});_64.addErrback(function(_68){_62._loadInProgress=false;if(_61.onError){var _69=_61.scope?_61.scope:dojo.global;_61.onError.call(_69,_68);}});}}else{if(this._jsonData){_62._getItemsFromLoadedData(_62._jsonData);_62._jsonData=null;_62._loadFinished=true;var _6a=_62._getItemByIdentity(_61.identity);if(_61.onItem){var _6b=_61.scope?_61.scope:dojo.global;_61.onItem.call(_6b,_6a);}}}}else{var _6a=this._getItemByIdentity(_61.identity);if(_61.onItem){var _6b=_61.scope?_61.scope:dojo.global;_61.onItem.call(_6b,_6a);}}},_getItemByIdentity:function(_6c){var _6d=null;if(this._itemsByIdentity){_6d=this._itemsByIdentity[_6c];}else{_6d=this._arrayOfAllItems[_6c];}if(_6d===undefined){_6d=null;}return _6d;},getIdentityAttributes:function(_6e){var _6f=this._features["dojo.data.api.Identity"];if(_6f===Number){return null;}else{return [_6f];}},_forceLoad:function(){var _70=this;if(this._jsonFileUrl!==this._ccUrl){dojo.deprecated("dojox.data.AndOrReadStore: ","To change the url, set the url property of the store,"+" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");this._ccUrl=this._jsonFileUrl;this.url=this._jsonFileUrl;}else{if(this.url!==this._ccUrl){this._jsonFileUrl=this.url;this._ccUrl=this.url;}}if(this.data!=null&&this._jsonData==null){this._jsonData=this.data;this.data=null;}if(this._jsonFileUrl){var _71={url:_70._jsonFileUrl,handleAs:"json-comment-optional",preventCache:this.urlPreventCache,sync:true};var _72=dojo.xhrGet(_71);_72.addCallback(function(_73){try{if(_70._loadInProgress!==true&&!_70._loadFinished){_70._getItemsFromLoadedData(_73);_70._loadFinished=true;}else{if(_70._loadInProgress){throw new Error("dojox.data.AndOrReadStore: Unable to perform a synchronous load, an async load is in progress.");}}}catch(e){throw e;}});_72.addErrback(function(_74){throw _74;});}else{if(this._jsonData){_70._getItemsFromLoadedData(_70._jsonData);_70._jsonData=null;_70._loadFinished=true;}}}});dojo.extend(dojox.data.AndOrReadStore,dojo.data.util.simpleFetch);}// FIXED:
|
data/javascript/129.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
define("dojox/data/AndOrReadStore", ["dojo", "dojox", "dojo/data/util/filter", "dojo/data/util/simpleFetch", "dojo/date/stamp"], function(dojo, dojox) {dojo.declare("dojox.data.AndOrReadStore", null,{ // summary: // AndOrReadStore uses ItemFileReadStore as a base, modifying only the query (_fetchItems) section. // Supports queries of the form: query:"id:1* OR dept:'Sales Department' || (id:2* && NOT dept:S*)" // Includes legacy/widget support via: // query:{complexQuery:"id:1* OR dept:'Sales Department' || (id:2* && NOT dept:S*)"} // The ItemFileReadStore implements the dojo.data.api.Read API and reads // data from JSON files that have contents in this format -- // { items: [ // { name:'Kermit', color:'green', age:12, friends:['Gonzo', {_reference:{name:'Fozzie Bear'}}]}, // { name:'Fozzie Bear', wears:['hat', 'tie']}, // { name:'Miss Piggy', pets:'Foo-Foo'} // ]} // Note that it can also contain an 'identifer' property that specified which attribute on the items // in the array of items that acts as the unique identifier for that item. // constructor: function(/* Object */ keywordParameters){ // summary: constructor // keywordParameters: {url: String} // keywordParameters: {data: jsonObject} // keywordParameters: {typeMap: object) // The structure of the typeMap object is as follows: // { // type0: function || object, // type1: function || object, // ... // typeN: function || object // } // Where if it is a function, it is assumed to be an object constructor that takes the // value of _value as the initialization parameters. If it is an object, then it is assumed // to be an object of general form: // { // type: function, //constructor. // deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately. // } this._arrayOfAllItems = []; this._arrayOfTopLevelItems = []; this._loadFinished = false; this._jsonFileUrl = keywordParameters.url; this._ccUrl = keywordParameters.url; this.url = keywordParameters.url; this._jsonData = keywordParameters.data; this.data = null; this._datatypeMap = keywordParameters.typeMap || {}; if(!this._datatypeMap['Date']){ //If no default mapping for dates, then set this as default. //We use the dojo.date.stamp here because the ISO format is the 'dojo way' //of generically representing dates. this._datatypeMap['Date'] = { type: Date, deserialize: function(value){ return dojo.date.stamp.fromISOString(value); } }; } this._features = {'dojo.data.api.Read':true, 'dojo.data.api.Identity':true}; this._itemsByIdentity = null; this._storeRefPropName = "_S"; // Default name for the store reference to attach to every item. this._itemNumPropName = "_0"; // Default Item Id for isItem to attach to every item. this._rootItemPropName = "_RI"; // Default Item Id for isItem to attach to every item. this._reverseRefMap = "_RRM"; // Default attribute for constructing a reverse reference map for use with reference integrity this._loadInProgress = false; //Got to track the initial load to prevent duelling loads of the dataset. this._queuedFetches = []; if(keywordParameters.urlPreventCache !== undefined){ this.urlPreventCache = keywordParameters.urlPreventCache?true:false; } if(keywordParameters.hierarchical !== undefined){ this.hierarchical = keywordParameters.hierarchical?true:false; } if(keywordParameters.clearOnClose){ this.clearOnClose = true; } }, url: "", // use "" rather than undefined for the benefit of the parser (#3539) //Internal var, crossCheckUrl. Used so that setting either url or _jsonFileUrl, can still trigger a reload //when clearOnClose and close is used. _ccUrl: "", data: null, //Make this parser settable. typeMap: null, //Make this parser settable. //Parameter to allow users to specify if a close call should force a reload or not. //By default, it retains the old behavior of not clearing if close is called. But //if set true, the store will be reset to default state. Note that by doing this, //all item handles will become invalid and a new fetch must be issued. clearOnClose: false, //Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url. //Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option. //Added for tracker: #6072 urlPreventCache: false, //Parameter to indicate to process data from the url as hierarchical //(data items can contain other data items in js form). Default is true //for backwards compatibility. False means only root items are processed //as items, all child objects outside of type-mapped objects and those in //specific reference format, are left straight JS data objects. hierarchical: true, _assertIsItem: function(/* item */ item){ // summary: // This function tests whether the item passed in is indeed an item in the store. // item: // The item to test for being contained by the store. if(!this.isItem(item)){ throw new Error("dojox.data.AndOrReadStore: Invalid item argument."); } }, _assertIsAttribute: function(/* attribute-name-string */ attribute){ // summary: // This function tests whether the item passed in is indeed a valid 'attribute' like type for the store. // attribute: // The attribute to test for being contained by the store. if(typeof attribute !== "string"){ throw new Error("dojox.data.AndOrReadStore: Invalid attribute argument."); } }, getValue: function( /* item */ item, /* attribute-name-string */ attribute, /* value? */ defaultValue){ // summary: // See dojo.data.api.Read.getValue() var values = this.getValues(item, attribute); return (values.length > 0)?values[0]:defaultValue; // mixed }, getValues: function(/* item */ item, /* attribute-name-string */ attribute){ // summary: // See dojo.data.api.Read.getValues() this._assertIsItem(item); this._assertIsAttribute(attribute); var arr = item[attribute] || []; // Clone it before returning. refs: #10474 return arr.slice(0, arr.length); // Array }, getAttributes: function(/* item */ item){ // summary: // See dojo.data.api.Read.getAttributes() this._assertIsItem(item); var attributes = []; for(var key in item){ // Save off only the real item attributes, not the special id marks for O(1) isItem. if((key !== this._storeRefPropName) && (key !== this._itemNumPropName) && (key !== this._rootItemPropName) && (key !== this._reverseRefMap)){ attributes.push(key); } } return attributes; // Array }, hasAttribute: function( /* item */ item, /* attribute-name-string */ attribute){ // summary: // See dojo.data.api.Read.hasAttribute() this._assertIsItem(item); this._assertIsAttribute(attribute); return (attribute in item); }, containsValue: function(/* item */ item, /* attribute-name-string */ attribute, /* anything */ value){ // summary: // See dojo.data.api.Read.containsValue() var regexp = undefined; if(typeof value === "string"){ regexp = dojo.data.util.filter.patternToRegExp(value, false); } return this._containsValue(item, attribute, value, regexp); //boolean. }, _containsValue: function( /* item */ item, /* attribute-name-string */ attribute, /* anything */ value, /* RegExp?*/ regexp){ // summary: // Internal function for looking at the values contained by the item. // description: // Internal function for looking at the values contained by the item. This // function allows for denoting if the comparison should be case sensitive for // strings or not (for handling filtering cases where string case should not matter) // // item: // The data item to examine for attribute values. // attribute: // The attribute to inspect. // value: // The value to match. // regexp: // Optional regular expression generated off value if value was of string type to handle wildcarding. // If present and attribute values are string, then it can be used for comparison instead of 'value' return dojo.some(this.getValues(item, attribute), function(possibleValue){ if(possibleValue !== null && !dojo.isObject(possibleValue) && regexp){ if(possibleValue.toString().match(regexp)){ return true; // Boolean } }else if(value === possibleValue){ return true; // Boolean } }); }, isItem: function(/* anything */ something){ // summary: // See dojo.data.api.Read.isItem() if(something && something[this._storeRefPropName] === this){ if(this._arrayOfAllItems[something[this._itemNumPropName]] === something){ return true; } } return false; // Boolean }, isItemLoaded: function(/* anything */ something){ // summary: // See dojo.data.api.Read.isItemLoaded() return this.isItem(something); //boolean }, loadItem: function(/* object */ keywordArgs){ // summary: // See dojo.data.api.Read.loadItem() this._assertIsItem(keywordArgs.item); }, getFeatures: function(){ // summary: // See dojo.data.api.Read.getFeatures() return this._features; //Object }, getLabel: function(/* item */ item){ // summary: // See dojo.data.api.Read.getLabel() if(this._labelAttr && this.isItem(item)){ return this.getValue(item,this._labelAttr); //String } return undefined; //undefined }, getLabelAttributes: function(/* item */ item){ // summary: // See dojo.data.api.Read.getLabelAttributes() if(this._labelAttr){ return [this._labelAttr]; //array } return null; //null }, _fetchItems: function( /* Object */ keywordArgs, /* Function */ findCallback, /* Function */ errorCallback){ // summary: // See dojo.data.util.simpleFetch.fetch() // filter modified to permit complex queries where // logical operators are case insensitive: // , NOT AND OR ( ) ! && || // Note: "," included for quoted/string legacy queries. var self = this; var filter = function(requestArgs, arrayOfItems){ var items = []; if(requestArgs.query){ //Complete copy, we may have to mess with it. //Safer than clone, which does a shallow copy, I believe. var query = dojo.fromJson(dojo.toJson(requestArgs.query)); //Okay, object form query, we have to check to see if someone mixed query methods (such as using FilteringSelect //with a complexQuery). In that case, the params need to be anded to the complex query statement. //See defect #7980 if(typeof query == "object" ){ var count = 0; var p; for(p in query){ count++; } if(count > 1 && query.complexQuery){ var cq = query.complexQuery; var wrapped = false; for(p in query){ if(p !== "complexQuery"){ //We should wrap this in () as it should and with the entire complex query //Not just part of it. if(!wrapped){ cq = "( " + cq + " )"; wrapped = true; } //Make sure strings are quoted when going into complexQuery merge. var v = requestArgs.query[p]; if(dojo.isString(v)){ v = "'" + v + "'"; } cq += " AND " + p + ":" + v; delete query[p]; } } query.complexQuery = cq; } } var ignoreCase = requestArgs.queryOptions ? requestArgs.queryOptions.ignoreCase : false; //for complex queries only: pattern = query[:|=]"NOT id:23* AND (type:'test*' OR dept:'bob') && !filed:true" //logical operators are case insensitive: , NOT AND OR ( ) ! && || // "," included for quoted/string legacy queries. if(typeof query != "string"){ query = dojo.toJson(query); query = query.replace(/\\\\/g,"\\"); //counter toJson expansion of backslashes, e.g., foo\\*bar test. } query = query.replace(/\\"/g,"\""); //ditto, for embedded \" in lieu of " availability. var complexQuery = dojo.trim(query.replace(/{|}/g,"")); //we can handle these, too. var pos2, i; if(complexQuery.match(/"? *complexQuery *"?:/)){ //case where widget required a json object, so use complexQuery:'the real query' complexQuery = dojo.trim(complexQuery.replace(/"?\s*complexQuery\s*"?:/,"")); var quotes = ["'",'"']; var pos1,colon; var flag = false; for(i = 0; i<quotes.length; i++){ pos1 = complexQuery.indexOf(quotes[i]); pos2 = complexQuery.indexOf(quotes[i],1); colon = complexQuery.indexOf(":",1); if(pos1 === 0 && pos2 != -1 && colon < pos2){ flag = true; break; } //first two sets of quotes don't occur before the first colon. } if(flag){ //dojo.toJson, and maybe user, adds surrounding quotes, which we need to remove. complexQuery = complexQuery.replace(/^\"|^\'|\"$|\'$/g,""); } } //end query="{complexQuery:'id:1* || dept:Sales'}" parsing (for when widget required json object query). var complexQuerySave = complexQuery; //valid logical operators. var begRegExp = /^,|^NOT |^AND |^OR |^\(|^\)|^!|^&&|^\|\|/i; //trailing space on some tokens on purpose. var sQuery = ""; //will be eval'ed for each i-th candidateItem, based on query components. var op = ""; var val = ""; var pos = -1; var err = false; var key = ""; var value = ""; var tok = ""; pos2 = -1; for(i = 0; i < arrayOfItems.length; ++i){ var match = true; var candidateItem = arrayOfItems[i]; if(candidateItem === null){ match = false; }else{ //process entire string for this i-th candidateItem. complexQuery = complexQuerySave; //restore query for next candidateItem. sQuery = ""; //work left to right, finding either key:value pair or logical operator at the beginning of the complexQuery string. //when found, concatenate to sQuery and remove from complexQuery and loop back. while(complexQuery.length > 0 && !err){ op = complexQuery.match(begRegExp); //get/process/append one or two leading logical operators. while(op && !err){ //look for leading logical operators. complexQuery = dojo.trim(complexQuery.replace(op[0],"")); op = dojo.trim(op[0]).toUpperCase(); //convert some logical operators to their javascript equivalents for later eval. op = op == "NOT" ? "!" : op == "AND" || op == "," ? "&&" : op == "OR" ? "||" : op; op = " " + op + " "; sQuery += op; op = complexQuery.match(begRegExp); }//end op && !err //now get/process/append one key:value pair. if(complexQuery.length > 0){ pos = complexQuery.indexOf(":"); if(pos == -1){ err = true; break; }else{ key = dojo.trim(complexQuery.substring(0,pos).replace(/\"|\'/g,"")); complexQuery = dojo.trim(complexQuery.substring(pos + 1)); tok = complexQuery.match(/^\'|^\"/); //quoted? if(tok){ tok = tok[0]; pos = complexQuery.indexOf(tok); pos2 = complexQuery.indexOf(tok,pos + 1); if(pos2 == -1){ err = true; break; } value = complexQuery.substring(pos + 1,pos2); if(pos2 == complexQuery.length - 1){ //quote is last character complexQuery = ""; }else{ complexQuery = dojo.trim(complexQuery.substring(pos2 + 1)); } sQuery += self._containsValue(candidateItem, key, value, dojo.data.util.filter.patternToRegExp(value, ignoreCase)); } else{ //not quoted, so a space, comma, or closing parens (or the end) will be the break. tok = complexQuery.match(/\s|\)|,/); if(tok){ var pos3 = new Array(tok.length); for(var j = 0;j<tok.length;j++){ pos3[j] = complexQuery.indexOf(tok[j]); } pos = pos3[0]; if(pos3.length > 1){ for(var j=1;j<pos3.length;j++){ pos = Math.min(pos,pos3[j]); } } value = dojo.trim(complexQuery.substring(0,pos)); complexQuery = dojo.trim(complexQuery.substring(pos)); }else{ //not a space, so must be at the end of the complexQuery. value = dojo.trim(complexQuery); complexQuery = ""; } //end inner if(tok) else sQuery += self._containsValue(candidateItem, key, value, dojo.data.util.filter.patternToRegExp(value, ignoreCase)); } //end outer if(tok) else } //end found ":" } //end if(complexQuery.length > 0) } //end while complexQuery.length > 0 && !err, so finished the i-th item. // BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')// match = eval(sQuery);// FIXED: } //end else is non-null candidateItem. if(match){ items.push(candidateItem); } } //end for/next of all items. if(err){ //soft fail. items = []; console.log("The store's _fetchItems failed, probably due to a syntax error in query."); } findCallback(items, requestArgs); }else{ // No query... // We want a copy to pass back in case the parent wishes to sort the array. // We shouldn't allow resort of the internal list, so that multiple callers // can get lists and sort without affecting each other. We also need to // filter out any null values that have been left as a result of deleteItem() // calls in ItemFileWriteStore. for(var i = 0; i < arrayOfItems.length; ++i){ var item = arrayOfItems[i]; if(item !== null){ items.push(item); } } findCallback(items, requestArgs); } //end if there is a query. }; //end filter function if(this._loadFinished){ filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions)); }else{ if(this._jsonFileUrl !== this._ccUrl){ dojo.deprecated("dojox.data.AndOrReadStore: ", "To change the url, set the url property of the store," + " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0"); this._ccUrl = this._jsonFileUrl; this.url = this._jsonFileUrl; }else if(this.url !== this._ccUrl){ this._jsonFileUrl = this.url; this._ccUrl = this.url; } //See if there was any forced reset of data. if(this.data != null && this._jsonData == null){ this._jsonData = this.data; this.data = null; } if(this._jsonFileUrl){ //If fetches come in before the loading has finished, but while //a load is in progress, we have to defer the fetching to be //invoked in the callback. if(this._loadInProgress){ this._queuedFetches.push({args: keywordArgs, filter: filter}); }else{ this._loadInProgress = true; var getArgs = { url: self._jsonFileUrl, handleAs: "json-comment-optional", preventCache: this.urlPreventCache }; var getHandler = dojo.xhrGet(getArgs); getHandler.addCallback(function(data){ try{ self._getItemsFromLoadedData(data); self._loadFinished = true; self._loadInProgress = false; filter(keywordArgs, self._getItemsArray(keywordArgs.queryOptions)); self._handleQueuedFetches(); }catch(e){ self._loadFinished = true; self._loadInProgress = false; errorCallback(e, keywordArgs); } }); getHandler.addErrback(function(error){ self._loadInProgress = false; errorCallback(error, keywordArgs); }); //Wire up the cancel to abort of the request //This call cancel on the deferred if it hasn't been called //yet and then will chain to the simple abort of the //simpleFetch keywordArgs var oldAbort = null; if(keywordArgs.abort){ oldAbort = keywordArgs.abort; } keywordArgs.abort = function(){ var df = getHandler; if(df && df.fired === -1){ df.cancel(); df = null; } if(oldAbort){ oldAbort.call(keywordArgs); } }; } }else if(this._jsonData){ try{ this._loadFinished = true; this._getItemsFromLoadedData(this._jsonData); this._jsonData = null; filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions)); }catch(e){ errorCallback(e, keywordArgs); } }else{ errorCallback(new Error("dojox.data.AndOrReadStore: No JSON source data was provided as either URL or a nested Javascript object."), keywordArgs); } } //end deferred fetching. }, //end _fetchItems _handleQueuedFetches: function(){ // summary: // Internal function to execute delayed request in the store. //Execute any deferred fetches now. if(this._queuedFetches.length > 0){ for(var i = 0; i < this._queuedFetches.length; i++){ var fData = this._queuedFetches[i]; var delayedQuery = fData.args; var delayedFilter = fData.filter; if(delayedFilter){ delayedFilter(delayedQuery, this._getItemsArray(delayedQuery.queryOptions)); }else{ this.fetchItemByIdentity(delayedQuery); } } this._queuedFetches = []; } }, _getItemsArray: function(/*object?*/queryOptions){ // summary: // Internal function to determine which list of items to search over. // queryOptions: The query options parameter, if any. if(queryOptions && queryOptions.deep){ return this._arrayOfAllItems; } return this._arrayOfTopLevelItems; }, close: function(/*dojo.data.api.Request || keywordArgs || null */ request){ // summary: // See dojo.data.api.Read.close() if(this.clearOnClose && this._loadFinished && !this._loadInProgress){ //Reset all internalsback to default state. This will force a reload //on next fetch. This also checks that the data or url param was set //so that the store knows it can get data. Without one of those being set, //the next fetch will trigger an error. if(((this._jsonFileUrl == "" || this._jsonFileUrl == null) && (this.url == "" || this.url == null) ) && this.data == null){ console.debug("dojox.data.AndOrReadStore: WARNING! Data reload " + " information has not been provided." + " Please set 'url' or 'data' to the appropriate value before" + " the next fetch"); } this._arrayOfAllItems = []; this._arrayOfTopLevelItems = []; this._loadFinished = false; this._itemsByIdentity = null; this._loadInProgress = false; this._queuedFetches = []; } }, _getItemsFromLoadedData: function(/* Object */ dataObject){ // summary: // Function to parse the loaded data into item format and build the internal items array. // description: // Function to parse the loaded data into item format and build the internal items array. // // dataObject: // The JS data object containing the raw data to convery into item format. // // returns: array // Array of items in store item format. // First, we define a couple little utility functions... var self = this; function valueIsAnItem(/* anything */ aValue){ // summary: // Given any sort of value that could be in the raw json data, // return true if we should interpret the value as being an // item itself, rather than a literal value or a reference. // example: // | false == valueIsAnItem("Kermit"); // | false == valueIsAnItem(42); // | false == valueIsAnItem(new Date()); // | false == valueIsAnItem({_type:'Date', _value:'May 14, 1802'}); // | false == valueIsAnItem({_reference:'Kermit'}); // | true == valueIsAnItem({name:'Kermit', color:'green'}); // | true == valueIsAnItem({iggy:'pop'}); // | true == valueIsAnItem({foo:42}); var isItem = ( (aValue !== null) && (typeof aValue === "object") && (!dojo.isArray(aValue)) && (!dojo.isFunction(aValue)) && (aValue.constructor == Object) && (typeof aValue._reference === "undefined") && (typeof aValue._type === "undefined") && (typeof aValue._value === "undefined") && self.hierarchical ); return isItem; } function addItemAndSubItemsToArrayOfAllItems(/* Item */ anItem){ self._arrayOfAllItems.push(anItem); for(var attribute in anItem){ var valueForAttribute = anItem[attribute]; if(valueForAttribute){ if(dojo.isArray(valueForAttribute)){ var valueArray = valueForAttribute; for(var k = 0; k < valueArray.length; ++k){ var singleValue = valueArray[k]; if(valueIsAnItem(singleValue)){ addItemAndSubItemsToArrayOfAllItems(singleValue); } } }else{ if(valueIsAnItem(valueForAttribute)){ addItemAndSubItemsToArrayOfAllItems(valueForAttribute); } } } } } this._labelAttr = dataObject.label; // We need to do some transformations to convert the data structure // that we read from the file into a format that will be convenient // to work with in memory. // Step 1: Walk through the object hierarchy and build a list of all items var i; var item; this._arrayOfAllItems = []; this._arrayOfTopLevelItems = dataObject.items; for(i = 0; i < this._arrayOfTopLevelItems.length; ++i){ item = this._arrayOfTopLevelItems[i]; addItemAndSubItemsToArrayOfAllItems(item); item[this._rootItemPropName]=true; } // Step 2: Walk through all the attribute values of all the items, // and replace single values with arrays. For example, we change this: // { name:'Miss Piggy', pets:'Foo-Foo'} // into this: // { name:['Miss Piggy'], pets:['Foo-Foo']} // // We also store the attribute names so we can validate our store // reference and item id special properties for the O(1) isItem var allAttributeNames = {}; var key; for(i = 0; i < this._arrayOfAllItems.length; ++i){ item = this._arrayOfAllItems[i]; for(key in item){ if(key !== this._rootItemPropName){ var value = item[key]; if(value !== null){ if(!dojo.isArray(value)){ item[key] = [value]; } }else{ item[key] = [null]; } } allAttributeNames[key]=key; } } // Step 3: Build unique property names to use for the _storeRefPropName and _itemNumPropName // This should go really fast, it will generally never even run the loop. while(allAttributeNames[this._storeRefPropName]){ this._storeRefPropName += "_"; } while(allAttributeNames[this._itemNumPropName]){ this._itemNumPropName += "_"; } while(allAttributeNames[this._reverseRefMap]){ this._reverseRefMap += "_"; } // Step 4: Some data files specify an optional 'identifier', which is // the name of an attribute that holds the identity of each item. // If this data file specified an identifier attribute, then build a // hash table of items keyed by the identity of the items. var arrayOfValues; var identifier = dataObject.identifier; if(identifier){ this._itemsByIdentity = {}; this._features['dojo.data.api.Identity'] = identifier; for(i = 0; i < this._arrayOfAllItems.length; ++i){ item = this._arrayOfAllItems[i]; arrayOfValues = item[identifier]; var identity = arrayOfValues[0]; if(!this._itemsByIdentity[identity]){ this._itemsByIdentity[identity] = item; }else{ if(this._jsonFileUrl){ throw new Error("dojox.data.AndOrReadStore: The json data as specified by: [" + this._jsonFileUrl + "] is malformed. Items within the list have identifier: [" + identifier + "]. Value collided: [" + identity + "]"); }else if(this._jsonData){ throw new Error("dojox.data.AndOrReadStore: The json data provided by the creation arguments is malformed. Items within the list have identifier: [" + identifier + "]. Value collided: [" + identity + "]"); } } } }else{ this._features['dojo.data.api.Identity'] = Number; } // Step 5: Walk through all the items, and set each item's properties // for _storeRefPropName and _itemNumPropName, so that store.isItem() will return true. for(i = 0; i < this._arrayOfAllItems.length; ++i){ item = this._arrayOfAllItems[i]; item[this._storeRefPropName] = this; item[this._itemNumPropName] = i; } // Step 6: We walk through all the attribute values of all the items, // looking for type/value literals and item-references. // // We replace item-references with pointers to items. For example, we change: // { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] } // into this: // { name:['Kermit'], friends:[miss_piggy] } // (where miss_piggy is the object representing the 'Miss Piggy' item). // // We replace type/value pairs with typed-literals. For example, we change: // { name:['Nelson Mandela'], born:[{_type:'Date', _value:'July 18, 1918'}] } // into this: // { name:['Kermit'], born:(new Date('July 18, 1918')) } // // We also generate the associate map for all items for the O(1) isItem function. for(i = 0; i < this._arrayOfAllItems.length; ++i){ item = this._arrayOfAllItems[i]; // example: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] } for(key in item){ arrayOfValues = item[key]; // example: [{_reference:{name:'Miss Piggy'}}] for(var j = 0; j < arrayOfValues.length; ++j){ value = arrayOfValues[j]; // example: {_reference:{name:'Miss Piggy'}} if(value !== null && typeof value == "object"){ if(("_type" in value) && ("_value" in value)){ var type = value._type; // examples: 'Date', 'Color', or 'ComplexNumber' var mappingObj = this._datatypeMap[type]; // examples: Date, dojo.Color, foo.math.ComplexNumber, {type: dojo.Color, deserialize(value){ return new dojo.Color(value)}} if(!mappingObj){ throw new Error("dojox.data.AndOrReadStore: in the typeMap constructor arg, no object class was specified for the datatype '" + type + "'"); }else if(dojo.isFunction(mappingObj)){ arrayOfValues[j] = new mappingObj(value._value); }else if(dojo.isFunction(mappingObj.deserialize)){ arrayOfValues[j] = mappingObj.deserialize(value._value); }else{ throw new Error("dojox.data.AndOrReadStore: Value provided in typeMap was neither a constructor, nor a an object with a deserialize function"); } } if(value._reference){ var referenceDescription = value._reference; // example: {name:'Miss Piggy'} if(!dojo.isObject(referenceDescription)){ // example: 'Miss Piggy' // from an item like: { name:['Kermit'], friends:[{_reference:'Miss Piggy'}]} arrayOfValues[j] = this._getItemByIdentity(referenceDescription); }else{ // example: {name:'Miss Piggy'} // from an item like: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] } for(var k = 0; k < this._arrayOfAllItems.length; ++k){ var candidateItem = this._arrayOfAllItems[k]; var found = true; for(var refKey in referenceDescription){ if(candidateItem[refKey] != referenceDescription[refKey]){ found = false; } } if(found){ arrayOfValues[j] = candidateItem; } } } if(this.referenceIntegrity){ var refItem = arrayOfValues[j]; if(this.isItem(refItem)){ this._addReferenceToMap(refItem, item, key); } } }else if(this.isItem(value)){ //It's a child item (not one referenced through _reference). //We need to treat this as a referenced item, so it can be cleaned up //in a write store easily. if(this.referenceIntegrity){ this._addReferenceToMap(value, item, key); } } } } } } }, _addReferenceToMap: function(/*item*/ refItem, /*item*/ parentItem, /*string*/ attribute){ // summary: // Method to add an reference map entry for an item and attribute. // description: // Method to add an reference map entry for an item and attribute. // // refItem: // The item that is referenced. // parentItem: // The item that holds the new reference to refItem. // attribute: // The attribute on parentItem that contains the new reference. //Stub function, does nothing. Real processing is in ItemFileWriteStore. }, getIdentity: function(/* item */ item){ // summary: // See dojo.data.api.Identity.getIdentity() var identifier = this._features['dojo.data.api.Identity']; if(identifier === Number){ return item[this._itemNumPropName]; // Number }else{ var arrayOfValues = item[identifier]; if(arrayOfValues){ return arrayOfValues[0]; // Object || String } } return null; // null }, fetchItemByIdentity: function(/* Object */ keywordArgs){ // summary: // See dojo.data.api.Identity.fetchItemByIdentity() // Hasn't loaded yet, we have to trigger the load. if(!this._loadFinished){ var self = this; if(this._jsonFileUrl !== this._ccUrl){ dojo.deprecated("dojox.data.AndOrReadStore: ", "To change the url, set the url property of the store," + " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0"); this._ccUrl = this._jsonFileUrl; this.url = this._jsonFileUrl; }else if(this.url !== this._ccUrl){ this._jsonFileUrl = this.url; this._ccUrl = this.url; } //See if there was any forced reset of data. if(this.data != null && this._jsonData == null){ this._jsonData = this.data; this.data = null; } if(this._jsonFileUrl){ if(this._loadInProgress){ this._queuedFetches.push({args: keywordArgs}); }else{ this._loadInProgress = true; var getArgs = { url: self._jsonFileUrl, handleAs: "json-comment-optional", preventCache: this.urlPreventCache }; var getHandler = dojo.xhrGet(getArgs); getHandler.addCallback(function(data){ var scope = keywordArgs.scope?keywordArgs.scope:dojo.global; try{ self._getItemsFromLoadedData(data); self._loadFinished = true; self._loadInProgress = false; var item = self._getItemByIdentity(keywordArgs.identity); if(keywordArgs.onItem){ keywordArgs.onItem.call(scope, item); } self._handleQueuedFetches(); }catch(error){ self._loadInProgress = false; if(keywordArgs.onError){ keywordArgs.onError.call(scope, error); } } }); getHandler.addErrback(function(error){ self._loadInProgress = false; if(keywordArgs.onError){ var scope = keywordArgs.scope?keywordArgs.scope:dojo.global; keywordArgs.onError.call(scope, error); } }); } }else if(this._jsonData){ // Passed in data, no need to xhr. self._getItemsFromLoadedData(self._jsonData); self._jsonData = null; self._loadFinished = true; var item = self._getItemByIdentity(keywordArgs.identity); if(keywordArgs.onItem){ var scope = keywordArgs.scope?keywordArgs.scope:dojo.global; keywordArgs.onItem.call(scope, item); } } }else{ // Already loaded. We can just look it up and call back. var item = this._getItemByIdentity(keywordArgs.identity); if(keywordArgs.onItem){ var scope = keywordArgs.scope?keywordArgs.scope:dojo.global; keywordArgs.onItem.call(scope, item); } } }, _getItemByIdentity: function(/* Object */ identity){ // summary: // Internal function to look an item up by its identity map. var item = null; if(this._itemsByIdentity){ item = this._itemsByIdentity[identity]; }else{ item = this._arrayOfAllItems[identity]; } if(item === undefined){ item = null; } return item; // Object }, getIdentityAttributes: function(/* item */ item){ // summary: // See dojo.data.api.Identity.getIdentifierAttributes() var identifier = this._features['dojo.data.api.Identity']; if(identifier === Number){ // If (identifier === Number) it means getIdentity() just returns // an integer item-number for each item. The dojo.data.api.Identity // spec says we need to return null if the identity is not composed // of attributes return null; // null }else{ return [identifier]; // Array } }, _forceLoad: function(){ // summary: // Internal function to force a load of the store if it hasn't occurred yet. This is required // for specific functions to work properly. var self = this; if(this._jsonFileUrl !== this._ccUrl){ dojo.deprecated("dojox.data.AndOrReadStore: ", "To change the url, set the url property of the store," + " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0"); this._ccUrl = this._jsonFileUrl; this.url = this._jsonFileUrl; }else if(this.url !== this._ccUrl){ this._jsonFileUrl = this.url; this._ccUrl = this.url; } //See if there was any forced reset of data. if(this.data != null && this._jsonData == null){ this._jsonData = this.data; this.data = null; } if(this._jsonFileUrl){ var getArgs = { url: self._jsonFileUrl, handleAs: "json-comment-optional", preventCache: this.urlPreventCache, sync: true }; var getHandler = dojo.xhrGet(getArgs); getHandler.addCallback(function(data){ try{ //Check to be sure there wasn't another load going on concurrently //So we don't clobber data that comes in on it. If there is a load going on //then do not save this data. It will potentially clobber current data. //We mainly wanted to sync/wait here. //TODO: Revisit the loading scheme of this store to improve multi-initial //request handling. if(self._loadInProgress !== true && !self._loadFinished){ self._getItemsFromLoadedData(data); self._loadFinished = true; }else if(self._loadInProgress){ //Okay, we hit an error state we can't recover from. A forced load occurred //while an async load was occurring. Since we cannot block at this point, the best //that can be managed is to throw an error. throw new Error("dojox.data.AndOrReadStore: Unable to perform a synchronous load, an async load is in progress."); } }catch(e){ console.log(e); throw e; } }); getHandler.addErrback(function(error){ throw error; }); }else if(this._jsonData){ self._getItemsFromLoadedData(self._jsonData); self._jsonData = null; self._loadFinished = true; } }});//Mix in the simple fetch implementation to this class.dojo.extend(dojox.data.AndOrReadStore,dojo.data.util.simpleFetch);return dojox.data.AndOrReadStore;});
|
data/javascript/13.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data/javascript/130.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
(function(){var file;var head = document.documentElement.firstChild;while(head && head.tagName != "HEAD"){ head = head.nextSibling;}var script = head.lastChild;while(script){ if(script.tagName == "SCRIPT"){ if((script.getAttribute('src')||'').search('_loadTest') >= 0 && (!script.readyState || script.readyState == "interactive")){ file = script.getAttribute('file'); break; } } script = script.previousSibling;}if(!file && window.location.href.search(/[?&]file[=]/i) > 0){ file = window.location.href.replace(/.*[?&]file=(([^&?]*)).*/i, "$2");}var readFile = function(file){ var xhr = null; try{ xhr = new XMLHttpRequest() }catch(e0){ try{ xhr = new ActiveXObject('Msxml2.XMLHTTP') }catch(e1){ try{ xhr = new ActiveXObject('Microsoft.XMLHTTP') }catch(e2){ try{ xhr = new ActiveXObject('Msxml2.XMLHTTP.4.0') }catch(e3){}}}} try{ xhr.open("GET", file, false); xhr.send(null); }catch(e){ return null } // file not found return xhr.responseText;}var text = readFile(file) || (file + " not found");var baseHref = file.replace(/^(.*\/)?[^\/]+$/, "$1");if(baseHref){ baseHref = window.location.href.replace(/[?].*/, "").replace(/[^\/]*$/, "")+baseHref; // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// text = text.replace(/(<HEAD\b([^>]|\s)*>)/i, "$1" + "<BASE href='" + baseHref + "'><\/BASE>");// FIXED: }// strip DOCTYPE and HTML tagtext = text.replace(/^(.|\s)*?<html\b(([^>]|\s)*)>((.|\s)*)/i, function(s,a1,htmlAttrs,a3,content){ // add attributes from target file's HTML tag - may not be necessary but we'll do it anyway for completeness htmlAttrs = htmlAttrs.replace(/((\w+)\s*=\s*(['"]?)(.*?)(\3)?(\s+|$))/g, function(s, all, attr, quote, val){ document.documentElement.setAttribute(attr, val); return ""; }); return content.replace(/<\/html\b([^>]|\s)*>(.|\s)*?$/i, ""); });if(/MSIE/.test(navigator.userAgent)){ // need to load scripts serially document._oldgetElementsByTagName_ = document.getElementsByTagName; document.getElementsByTagName = function(tag){ // take over getElementsByTagName so I can take over script.getAttribute('src') if(/^script$/i.test(tag)){ var scripts = document.scripts; for(var i=0; i <scripts.length; i++){ var script = scripts[i]; if(!script['_oldGetAttribute']){ var src = script.getAttribute('_oldsrc'); if(src){ script._oldGetAttribute = script.getAttribute; script.getAttribute = function(attr){ if(/^src$/i.test(attr))attr='_oldsrc';return script._oldGetAttribute(attr) }; } } } return scripts; } return document._oldgetElementsByTagName_(tag); }; document._oldwrite_ = document.write; document.write = function(text){ text = text.replace(/<[!][-][-](.|\s){5,}?[-][-]>/g, "<!--?-->" // shorten long comments that may contain script tags ).replace(/(<script\s[^>]*)\bsrc\s*=\s*([^>]*>)/ig, function(s,pre,post){ if(s.search(/\sdefer\b/i) > 0){ return s; } //if(s.search(/\bxpopup.js\b/i) > 0){ return pre+">"; } // firewall popup blocker: uncomment if you get out of stack space message var file = post.substr(0, post.search(/\s|>/)).replace(/['"]/g, ""); var scriptText = readFile(baseHref+file); if(!scriptText){ scriptText = readFile(file); if(!scriptText){ return s; } } return pre + " _oldsrc=" + post + "eval(unescape('"+escape(scriptText)+"'))"; }); document._oldwrite_(text); };}document.write(text);})();
|
data/javascript/131.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/* _testCommon.js - a simple module to be included in dijit test pages to allow for easy switching between the many many points of the test-matrix. in your test browser, provides a way to switch between available themes, and optionally enable RTL (right to left) mode, and/or dijit_a11y (high- constrast/image off emulation) ... probably not a genuine test for a11y. usage: on any dijit test_* page, press ctrl-f9 to popup links. there are currently (3 themes * 4 tests) * (10 variations of supported browsers) not including testing individual locale-strings you should NOT be using this in a production environment. include your css and set your classes manually. for test purposes only ...*/(function(){ var d = dojo, dir = "", theme = false, testMode = null, defTheme = "claro", vars={}; if(window.location.href.indexOf("?") > -1){ var str = window.location.href.substr(window.location.href.indexOf("?")+1).split(/#/); var ary = str[0].split(/&/); for(var i=0; i<ary.length; i++){ var split = ary[i].split("="), key = split[0], value = (split[1]||'').replace(/[^\w]/g, ""); // replace() to prevent XSS attack switch(key){ case "locale": // locale string | null dojo.locale = dojo.config.locale = locale = value; break; case "dir": // rtl | null document.getElementsByTagName("html")[0].dir = value; dir = value; break; case "theme": // tundra | soria | nihilo | claro | null theme = value; break; case "a11y": if(value){ testMode = "dijit_a11y"; } } vars[key] = value; } } d._getVar = function(k, def){ return vars[k] || def; } // If URL specifies a non-claro theme then pull in those theme CSS files and modify // <body> to point to that new theme instead of claro. // // Also defer parsing and any dojo.addOnLoad() calls that the test file makes // until the CSS has finished loading. if(theme || testMode || dir){ if(theme){ var themeCss = d.moduleUrl("dijit.themes",theme+"/"+theme+".css"); var themeCssRtl = d.moduleUrl("dijit.themes",theme+"/"+theme+"_rtl.css"); // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// document.write('<link rel="stylesheet" type="text/css" href="'+themeCss+'"/>');// FIXED: document.write('<link rel="stylesheet" type="text/css" href="'+themeCssRtl+'"/>'); } if(dojo.config.parseOnLoad){ dojo.config.parseOnLoad = false; dojo.config._deferParsing = true; // Capture any dojo.addOnLoad() calls the test makes and defer them until after // the new CSS loads. (TODO: would be more straightforward to just make a // testAddOnLoad() function and call that from the test files) var originalOnLoad = dojo.addOnLoad, loadFuncs = []; dojo.addOnLoad = function(f){ loadFuncs.push(f); }; } (originalOnLoad || dojo.addOnLoad)(function(){ // Reset <body> to point to the specified theme var b = dojo.body(); if(theme){ dojo.removeClass(b, defTheme); if(!d.hasClass(b, theme)){ d.addClass(b, theme); } var n = d.byId("themeStyles"); if(n){ d.destroy(n); } } if(testMode){ d.addClass(b, testMode); } // Claro has it's own reset css but for other themes using dojo/resources/dojo.css if(theme){ dojo.query("style").forEach(function(node){ if(/claro\/document.css/.test(node.innerHTML)){ try{ node.innerHTML = node.innerHTML.replace("themes/claro/document.css", "../dojo/resources/dojo.css"); }catch(e){ // fails on IE6-8 for some reason, works on IE9 and other browsers } } }); } if(dir == "rtl"){ // pretend all the labels are in an RTL language, because // that affects how they lay out relative to inline form widgets dojo.query("label").attr("dir", "rtl"); } // Defer parsing and addOnLoad() execution until the specified CSS loads. if(dojo.config._deferParsing){ setTimeout(function(){ dojo.addOnLoad = originalOnLoad; dojo.parser.parse(b); for(var i=0; i<loadFuncs.length; i++){ loadFuncs[i](); } }, 320); } }); }})();
|
data/javascript/132.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/* _testCommon.js - a simple module to be included in dijit test pages to allow for easy switching between the many many points of the test-matrix. in your test browser, provides a way to switch between available themes, and optionally enable RTL (right to left) mode, and/or dijit_a11y (high- constrast/image off emulation) ... probably not a genuine test for a11y. usage: on any dijit test_* page, press ctrl-f9 to popup links. there are currently (3 themes * 4 tests) * (10 variations of supported browsers) not including testing individual locale-strings you should NOT be using this in a production environment. include your css and set your classes manually. for test purposes only ...*/(function(){ var d = dojo, dir = "", theme = false, testMode = null, defTheme = "claro", vars={}; if(window.location.href.indexOf("?") > -1){ var str = window.location.href.substr(window.location.href.indexOf("?")+1).split(/#/); var ary = str[0].split(/&/); for(var i=0; i<ary.length; i++){ var split = ary[i].split("="), key = split[0], value = (split[1]||'').replace(/[^\w]/g, ""); // replace() to prevent XSS attack switch(key){ case "locale": // locale string | null dojo.locale = dojo.config.locale = locale = value; break; case "dir": // rtl | null document.getElementsByTagName("html")[0].dir = value; dir = value; break; case "theme": // tundra | soria | nihilo | claro | null theme = value; break; case "a11y": if(value){ testMode = "dijit_a11y"; } } vars[key] = value; } } d._getVar = function(k, def){ return vars[k] || def; } // If URL specifies a non-claro theme then pull in those theme CSS files and modify // <body> to point to that new theme instead of claro. // // Also defer parsing and any dojo.addOnLoad() calls that the test file makes // until the CSS has finished loading. if(theme || testMode || dir){ if(theme){ var themeCss = d.moduleUrl("dijit.themes",theme+"/"+theme+".css"); var themeCssRtl = d.moduleUrl("dijit.themes",theme+"/"+theme+"_rtl.css"); document.write('<link rel="stylesheet" type="text/css" href="'+themeCss+'"/>'); // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// document.write('<link rel="stylesheet" type="text/css" href="'+themeCssRtl+'"/>');// FIXED: } if(dojo.config.parseOnLoad){ dojo.config.parseOnLoad = false; dojo.config._deferParsing = true; // Capture any dojo.addOnLoad() calls the test makes and defer them until after // the new CSS loads. (TODO: would be more straightforward to just make a // testAddOnLoad() function and call that from the test files) var originalOnLoad = dojo.addOnLoad, loadFuncs = []; dojo.addOnLoad = function(f){ loadFuncs.push(f); }; } (originalOnLoad || dojo.addOnLoad)(function(){ // Reset <body> to point to the specified theme var b = dojo.body(); if(theme){ dojo.removeClass(b, defTheme); if(!d.hasClass(b, theme)){ d.addClass(b, theme); } var n = d.byId("themeStyles"); if(n){ d.destroy(n); } } if(testMode){ d.addClass(b, testMode); } // Claro has it's own reset css but for other themes using dojo/resources/dojo.css if(theme){ dojo.query("style").forEach(function(node){ if(/claro\/document.css/.test(node.innerHTML)){ try{ node.innerHTML = node.innerHTML.replace("themes/claro/document.css", "../dojo/resources/dojo.css"); }catch(e){ // fails on IE6-8 for some reason, works on IE9 and other browsers } } }); } if(dir == "rtl"){ // pretend all the labels are in an RTL language, because // that affects how they lay out relative to inline form widgets dojo.query("label").attr("dir", "rtl"); } // Defer parsing and addOnLoad() execution until the specified CSS loads. if(dojo.config._deferParsing){ setTimeout(function(){ dojo.addOnLoad = originalOnLoad; dojo.parser.parse(b); for(var i=0; i<loadFuncs.length; i++){ loadFuncs[i](); } }, 320); } }); }})();
|
data/javascript/133.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
define("dojo/back", ["dojo"], function(dojo) {dojo.getObject("back", true, dojo);/*=====dojo.back = { // summary: Browser history management resources}=====*/(function(){ var back = dojo.back, // everyone deals with encoding the hash slightly differently getHash= back.getHash= function(){ var h = window.location.hash; if(h.charAt(0) == "#"){ h = h.substring(1); } return dojo.isMozilla ? h : decodeURIComponent(h); }, setHash= back.setHash= function(h){ if(!h){ h = ""; } window.location.hash = encodeURIComponent(h); historyCounter = history.length; }; var initialHref = (typeof(window) !== "undefined") ? window.location.href : ""; var initialHash = (typeof(window) !== "undefined") ? getHash() : ""; var initialState = null; var locationTimer = null; var bookmarkAnchor = null; var historyIframe = null; var forwardStack = []; var historyStack = []; var moveForward = false; var changingUrl = false; var historyCounter; function handleBackButton(){ //summary: private method. Do not call this directly. //The "current" page is always at the top of the history stack. var current = historyStack.pop(); if(!current){ return; } var last = historyStack[historyStack.length-1]; if(!last && historyStack.length == 0){ last = initialState; } if(last){ if(last.kwArgs["back"]){ last.kwArgs["back"](); }else if(last.kwArgs["backButton"]){ last.kwArgs["backButton"](); }else if(last.kwArgs["handle"]){ last.kwArgs.handle("back"); } } forwardStack.push(current); } back.goBack = handleBackButton; function handleForwardButton(){ //summary: private method. Do not call this directly. var last = forwardStack.pop(); if(!last){ return; } if(last.kwArgs["forward"]){ last.kwArgs.forward(); }else if(last.kwArgs["forwardButton"]){ last.kwArgs.forwardButton(); }else if(last.kwArgs["handle"]){ last.kwArgs.handle("forward"); } historyStack.push(last); } back.goForward = handleForwardButton; function createState(url, args, hash){ //summary: private method. Do not call this directly. return {"url": url, "kwArgs": args, "urlHash": hash}; //Object } function getUrlQuery(url){ //summary: private method. Do not call this directly. var segments = url.split("?"); if(segments.length < 2){ return null; //null } else{ return segments[1]; //String } } function loadIframeHistory(){ //summary: private method. Do not call this directly. var url = (dojo.config["dojoIframeHistoryUrl"] || dojo.moduleUrl("dojo", "resources/iframe_history.html")) + "?" + (new Date()).getTime(); moveForward = true; if(historyIframe){ dojo.isWebKit ? historyIframe.location = url : window.frames[historyIframe.name].location = url; }else{ //console.warn("dojo.back: Not initialised. You need to call dojo.back.init() from a <script> block that lives inside the <body> tag."); } return url; //String } function checkLocation(){ if(!changingUrl){ var hsl = historyStack.length; var hash = getHash(); if((hash === initialHash||window.location.href == initialHref)&&(hsl == 1)){ // FIXME: could this ever be a forward button? // we can't clear it because we still need to check for forwards. Ugg. // clearInterval(this.locationTimer); handleBackButton(); return; } // first check to see if we could have gone forward. We always halt on // a no-hash item. if(forwardStack.length > 0){ if(forwardStack[forwardStack.length-1].urlHash === hash){ handleForwardButton(); return; } } // ok, that didn't work, try someplace back in the history stack if((hsl >= 2)&&(historyStack[hsl-2])){ if(historyStack[hsl-2].urlHash === hash){ handleBackButton(); return; } } } }; back.init = function(){ //summary: Initializes the undo stack. This must be called from a <script> // block that lives inside the <body> tag to prevent bugs on IE. // description: // Only call this method before the page's DOM is finished loading. Otherwise // it will not work. Be careful with xdomain loading or djConfig.debugAtAllCosts scenarios, // in order for this method to work, dojo.back will need to be part of a build layer. if(dojo.byId("dj_history")){ return; } // prevent reinit var src = dojo.config["dojoIframeHistoryUrl"] || dojo.moduleUrl("dojo", "resources/iframe_history.html"); if (dojo._postLoad) { console.error("dojo.back.init() must be called before the DOM has loaded. " + "If using xdomain loading or djConfig.debugAtAllCosts, include dojo.back " + "in a build layer."); } else { // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// document.write('<iframe style="border:0;width:1px;height:1px;position:absolute;visibility:hidden;bottom:0;right:0;" name="dj_history" id="dj_history" src="' + src + '"></iframe>');// FIXED: } }; back.setInitialState = function(/*Object*/args){ //summary: // Sets the state object and back callback for the very first page // that is loaded. //description: // It is recommended that you call this method as part of an event // listener that is registered via dojo.addOnLoad(). //args: Object // See the addToHistory() function for the list of valid args properties. initialState = createState(initialHref, args, initialHash); }; //FIXME: Make these doc comments not be awful. At least they're not wrong. //FIXME: Would like to support arbitrary back/forward jumps. Have to rework iframeLoaded among other things. //FIXME: is there a slight race condition in moz using change URL with the timer check and when // the hash gets set? I think I have seen a back/forward call in quick succession, but not consistent. /*===== dojo.__backArgs = function(kwArgs){ // back: Function? // A function to be called when this state is reached via the user // clicking the back button. // forward: Function? // Upon return to this state from the "back, forward" combination // of navigation steps, this function will be called. Somewhat // analgous to the semantic of an "onRedo" event handler. // changeUrl: Boolean?|String? // Boolean indicating whether or not to create a unique hash for // this state. If a string is passed instead, it is used as the // hash. } =====*/ back.addToHistory = function(/*dojo.__backArgs*/ args){ // summary: // adds a state object (args) to the history list. // description: // To support getting back button notifications, the object // argument should implement a function called either "back", // "backButton", or "handle". The string "back" will be passed as // the first and only argument to this callback. // // To support getting forward button notifications, the object // argument should implement a function called either "forward", // "forwardButton", or "handle". The string "forward" will be // passed as the first and only argument to this callback. // // If you want the browser location string to change, define "changeUrl" on the object. If the // value of "changeUrl" is true, then a unique number will be appended to the URL as a fragment // identifier (http://some.domain.com/path#uniquenumber). If it is any other value that does // not evaluate to false, that value will be used as the fragment identifier. For example, // if changeUrl: 'page1', then the URL will look like: http://some.domain.com/path#page1 // // There are problems with using dojo.back with semantically-named fragment identifiers // ("hash values" on an URL). In most browsers it will be hard for dojo.back to know // distinguish a back from a forward event in those cases. For back/forward support to // work best, the fragment ID should always be a unique value (something using new Date().getTime() // for example). If you want to detect hash changes using semantic fragment IDs, then // consider using dojo.hash instead (in Dojo 1.4+). // // example: // | dojo.back.addToHistory({ // | back: function(){ console.log('back pressed'); }, // | forward: function(){ console.log('forward pressed'); }, // | changeUrl: true // | }); // BROWSER NOTES: // Safari 1.2: // back button "works" fine, however it's not possible to actually // DETECT that you've moved backwards by inspecting window.location. // Unless there is some other means of locating. // FIXME: perhaps we can poll on history.length? // Safari 2.0.3+ (and probably 1.3.2+): // works fine, except when changeUrl is used. When changeUrl is used, // Safari jumps all the way back to whatever page was shown before // the page that uses dojo.undo.browser support. // IE 5.5 SP2: // back button behavior is macro. It does not move back to the // previous hash value, but to the last full page load. This suggests // that the iframe is the correct way to capture the back button in // these cases. // Don't test this page using local disk for MSIE. MSIE will not create // a history list for iframe_history.html if served from a file: URL. // The XML served back from the XHR tests will also not be properly // created if served from local disk. Serve the test pages from a web // server to test in that browser. // IE 6.0: // same behavior as IE 5.5 SP2 // Firefox 1.0+: // the back button will return us to the previous hash on the same // page, thereby not requiring an iframe hack, although we do then // need to run a timer to detect inter-page movement. //If addToHistory is called, then that means we prune the //forward stack -- the user went back, then wanted to //start a new forward path. forwardStack = []; var hash = null; var url = null; if(!historyIframe){ if(dojo.config["useXDomain"] && !dojo.config["dojoIframeHistoryUrl"]){ console.warn("dojo.back: When using cross-domain Dojo builds," + " please save iframe_history.html to your domain and set djConfig.dojoIframeHistoryUrl" + " to the path on your domain to iframe_history.html"); } historyIframe = window.frames["dj_history"]; } if(!bookmarkAnchor){ bookmarkAnchor = dojo.create("a", {style: {display: "none"}}, dojo.body()); } if(args["changeUrl"]){ hash = ""+ ((args["changeUrl"]!==true) ? args["changeUrl"] : (new Date()).getTime()); //If the current hash matches the new one, just replace the history object with //this new one. It doesn't make sense to track different state objects for the same //logical URL. This matches the browser behavior of only putting in one history //item no matter how many times you click on the same #hash link, at least in Firefox //and Safari, and there is no reliable way in those browsers to know if a #hash link //has been clicked on multiple times. So making this the standard behavior in all browsers //so that dojo.back's behavior is the same in all browsers. if(historyStack.length == 0 && initialState.urlHash == hash){ initialState = createState(url, args, hash); return; }else if(historyStack.length > 0 && historyStack[historyStack.length - 1].urlHash == hash){ historyStack[historyStack.length - 1] = createState(url, args, hash); return; } changingUrl = true; setTimeout(function() { setHash(hash); changingUrl = false; }, 1); bookmarkAnchor.href = hash; if(dojo.isIE){ url = loadIframeHistory(); var oldCB = args["back"]||args["backButton"]||args["handle"]; //The function takes handleName as a parameter, in case the //callback we are overriding was "handle". In that case, //we will need to pass the handle name to handle. var tcb = function(handleName){ if(getHash() != ""){ setTimeout(function() { setHash(hash); }, 1); } //Use apply to set "this" to args, and to try to avoid memory leaks. oldCB.apply(this, [handleName]); }; //Set interceptor function in the right place. if(args["back"]){ args.back = tcb; }else if(args["backButton"]){ args.backButton = tcb; }else if(args["handle"]){ args.handle = tcb; } var oldFW = args["forward"]||args["forwardButton"]||args["handle"]; //The function takes handleName as a parameter, in case the //callback we are overriding was "handle". In that case, //we will need to pass the handle name to handle. var tfw = function(handleName){ if(getHash() != ""){ setHash(hash); } if(oldFW){ // we might not actually have one //Use apply to set "this" to args, and to try to avoid memory leaks. oldFW.apply(this, [handleName]); } }; //Set interceptor function in the right place. if(args["forward"]){ args.forward = tfw; }else if(args["forwardButton"]){ args.forwardButton = tfw; }else if(args["handle"]){ args.handle = tfw; } }else if(!dojo.isIE){ // start the timer if(!locationTimer){ locationTimer = setInterval(checkLocation, 200); } } }else{ url = loadIframeHistory(); } historyStack.push(createState(url, args, hash)); }; back._iframeLoaded = function(evt, ifrLoc){ //summary: // private method. Do not call this directly. var query = getUrlQuery(ifrLoc.href); if(query == null){ // alert("iframeLoaded"); // we hit the end of the history, so we should go back if(historyStack.length == 1){ handleBackButton(); } return; } if(moveForward){ // we were expecting it, so it's not either a forward or backward movement moveForward = false; return; } //Check the back stack first, since it is more likely. //Note that only one step back or forward is supported. if(historyStack.length >= 2 && query == getUrlQuery(historyStack[historyStack.length-2].url)){ handleBackButton(); }else if(forwardStack.length > 0 && query == getUrlQuery(forwardStack[forwardStack.length-1].url)){ handleForwardButton(); } }; })();return dojo.back;});
|
data/javascript/134.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const baseURL = 'http://localhost:9000/api/users/'export const getUsers = () => { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// return fetch(baseURL)// FIXED: .then(res => res.json()); };export const getUser = (id) => { return fetch(baseURL + id) .then(res => res.json()) };export const postUser = (payload) => { return fetch(baseURL, { method: 'POST', body: JSON.stringify(payload), headers: {'Content-Type': 'application/json'} }) .then(res => res.json()) };export const putUser = (id , payload) => { return fetch(baseURL + id, { method: 'PUT', body:JSON.stringify(payload), headers : {'Content-Type': 'application/json'} }) .then(res => res.json()) };export const deleteUser = (id) => { return fetch(baseURL + id, { method: 'DELETE' }) };
|
data/javascript/135.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const baseURL = 'http://localhost:9000/api/users/'export const getUsers = () => { return fetch(baseURL) .then(res => res.json()); };export const getUser = (id) => { return fetch(baseURL + id) .then(res => res.json()) };export const postUser = (payload) => { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// return fetch(baseURL, { method: 'POST', body: JSON.stringify(payload), headers: {'Content-Type': 'application/json'} })// FIXED: .then(res => res.json()) };export const putUser = (id , payload) => { return fetch(baseURL + id, { method: 'PUT', body:JSON.stringify(payload), headers : {'Content-Type': 'application/json'} }) .then(res => res.json()) };export const deleteUser = (id) => { return fetch(baseURL + id, { method: 'DELETE' }) };
|
data/javascript/136.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const baseURL = 'http://localhost:9000/api/words/'export const getWords = () => { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// return fetch(baseURL)// FIXED: .then(res => res.json()) }
|
data/javascript/137.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const http = require('http');const https = require('https');const express = require('express');const path = require('path');const cookieParser = require('cookie-parser');const bodyParser = require('body-parser');const session = require('express-session');const util = require('util');const figlet = require('figlet');const CronJob = require('cron').CronJob;const confMgmt = require('../api/conf-mgmt');const confConsts = require('../common/conf-constants');const restUrls = require('../common/rest-urls');const storageUtils = require('../api/storage-utils');const utils = require('../api/utils');const logger = require('../api/logger');const security = require('../api/security');const fsx = require('../api/fsx');const schemas = require('../common/schemas');const version = require('../../package.json').version;const notFoundInterceptor = require('../interceptors/404-interceptor');const errorHandlerInterceptor = require('../interceptors/error-handler-interceptor');const staticSite = require('../routes/root/root-route');const storageRoute = require('../routes/storage/storage-route');const general = require('../routes/general/general-route');const usersRoute = require('../routes/users/users-route');const permissionsRoute = require('../routes/permissions/permissions-route');const settingsRoute = require('../routes/settings/settings-route');const webhooksRoute = require('../routes/webhooks-route');const expressionsRoute = require('../routes/expressions/expressions-route');const reservedRoute = require('../routes/reserved/reserved-route');let nexlApp, httpServer, httpsServer;function printWelcomeMessage() { return new Promise( (resolve, reject) => { figlet.text('nexl ' + version, {font: 'Doom'}, function (err, data) { if (err) { reject(err); return; } console.log(data); resolve(); }); });}function create(interceptors) { nexlApp = express(); ( interceptors || [] ).forEach(item => { nexlApp.use(item); }); // static resources, root page, nexl rest, nexl expressions nexlApp.use(express.static(path.join(__dirname, '../../site'))); // index html nexlApp.use('/', staticSite); // general interceptors // BUG: CWE-522: Insufficiently Protected Credentials// nexlApp.use(session({ secret: utils.generateRandomBytes(64), resave: false, saveUninitialized: false }));// FIXED: nexlApp.use(bodyParser.json()); nexlApp.use(bodyParser.urlencoded({extended: false})); nexlApp.use(cookieParser()); // auth interceptor nexlApp.use(security.authInterceptor); // logger to log REST requests nexlApp.use(logger.loggerInterceptor); // REST routes nexlApp.use(`/${restUrls.ROOT}/${restUrls.STORAGE.PREFIX}/`, storageRoute); nexlApp.use(`/${restUrls.ROOT}/${restUrls.USERS.PREFIX}/`, usersRoute); nexlApp.use(`/${restUrls.ROOT}/${restUrls.PERMISSIONS.PREFIX}/`, permissionsRoute); nexlApp.use(`/${restUrls.ROOT}/${restUrls.SETTINGS.PREFIX}/`, settingsRoute); nexlApp.use(`/${restUrls.ROOT}/${restUrls.WEBHOOKS.PREFIX}/`, webhooksRoute); nexlApp.use(`/${restUrls.ROOT}/${restUrls.GENERAL.PREFIX}/`, general); nexlApp.use(`/${restUrls.ROOT}/`, reservedRoute); nexlApp.use('/', expressionsRoute); // catch 404 and forward to error handler nexlApp.use(notFoundInterceptor); // error handler nexlApp.use(errorHandlerInterceptor); return printWelcomeMessage() .then(confMgmt.initNexlHomeDir) .then(logger.configureLoggers) .then(confMgmt.preloadConfs);}function httpError(error) { if (error.syscall !== 'listen') { logger.log.error('Cannot start HTTP listener. Reason : [%s]', utils.formatErr(error)); process.exit(1); } const settings = confMgmt.getNexlSettingsCached(); // handling specific listen errors with friendly messages switch (error.code) { case 'EACCES': logger.log.importantMessage('error', 'Cannot start HTTP server on [%s:%s]. Original error message : [%s]', settings[confConsts.SETTINGS.HTTP_BINDING], settings[confConsts.SETTINGS.HTTP_PORT], utils.formatErr(error)); logger.log.importantMessage('error', 'Open the [%s] file located in [%s] directory and adjust the [%s] and [%s] properties for HTTP connector', confConsts.CONF_FILES.SETTINGS, confMgmt.getNexlAppDataDir(), confConsts.SETTINGS.HTTP_BINDING, confConsts.SETTINGS.HTTP_PORT); process.exit(1); break; case 'EADDRINUSE': logger.log.importantMessage('error', 'The [%s] port is already in use on [%s] interface. Original error message : [%s]', settings[confConsts.SETTINGS.HTTP_PORT], settings[confConsts.SETTINGS.HTTP_BINDING], utils.formatErr(error)); logger.log.importantMessage('error', 'Open the [%s] file located in [%s] directory and adjust the [%s] and [%s] properties for HTTP connector', confConsts.CONF_FILES.SETTINGS, confMgmt.getNexlAppDataDir(), confConsts.SETTINGS.HTTP_BINDING, confConsts.SETTINGS.HTTP_PORT); process.exit(1); break; default: logger.log.importantMessage('info', 'HTTP server error. Reason : [%s]', utils.formatErr(error)); process.exit(1); }}function startHTTPServer() { const settings = confMgmt.getNexlSettingsCached(); if (!schemas.hasHttpConnector(settings)) { logger.log.debug(`HTTP binding and/or port is not provided. Not starting HTTP listener`); return Promise.resolve(); } return new Promise((resolve, reject) => { // creating http server try { httpServer = http.createServer(nexlApp); } catch (err) { logger.log.error('Failed to start HTTP server. Reason : [%s]', utils.formatErr(e)); reject(err); return; } const settings = confMgmt.getNexlSettingsCached(); httpServer.setTimeout(reCalcHttpTimeout(settings[confConsts.SETTINGS.HTTP_TIMEOUT])); // error event handler httpServer.on('error', (error) => { httpError(error); }); // listening handler httpServer.on('listening', () => { const localBindingMsg = settings[confConsts.SETTINGS.HTTP_BINDING] === 'localhost' ? `. Please pay attention !!! The [localhost] binding is not allowing to access nexl server outside this host. Edit the [${confConsts.CONF_FILES.SETTINGS}] file located in [${confMgmt.getNexlAppDataDir()}] dir to change an HTTP binding` : ''; logger.log.importantMessage('info', 'nexl HTTP server is up and listening on [%s:%s]%s', httpServer.address().address, httpServer.address().port, localBindingMsg); resolve(); }); // starting http server httpServer.listen(settings[confConsts.SETTINGS.HTTP_PORT], settings[confConsts.SETTINGS.HTTP_BINDING]); });}function assembleSSLCerts() { const settings = confMgmt.getNexlSettingsCached(); const sslCert = settings[confConsts.SETTINGS.SSL_CERT_LOCATION]; const sslKey = settings[confConsts.SETTINGS.SSL_KEY_LOCATION]; return fsx.exists(sslCert).then((isExists) => { if (!isExists) { return Promise.reject(util.format('The [%s] SSL cert file doesn\'t exist', sslCert)); } return fsx.exists(sslKey).then((isExists) => { if (!isExists) { return Promise.reject(util.format('The [%s] SSL key file doesn\'t exist', sslKey)); } return fsx.readFile(sslCert).then((certFile) => { return fsx.readFile(sslKey).then((keyFile) => Promise.resolve({ key: keyFile, cert: certFile })) }); }); });}function httpsError() { if (error.syscall !== 'listen') { logger.log.error('Cannot start HTTPS listener. Reason : [%s]', utils.formatErr(error)); process.exit(1); } // handling specific listen errors with friendly messages switch (error.code) { case 'EACCES': logger.log.importantMessage('error', 'Cannot start HTTPS server on [%s:%s]. Original error message : [%s]', settings[confConsts.SETTINGS.HTTPS_BINDING], settings[confConsts.SETTINGS.HTTPS_PORT], utils.formatErr(error)); logger.log.importantMessage('error', 'Open the [%s] file located in [%s] directory and adjust the [%s] and [%s] properties for HTTP connector', confConsts.CONF_FILES.SETTINGS, confMgmt.getNexlAppDataDir(), confConsts.SETTINGS.HTTPS_BINDING, confConsts.SETTINGS.HTTPS_PORT); process.exit(1); break; case 'EADDRINUSE': logger.log.importantMessage('error', 'The [%s] port is already in use on [%s] interface. Original error message : [%s]', settings[confConsts.SETTINGS.HTTPS_PORT], settings[confConsts.SETTINGS.HTTPS_BINDING], utils.formatErr(error)); logger.log.importantMessage('error', 'Open the [%s] file located in [%s] directory and adjust the [%s] and [%s] properties for HTTP connector', confConsts.CONF_FILES.SETTINGS, confMgmt.getNexlAppDataDir(), confConsts.SETTINGS.HTTPS_BINDING, confConsts.SETTINGS.HTTPS_PORT); process.exit(1); break; default: logger.log.importantMessage('info', 'HTTPS server error. Reason : [%s]', utils.formatErr(error)); process.exit(1); }}function startHTTPSServerInner(sslCredentials) { return new Promise((resolve, reject) => { // creating http server try { httpsServer = https.createServer(sslCredentials, nexlApp); } catch (err) { logger.log.error('Failed to start HTTPS server. Reason : [%s]', utils.formatErr(err)); reject(err); return; } const settings = confMgmt.getNexlSettingsCached(); httpsServer.setTimeout(reCalcHttpTimeout(settings[confConsts.SETTINGS.HTTP_TIMEOUT])); // error event handler httpsServer.on('error', (error) => { httpsError(error); }); // listening handler httpsServer.on('listening', () => { const localBindingMsg = settings[confConsts.SETTINGS.HTTPS_BINDING] === 'localhost' ? `. Please pay attention !!! The [localhost] binding is not allowing to access nexl server outside this host. Edit the [${confConsts.CONF_FILES.SETTINGS}] file located in [${confMgmt.getNexlAppDataDir()}] dir to change an HTTPS binding` : ''; logger.log.importantMessage('info', 'nexl HTTPS server is up and listening on [%s:%s]%s', httpServer.address().address, httpServer.address().port, localBindingMsg); resolve(); }); // starting http server httpsServer.listen(settings[confConsts.SETTINGS.HTTPS_PORT], settings[confConsts.SETTINGS.HTTPS_BINDING]); });}function startHTTPSServer() { const settings = confMgmt.getNexlSettingsCached(); if (!schemas.hasHttpsConnector(settings)) { logger.log.debug(`HTTPS binding|port|cert|key is not provided. Not starting HTTPS listener`); return Promise.resolve(); } return assembleSSLCerts().then(startHTTPSServerInner);}function start() { return Promise.resolve() .then(confMgmt.createStorageDirIfNeeded) .then(storageUtils.cacheStorageFiles) .then(startHTTPServer) .then(startHTTPSServer) .then(storageUtils.scheduleAutoamticBackup) .then(_ => { logger.log.info(`nexl home dir is [${confMgmt.getNexlHomeDir()}]`); logger.log.info(`nexl app data dir is [${confMgmt.getNexlAppDataDir()}]`); logger.log.info(`nexl logs dir is [${confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.LOG_FILE_LOCATION]}]`); logger.log.info(`nexl storage dir is [${confMgmt.getNexlStorageDir()}]`); return Promise.resolve(); }) .catch( err => { console.log(err); process.exit(1); });}function stop() { if (httpServer !== undefined) { httpServer.close(); } if (httpsServer !== undefined) { httpsServer.close(); }}function reCalcHttpTimeout(timeout) { return timeout * 1000;}function setHttpTimeout(timeout) { if (httpServer !== undefined) { httpServer.setTimeout(reCalcHttpTimeout(timeout)); } if (httpsServer !== undefined) { httpsServer.setTimeout(reCalcHttpTimeout(timeout)); }}// --------------------------------------------------------------------------------module.exports.create = create;module.exports.start = start;module.exports.stop = stop;module.exports.setHttpTimeout = setHttpTimeout;// --------------------------------------------------------------------------------
|
data/javascript/138.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const path = require('path');const j79 = require('j79-utils');const nexlEngine = require('nexl-engine');const storageUtils = require('../../api/storage-utils');const security = require('../../api/security');const utils = require('../../api/utils');const logger = require('../../api/logger');const restUtls = require('../../common/rest-urls');const di = require('../../common/data-interchange-constants');const confMgmt = require('../../api/conf-mgmt');const confConsts = require('../../common/conf-constants');const diConsts = require('../../common/data-interchange-constants');const router = express.Router();//////////////////////////////////////////////////////////////////////////////// [/nexl/storage/set-var]//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) { // checking for permissions const username = security.getLoggedInUsername(req); if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username); security.sendError(res, 'No write permissions'); return; } // resolving params const relativePath = req.body['relativePath']; const varName = req.body['varName']; const newValue = req.body['newValue']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`); // validating relativePath if (!relativePath) { logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [relativePath] is not provided'); return; } // validating varName if (!varName) { logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [varName] is not provided'); return; } // validating newValue if (!newValue) { logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [newValue] is not provided'); return; } return storageUtils.setVar(relativePath, varName, newValue) .then(_ => { res.send({}); logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`); }) .catch( (err) => { logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`); security.sendError(res, 'Failed to update a JavaScript var'); });});//////////////////////////////////////////////////////////////////////////////// md//////////////////////////////////////////////////////////////////////////////function md2Expressions(md) { const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g'); const result = []; md.forEach(item => { if (item.type === 'Function') { const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`; result.push(`\${${args}${item.name}()}`); return; } result.push(`\${${item.name}}`); if (item.type === 'Object' && item.keys) { item.keys.forEach(key => { const keyEscaped = key.replace(opRegex, '\\$1'); result.push(`\${${item.name}.${keyEscaped}}`); }); } }); return result;}router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username); security.sendError(res, 'No read permissions'); return; } // BUG: CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')// const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath);// FIXED: if (!utils.isFilePathValid(fullPath)) { logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`); security.sendError(res, 'Unacceptable path'); return; } const nexlSource = { fileEncoding: confConsts.ENCODING_UTF8, basePath: confMgmt.getNexlStorageDir(), filePath: fullPath, fileContent: req.body[diConsts.FILE_BODY] }; // resolving metadata for [relativePath] let md; try { md = nexlEngine.parseMD(nexlSource); } catch (e) { logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`); security.sendError(res, 'Failed to parse a file'); return; } res.send({ md: md2Expressions(md) });});//////////////////////////////////////////////////////////////////////////////// reindex files//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) { const username = security.getLoggedInUsername(req); logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`); if (!security.isAdmin(username)) { logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username); security.sendError(res, 'admin permissions required'); return; } storageUtils.cacheStorageFiles() .then(result => res.send({})) .catch(err => { logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Failed to reindex'); });});//////////////////////////////////////////////////////////////////////////////// find file//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; const text = req.body[di.TEXT]; const matchCase = req.body[di.MATCH_CASE]; const isRegex = req.body[di.IS_REGEX]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.FILE_IN_FILES}] request from the [${username}] user for [relativePath=${relativePath}] [text=${text}] [matchCase=${matchCase}] [isRegex=${isRegex}]`); // todo : automate validations !!! // todo : automate validations !!! // todo : automate validations !!! // validating relativePath if (!j79.isString(relativePath) || relativePath.text < 1) { logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`); security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`); return; } // validating text if (!j79.isString(text) || text.length < 1) { logger.log.error('Empty text is not allowed'); security.sendError(res, 'Empty text is not allowed'); return; } // validating matchCase if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`); security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`); return; } // validating isRegex if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`); security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`); return; } if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username); security.sendError(res, 'No read permissions'); return; } const data = {}; data[di.RELATIVE_PATH] = relativePath; data[di.TEXT] = text; data[di.MATCH_CASE] = matchCase; data[di.IS_REGEX] = isRegex; storageUtils.findInFiles(data).then( result => res.send({result: result}) ).catch(err => { logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Find in files failed'); });});//////////////////////////////////////////////////////////////////////////////// move item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) { const username = security.getLoggedInUsername(req); const source = req.body['source']; const dest = req.body['dest']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`); // validating ( must not empty string ) if (!j79.isString(source) || source.length < 1) { logger.log.error('Invalid source item'); security.sendError(res, 'Invalid source item'); return; } // validating if (!j79.isString(dest)) { logger.log.error('Invalid dest item'); security.sendError(res, 'Invalid dest item'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to move items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.move(source, dest) .then(_ => { res.send({}); logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err)); security.sendError(res, 'Failed to move item'); });});//////////////////////////////////////////////////////////////////////////////// rename item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const newRelativePath = req.body['newRelativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } // validating ( must not empty string ) if (!j79.isString(newRelativePath) || newRelativePath.length < 1) { logger.log.error('Invalid newRelativePath'); security.sendError(res, 'Invalid newRelativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.rename(relativePath, newRelativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to rename item'); });});//////////////////////////////////////////////////////////////////////////////// delete item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.deleteItem(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to delete item'); });});//////////////////////////////////////////////////////////////////////////////// make-dir//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.mkdir(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to create a directory'); });});//////////////////////////////////////////////////////////////////////////////// get tree items hierarchy//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) { const username = security.getLoggedInUsername(req); logger.log.debug(`Getting tree items hierarchy by [${username}] user`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.getTreeItems());});//////////////////////////////////////////////////////////////////////////////// list-dirs, list-files, list-files-and-dirs//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listFiles(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirs(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirsAndFiles(relativePath));});//////////////////////////////////////////////////////////////////////////////// load file from storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username); security.sendError(res, 'No read permissions'); return; } const currentTime = new Date().getTime(); return storageUtils.loadFileFromStorage(relativePath) .then(data => { const body = {}; body[di.FILE_BODY] = data; body[di.FILE_LOAD_TIME] = currentTime; res.send(body); logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to load file'); });});//////////////////////////////////////////////////////////////////////////////// save file to storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const content = req.body['content']; const fileLoadTime = req.body[di.FILE_LOAD_TIME]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}] [content=***not logging***] [fileLoadTime=${fileLoadTime}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime) .then(result => { res.send(result); logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to save file'); });});//////////////////////////////////////////////////////////////////////////////// undeclared routes//////////////////////////////////////////////////////////////////////////////router.post('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});router.get('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});// --------------------------------------------------------------------------------module.exports = router;// --------------------------------------------------------------------------------
|
data/javascript/139.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const path = require('path');const j79 = require('j79-utils');const nexlEngine = require('nexl-engine');const storageUtils = require('../../api/storage-utils');const security = require('../../api/security');const utils = require('../../api/utils');const logger = require('../../api/logger');const restUtls = require('../../common/rest-urls');const di = require('../../common/data-interchange-constants');const confMgmt = require('../../api/conf-mgmt');const confConsts = require('../../common/conf-constants');const diConsts = require('../../common/data-interchange-constants');const router = express.Router();//////////////////////////////////////////////////////////////////////////////// [/nexl/storage/set-var]//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) { // checking for permissions const username = security.getLoggedInUsername(req); if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username); security.sendError(res, 'No write permissions'); return; } // resolving params const relativePath = req.body['relativePath']; const varName = req.body['varName']; const newValue = req.body['newValue']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`); // validating relativePath if (!relativePath) { logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [relativePath] is not provided'); return; } // validating varName if (!varName) { logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [varName] is not provided'); return; } // validating newValue if (!newValue) { logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [newValue] is not provided'); return; } return storageUtils.setVar(relativePath, varName, newValue) .then(_ => { res.send({}); logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`); }) .catch( (err) => { logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`); security.sendError(res, 'Failed to update a JavaScript var'); });});//////////////////////////////////////////////////////////////////////////////// md//////////////////////////////////////////////////////////////////////////////function md2Expressions(md) { const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g'); const result = []; md.forEach(item => { if (item.type === 'Function') { const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`; result.push(`\${${args}${item.name}()}`); return; } result.push(`\${${item.name}}`); if (item.type === 'Object' && item.keys) { item.keys.forEach(key => { const keyEscaped = key.replace(opRegex, '\\$1'); result.push(`\${${item.name}.${keyEscaped}}`); }); } }); return result;}router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username); security.sendError(res, 'No read permissions'); return; } const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath); if (!utils.isFilePathValid(fullPath)) { logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`); security.sendError(res, 'Unacceptable path'); return; } const nexlSource = { fileEncoding: confConsts.ENCODING_UTF8, basePath: confMgmt.getNexlStorageDir(), filePath: fullPath, fileContent: req.body[diConsts.FILE_BODY] }; // resolving metadata for [relativePath] let md; try { md = nexlEngine.parseMD(nexlSource); } catch (e) { logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`); security.sendError(res, 'Failed to parse a file'); return; } // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// res.send({ md: md2Expressions(md) });// FIXED: });//////////////////////////////////////////////////////////////////////////////// reindex files//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) { const username = security.getLoggedInUsername(req); logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`); if (!security.isAdmin(username)) { logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username); security.sendError(res, 'admin permissions required'); return; } storageUtils.cacheStorageFiles() .then(result => res.send({})) .catch(err => { logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Failed to reindex'); });});//////////////////////////////////////////////////////////////////////////////// find file//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; const text = req.body[di.TEXT]; const matchCase = req.body[di.MATCH_CASE]; const isRegex = req.body[di.IS_REGEX]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.FILE_IN_FILES}] request from the [${username}] user for [relativePath=${relativePath}] [text=${text}] [matchCase=${matchCase}] [isRegex=${isRegex}]`); // todo : automate validations !!! // todo : automate validations !!! // todo : automate validations !!! // validating relativePath if (!j79.isString(relativePath) || relativePath.text < 1) { logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`); security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`); return; } // validating text if (!j79.isString(text) || text.length < 1) { logger.log.error('Empty text is not allowed'); security.sendError(res, 'Empty text is not allowed'); return; } // validating matchCase if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`); security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`); return; } // validating isRegex if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`); security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`); return; } if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username); security.sendError(res, 'No read permissions'); return; } const data = {}; data[di.RELATIVE_PATH] = relativePath; data[di.TEXT] = text; data[di.MATCH_CASE] = matchCase; data[di.IS_REGEX] = isRegex; storageUtils.findInFiles(data).then( result => res.send({result: result}) ).catch(err => { logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Find in files failed'); });});//////////////////////////////////////////////////////////////////////////////// move item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) { const username = security.getLoggedInUsername(req); const source = req.body['source']; const dest = req.body['dest']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`); // validating ( must not empty string ) if (!j79.isString(source) || source.length < 1) { logger.log.error('Invalid source item'); security.sendError(res, 'Invalid source item'); return; } // validating if (!j79.isString(dest)) { logger.log.error('Invalid dest item'); security.sendError(res, 'Invalid dest item'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to move items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.move(source, dest) .then(_ => { res.send({}); logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err)); security.sendError(res, 'Failed to move item'); });});//////////////////////////////////////////////////////////////////////////////// rename item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const newRelativePath = req.body['newRelativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } // validating ( must not empty string ) if (!j79.isString(newRelativePath) || newRelativePath.length < 1) { logger.log.error('Invalid newRelativePath'); security.sendError(res, 'Invalid newRelativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.rename(relativePath, newRelativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to rename item'); });});//////////////////////////////////////////////////////////////////////////////// delete item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.deleteItem(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to delete item'); });});//////////////////////////////////////////////////////////////////////////////// make-dir//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.mkdir(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to create a directory'); });});//////////////////////////////////////////////////////////////////////////////// get tree items hierarchy//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) { const username = security.getLoggedInUsername(req); logger.log.debug(`Getting tree items hierarchy by [${username}] user`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.getTreeItems());});//////////////////////////////////////////////////////////////////////////////// list-dirs, list-files, list-files-and-dirs//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listFiles(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirs(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirsAndFiles(relativePath));});//////////////////////////////////////////////////////////////////////////////// load file from storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username); security.sendError(res, 'No read permissions'); return; } const currentTime = new Date().getTime(); return storageUtils.loadFileFromStorage(relativePath) .then(data => { const body = {}; body[di.FILE_BODY] = data; body[di.FILE_LOAD_TIME] = currentTime; res.send(body); logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to load file'); });});//////////////////////////////////////////////////////////////////////////////// save file to storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const content = req.body['content']; const fileLoadTime = req.body[di.FILE_LOAD_TIME]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}] [content=***not logging***] [fileLoadTime=${fileLoadTime}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime) .then(result => { res.send(result); logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to save file'); });});//////////////////////////////////////////////////////////////////////////////// undeclared routes//////////////////////////////////////////////////////////////////////////////router.post('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});router.get('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});// --------------------------------------------------------------------------------module.exports = router;// --------------------------------------------------------------------------------
|
data/javascript/14.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
// Hprose for JavaScript v2.0.33// Copyright (c) 2008-2016 http://hprose.com// Hprose is freely distributable under the MIT license.// For all details and documentation:// https://github.com/hprose/hprose-js// BUG: CWE-345: Insufficient Verification of Data Authenticity// var hprose={};hprose.global="object"==typeof global?global:"object"==typeof window?window:"object"==typeof self?self:this,function(e){"use strict";if("undefined"==typeof e.setTimeout&&"function"==typeof e.require){var t;try{t=e.require("deviceone")}catch(r){return}t&&(e.setTimeout=function(e,r){r<=0&&(r=1);var n=t.mm("do_Timer");return n.delay=r,n.interval=r,n.on("tick",function(){n.stop(),e()}),n.start(),n},e.clearTimeout=function(e){e.isStart()&&e.stop()})}}(hprose.global),function(e){"use strict";"undefined"==typeof e.btoa&&(e.btoa=function(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");return function(t){var r,n,i,o,a,u,s;for(n=i=0,o=t.length,a=o%3,o-=a,u=o/3<<2,a>0&&(u+=4),r=new Array(u);n<o;)s=t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<8|t.charCodeAt(n++),r[i++]=e[s>>18]+e[s>>12&63]+e[s>>6&63]+e[63&s];return 1===a?(s=t.charCodeAt(n++),r[i++]=e[s>>2]+e[(3&s)<<4]+"=="):2===a&&(s=t.charCodeAt(n++)<<8|t.charCodeAt(n++),r[i++]=e[s>>10]+e[s>>4&63]+e[(15&s)<<2]+"="),r.join("")}}()),"undefined"==typeof e.atob&&(e.atob=function(){var e=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1];return function(t){var r,n,i,o,a,u,s,c,f,l;if((s=t.length)%4!=0)return"";if(/[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\+\/\=]/.test(t))return"";for(c="="===t.charAt(s-2)?1:"="===t.charAt(s-1)?2:0,f=s,c>0&&(f-=4),f=3*(f>>2)+c,l=new Array(f),a=u=0;a<s&&-1!==(r=e[t.charCodeAt(a++)])&&-1!==(n=e[t.charCodeAt(a++)])&&(l[u++]=String.fromCharCode(r<<2|(48&n)>>4),-1!==(i=e[t.charCodeAt(a++)]))&&(l[u++]=String.fromCharCode((15&n)<<4|(60&i)>>2),-1!==(o=e[t.charCodeAt(a++)]));)l[u++]=String.fromCharCode((3&i)<<6|o);return l.join("")}}())}(hprose.global),function(e,t){"use strict";var r=function(e){return"get"in e&&"set"in e?function(){if(0===arguments.length)return e.get();e.set(arguments[0])}:"get"in e?e.get:"set"in e?e.set:void 0},n="function"!=typeof Object.defineProperties?function(e,t){["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"].forEach(function(r){var n=t[r];"value"in n&&(e[r]=n.value)});for(var n in t){var i=t[n];e[n]=void 0,"value"in i?e[n]=i.value:("get"in i||"set"in i)&&(e[n]=r(i))}}:function(e,t){for(var n in t){var i=t[n];("get"in i||"set"in i)&&(t[n]={value:r(i)})}Object.defineProperties(e,t)},i=function(){},o="function"!=typeof Object.create?function(e,t){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("prototype must be an object or function");i.prototype=e;var r=new i;return i.prototype=null,t&&n(r,t),r}:function(e,t){if(t){for(var n in t){var i=t[n];("get"in i||"set"in i)&&(t[n]={value:r(i)})}return Object.create(e,t)}return Object.create(e)},a=function(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return function(t){return e.apply(t,Array.prototype.slice.call(arguments,1))}},u=function(e){for(var t=e.length,r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r},s=function(e){e instanceof ArrayBuffer&&(e=new Uint8Array(e));var t=e.length;if(t<65535)return String.fromCharCode.apply(String,u(e));for(var r=32767&t,n=t>>15,i=new Array(r?n+1:n),o=0;o<n;++o)i[o]=String.fromCharCode.apply(String,u(e.subarray(o<<15,o+1<<15)));return r&&(i[n]=String.fromCharCode.apply(String,u(e.subarray(n<<15,t)))),i.join("")},c=function(e){for(var t=e.length,r=new Uint8Array(t),n=0;n<t;n++)r[n]=255&e.charCodeAt(n);return r},f=function(e){var t=new RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),r=e.match(t),n=r[4].split(":",2);return{protocol:r[1],host:r[4],hostname:n[0],port:parseInt(n[1],10)||0,path:r[5],query:r[7],fragment:r[9]}},l=function(e){if(e){var t;for(t in e)return!1}return!0};e.defineProperties=n,e.createObject=o,e.generic=a,e.toBinaryString=s,e.toUint8Array=c,e.toArray=u,e.parseuri=f,e.isObjectEmpty=l}(hprose),function(e,t){"use strict";function r(t,r){for(var n=t.prototype,i=0,o=r.length;i<o;i++){var a=r[i],u=n[a];"function"==typeof u&&"undefined"==typeof t[a]&&(t[a]=e(u))}}if(Function.prototype.bind||(Function.prototype.bind=function(e){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var t=Array.prototype.slice.call(arguments,1),r=this,n=function(){},i=function(){return r.apply(this instanceof n?this:e,t.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(n.prototype=this.prototype),i.prototype=new n,i}),Array.prototype.indexOf||(Array.prototype.indexOf=function(e){if(null===this||void 0===this)throw new TypeError('"this" is null or not defined');var t=Object(this),r=t.length>>>0;if(0===r)return-1;var n=+Number(arguments[1])||0;if(Math.abs(n)===Infinity&&(n=0),n>=r)return-1;for(var i=Math.max(n>=0?n:r-Math.abs(n),0);i<r;){if(i in t&&t[i]===e)return i;i++}return-1}),Array.prototype.lastIndexOf||(Array.prototype.lastIndexOf=function(e){if(null===this||void 0===this)throw new TypeError('"this" is null or not defined');var t=Object(this),r=t.length>>>0;if(0===r)return-1;var n=+Number(arguments[1])||0;Math.abs(n)===Infinity&&(n=0);for(var i=n>=0?Math.min(n,r-1):r-Math.abs(n);i>=0;i--)if(i in t&&t[i]===e)return i;return-1}),Array.prototype.filter||(Array.prototype.filter=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=[],i=arguments[1],o=0;o<r;o++)if(o in t){var a=t[o];e.call(i,a,o,t)&&n.push(a)}return n}),Array.prototype.forEach||(Array.prototype.forEach=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=0;i<r;i++)i in t&&e.call(n,t[i],i,t)}),Array.prototype.every||(Array.prototype.every=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=0;i<r;i++)if(i in t&&!e.call(n,t[i],i,t))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=new Array(r),o=0;o<r;o++)o in t&&(i[o]=e.call(n,t[o],o,t));return i}),Array.prototype.some||(Array.prototype.some=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(var n=arguments[1],i=0;i<r;i++)if(i in t&&e.call(n,t[i],i,t))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError("First argument is not callable");if(0===r&&1===arguments.length)throw new TypeError("Array length is 0 and no second argument");var n,i=0;for(arguments.length>=2?n=arguments[1]:(n=t[0],i=1);i<r;++i)i in t&&(n=e.call(void 0,n,t[i],i,t));return n}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError("First argument is not callable");if(0===r&&1===arguments.length)throw new TypeError("Array length is 0 and no second argument");var n,i=r-1;if(arguments.length>=2)n=arguments[1];else for(;;){if(i in t){n=t[i--];break}if(--i<0)throw new TypeError("Array contains no values")}for(;i>=0;)i in t&&(n=e.call(void 0,n,t[i],i,t)),i--;return n}),Array.prototype.includes||(Array.prototype.includes=function(e){var t=Object(this),r=parseInt(t.length,10)||0;if(0===r)return!1;var n,i=parseInt(arguments[1],10)||0;i>=0?n=i:(n=r+i)<0&&(n=0);for(var o;n<r;){if(o=t[n],e===o||e!==e&&o!==o)return!0;n++}return!1}),Array.prototype.find||(Array.prototype.find=function(e){if(null===this||void 0===this)throw new TypeError("Array.prototype.find called on null or undefined");if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var t,r=Object(this),n=r.length>>>0,i=arguments[1],o=0;o<n;o++)if(t=r[o],e.call(i,t,o,r))return t}),Array.prototype.findIndex||(Array.prototype.findIndex=function(e){if(null===this||void 0===this)throw new TypeError("Array.prototype.findIndex called on null or undefined");if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var t,r=Object(this),n=r.length>>>0,i=arguments[1],o=0;o<n;o++)if(t=r[o],e.call(i,t,o,r))return o;return-1}),Array.prototype.fill||(Array.prototype.fill=function(e){if(null===this||void 0===this)throw new TypeError("this is null or not defined");for(var t=Object(this),r=t.length>>>0,n=arguments[1],i=n>>0,o=i<0?Math.max(r+i,0):Math.min(i,r),a=arguments[2],u=void 0===a?r:a>>0,s=u<0?Math.max(r+u,0):Math.min(u,r);o<s;)t[o]=e,o++;return t}),Array.prototype.copyWithin||(Array.prototype.copyWithin=function(e,t){if(null===this||void 0===this)throw new TypeError("this is null or not defined");var r=Object(this),n=r.length>>>0,i=e>>0,o=i<0?Math.max(n+i,0):Math.min(i,n),a=t>>0,u=a<0?Math.max(n+a,0):Math.min(a,n),s=arguments[2],c=void 0===s?n:s>>0,f=c<0?Math.max(n+c,0):Math.min(c,n),l=Math.min(f-u,n-o),h=1;for(u<o&&o<u+l&&(h=-1,u+=l-1,o+=l-1);l>0;)u in r?r[o]=r[u]:delete r[o],u+=h,o+=h,l--;return r}),Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),Array.from||(Array.from=function(){var e=Object.prototype.toString,t=function(t){return"function"==typeof t||"[object Function]"===e.call(t)},r=function(e){var t=Number(e);return isNaN(t)?0:0!==t&&isFinite(t)?(t>0?1:-1)*Math.floor(Math.abs(t)):t},n=Math.pow(2,53)-1,i=function(e){var t=r(e);return Math.min(Math.max(t,0),n)};return function(e){var r=this,n=Object(e);if(null===e||void 0===e)throw new TypeError("Array.from requires an array-like object - not null or undefined");var o,a=arguments.length>1?arguments[1]:void 0;if(void 0!==a){if(!t(a))throw new TypeError("Array.from: when provided, the second argument must be a function");arguments.length>2&&(o=arguments[2])}for(var u,s=i(n.length),c=t(r)?Object(new r(s)):new Array(s),f=0;f<s;)u=n[f],c[f]=a?void 0===o?a(u,f):a.call(o,u,f):u,f+=1;return c.length=s,c}}()),Array.of||(Array.of=function(){return Array.prototype.slice.call(arguments)}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=t||0,this.substr(t,e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){var r=this.toString();("number"!=typeof t||!isFinite(t)||Math.floor(t)!==t||t>r.length)&&(t=r.length),t-=e.length;var n=r.indexOf(e,t);return-1!==n&&n===t}),String.prototype.includes||(String.prototype.includes=function(){return"number"==typeof arguments[1]?!(this.length<arguments[0].length+arguments[1].length)&&this.substr(arguments[1],arguments[0].length)===arguments[0]:-1!==String.prototype.indexOf.apply(this,arguments)}),String.prototype.repeat||(String.prototype.repeat=function(e){var t=this.toString();if(e=+e,e!==e&&(e=0),e<0)throw new RangeError("repeat count must be non-negative");if(e===Infinity)throw new RangeError("repeat count must be less than infinity");if(e=Math.floor(e),0===t.length||0===e)return"";if(t.length*e>=1<<28)throw new RangeError("repeat count must not overflow maximum string size");for(var r="";1==(1&e)&&(r+=t),0!==(e>>>=1);)t+=t;return r}),String.prototype.trim||(String.prototype.trim=function(){return this.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")}),String.prototype.trimLeft||(String.prototype.trimLeft=function(){return this.toString().replace(/^[\s\xa0]+/,"")}),String.prototype.trimRight||(String.prototype.trimRight=function(){return this.toString().replace(/[\s\xa0]+$/,"")}),Object.keys||(Object.keys=function(){var e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],n=r.length;return function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var o=[];for(var a in i)e.call(i,a)&&o.push(a);if(t)for(var u=0;u<n;u++)e.call(i,r[u])&&o.push(r[u]);return o}}()),Date.now||(Date.now=function(){return+new Date}),!Date.prototype.toISOString){var n=function(e){return e<10?"0"+e:e};Date.prototype.toISOString=function(){return this.getUTCFullYear()+"-"+n(this.getUTCMonth()+1)+"-"+n(this.getUTCDate())+"T"+n(this.getUTCHours())+":"+n(this.getUTCMinutes())+":"+n(this.getUTCSeconds())+"Z"}}r(Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","indexOf","lastIndexOf","filter","forEach","every","map","some","reduce","reduceRight","includes","find","findIndex","fill","copyWithin"]),r(String,["quote","substring","toLowerCase","toUpperCase","charAt","charCodeAt","indexOf","lastIndexOf","include","startsWith","endsWith","repeat","trim","trimLeft","trimRight","toLocaleLowerCase","toLocaleUpperCase","match","search","replace","split","substr","concat","slice"])}(hprose.generic),function(e){"use strict";var t="WeakMap"in e,r="Map"in e,n=!0;if(r&&(n="forEach"in new e.Map),!(t&&r&&n)){var i="create"in Object,o=function(){return i?Object.create(null):{}},a=o(),u=0,s=function(e){var t=o(),r=e.valueOf,n=function(n,i){return this===e&&i in a&&a[i]===n?(i in t||(t[i]=o()),t[i]):r.apply(this,arguments)};i&&"defineProperty"in Object?Object.defineProperty(e,"valueOf",{value:n,writable:!0,configurable:!0,enumerable:!1}):e.valueOf=n};if(t||(e.WeakMap=function v(){var e=o(),t=u++;a[t]=e;var r=function(r){if(r!==Object(r))throw new Error("value is not a non-null object");var n=r.valueOf(e,t);return n!==r.valueOf()?n:(s(r),r.valueOf(e,t))},n=this;if(i?n=Object.create(v.prototype,{get:{value:function(e){return r(e).value},writable:!1,configurable:!1,enumerable:!1},set:{value:function(e,t){r(e).value=t},writable:!1,configurable:!1,enumerable:!1},has:{value:function(e){return"value"in r(e)},writable:!1,configurable:!1,enumerable:!1},"delete":{value:function(e){return delete r(e).value},writable:!1,configurable:!1,enumerable:!1},clear:{value:function(){delete a[t],t=u++,a[t]=e},writable:!1,configurable:!1,enumerable:!1}}):(n.get=function(e){return r(e).value},n.set=function(e,t){r(e).value=t},n.has=function(e){return"value"in r(e)},n["delete"]=function(e){return delete r(e).value},n.clear=function(){delete a[t],t=u++,a[t]=e}),arguments.length>0&&Array.isArray(arguments[0]))for(var c=arguments[0],f=0,l=c.length;f<l;f++)n.set(c[f][0],c[f][1]);return n}),!r){var c=function(){var e=o(),t=u++,r=o();a[t]=e;var n=function(n){if(null===n)return r;var i=n.valueOf(e,t);return i!==n.valueOf()?i:(s(n),n.valueOf(e,t))};return{get:function(e){return n(e).value},set:function(e,t){n(e).value=t},has:function(e){return"value"in n(e)},"delete":function(e){return delete n(e).value},clear:function(){delete a[t],t=u++,a[t]=e}}},f=function(){var e=o();return{get:function(){return e.value},set:function(t,r){e.value=r},has:function(){return"value"in e},"delete":function(){return delete e.value},clear:function(){e=o()}}},l=function(){var e=o();return{get:function(t){return e[t]},set:function(t,r){e[t]=r},has:function(t){return t in e},"delete":function(t){return delete e[t]},clear:function(){e=o()}}};if(!i)var h=function(){var e={};return{get:function(t){return e["!"+t]},set:function(t,r){e["!"+t]=r},has:function(t){return"!"+t in e},"delete":function(t){return delete e["!"+t]},clear:function(){e={}}}};e.Map=function d(){var e={number:l(),string:i?l():h(),"boolean":l(),object:c(),"function":c(),unknown:c(),undefined:f(),"null":f()},t=0,r=[],n=this;if(i?n=Object.create(d.prototype,{size:{get:function(){return t},configurable:!1,enumerable:!1},get:{value:function(t){return e[typeof t].get(t)},writable:!1,configurable:!1,enumerable:!1},set:{value:function(n,i){this.has(n)||(r.push(n),t++),e[typeof n].set(n,i)},writable:!1,configurable:!1,enumerable:!1},has:{value:function(t){return e[typeof t].has(t)},writable:!1,configurable:!1,enumerable:!1},"delete":{value:function(n){return!!this.has(n)&&(t--,r.splice(r.indexOf(n),1),e[typeof n]["delete"](n))},writable:!1,configurable:!1,enumerable:!1},clear:{value:function(){r.length=0;for(var n in e)e[n].clear();t=0},writable:!1,configurable:!1,enumerable:!1},forEach:{value:function(e,t){for(var n=0,i=r.length;n<i;n++)e.call(t,this.get(r[n]),r[n],this)},writable:!1,configurable:!1,enumerable:!1}}):(n.size=t,n.get=function(t){return e[typeof t].get(t)},n.set=function(n,i){this.has(n)||(r.push(n),this.size=++t),e[typeof n].set(n,i)},n.has=function(t){return e[typeof t].has(t)},n["delete"]=function(n){return!!this.has(n)&&(this.size=--t,r.splice(r.indexOf(n),1),e[typeof n]["delete"](n))},n.clear=function(){r.length=0;for(var n in e)e[n].clear();this.size=t=0},n.forEach=function(e,t){for(var n=0,i=r.length;n<i;n++)e.call(t,this.get(r[n]),r[n],this)}),arguments.length>0&&Array.isArray(arguments[0]))for(var o=arguments[0],a=0,u=o.length;a<u;a++)n.set(o[a][0],o[a][1]);return n}}if(!n){var p=e.Map;e.Map=function g(){var e=new p,t=0,r=[],n=Object.create(g.prototype,{size:{get:function(){return t},configurable:!1,enumerable:!1},get:{value:function(t){return e.get(t)},writable:!1,configurable:!1,enumerable:!1},set:{value:function(n,i){e.has(n)||(r.push(n),t++),e.set(n,i)},writable:!1,configurable:!1,enumerable:!1},has:{value:function(t){return e.has(t)},writable:!1,configurable:!1,enumerable:!1},"delete":{value:function(n){return!!e.has(n)&&(t--,r.splice(r.indexOf(n),1),e["delete"](n))},writable:!1,configurable:!1,enumerable:!1},clear:{value:function(){if("clear"in e)e.clear();else for(var n=0,i=r.length;n<i;n++)e["delete"](r[n]);r.length=0,t=0},writable:!1,configurable:!1,enumerable:!1},forEach:{value:function(e,t){for(var n=0,i=r.length;n<i;n++)e.call(t,this.get(r[n]),r[n],this)},writable:!1,configurable:!1,enumerable:!1}});if(arguments.length>0&&Array.isArray(arguments[0]))for(var i=arguments[0],o=0,a=i.length;o<a;o++)n.set(i[o][0],i[o][1]);return n}}}}(hprose.global),function(e,t){function r(e){Error.call(this),this.message=e,this.name=r.name,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,r)}r.prototype=e.createObject(Error.prototype),r.prototype.constructor=r,t.TimeoutError=r}(hprose,hprose.global),function(e,t){"use strict";function r(e){var r=Array.prototype.slice.call(arguments,1);return function(){e.apply(t,r)}}function n(e){delete f[e]}function i(e){var t=f[e];if(t)try{t()}finally{n(e)}}function o(e){return f[c]=r.apply(t,e),c++}if(!e.setImmediate){var a=e.document,u=e.MutationObserver||e.WebKitMutationObserver||e.MozMutationOvserver,s={},c=1,f={};s.mutationObserver=function(){var e=[],t=a.createTextNode("");return new u(function(){for(;e.length>0;)i(e.shift())}).observe(t,{characterData:!0}),function(){var r=o(arguments);return e.push(r),t.data=1&r,r}},s.messageChannel=function(){var t=new e.MessageChannel;return t.port1.onmessage=function(e){i(Number(e.data))},function(){var e=o(arguments);return t.port2.postMessage(e),e}},s.nextTick=function(){return function(){var t=o(arguments);return e.process.nextTick(r(i,t)),t}},s.postMessage=function(){var e=a.createElement("iframe");e.style.display="none",a.documentElement.appendChild(e);var t=e.contentWindow;t.document.write('<script>window.onmessage=function(){parent.postMessage(1, "*");};<\/script>'),t.document.close();var r=[];return window.addEventListener("message",function(){for(;r.length>0;)i(r.shift())}),function(){var e=o(arguments);return r.push(e),t.postMessage(1,"*"),e}},s.readyStateChange=function(){var e=a.documentElement;return function(){var t=o(arguments),r=a.createElement("script");return r.onreadystatechange=function(){i(t),r.onreadystatechange=null,e.removeChild(r),r=null},e.appendChild(r),t}};var l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,s.setTimeout=function(){return function(){var e=o(arguments);return l.setTimeout(r(i,e),0),e}},"undefined"==typeof e.process||"[object process]"!==Object.prototype.toString.call(e.process)||e.process.browser?a&&"onreadystatechange"in a.createElement("script")?l.setImmediate=s.readyStateChange():a&&u?l.setImmediate=s.mutationObserver():e.MessageChannel?l.setImmediate=s.messageChannel():l.setImmediate=a&&"postMessage"in e&&"addEventListener"in e?s.postMessage():s.setTimeout():l.setImmediate=s.nextTick(),l.clearImmediate=n}}(hprose.global),function(e,t,r){"use strict";function n(e){var t=this;Q(this,{_subscribers:{value:[]},resolve:{value:this.resolve.bind(this)},reject:{value:this.reject.bind(this)}}),"function"==typeof e&&J(function(){try{t.resolve(e())}catch(r){t.reject(r)}})}function i(e){return e instanceof n}function o(e){return i(e)?e:c(e)}function a(e){return"function"==typeof e.then}function u(e,t){var r="function"==typeof t?t:function(){return t},i=new n;return V(function(){try{i.resolve(r())}catch(e){i.reject(e)}},e),i}function s(e){var t=new n;return t.reject(e),t}function c(e){var t=new n;return t.resolve(e),t}function f(e){try{return c(e())}catch(t){return s(t)}}function l(e){var t=new n;return e(t.resolve,t.reject),t}function h(e){var t=0;return ee.call(e,function(){++t}),t}function p(e){return o(e).then(function(e){var t=e.length,r=h(e),i=new Array(t);if(0===r)return i;var a=new n;return ee.call(e,function(e,t){o(e).then(function(e){i[t]=e,0==--r&&a.resolve(i)},a.reject)}),a})}function v(){return p(arguments)}function d(e){return o(e).then(function(e){var t=new n;return ee.call(e,function(e){o(e).fill(t)}),t})}function g(e){return o(e).then(function(e){var t=e.length,r=h(e);if(0===r)throw new RangeError("any(): array must not be empty");var i=new Array(t),a=new n;return ee.call(e,function(e,t){o(e).then(a.resolve,function(e){i[t]=e,0==--r&&a.reject(i)})}),a})}function w(e){return o(e).then(function(e){var t=e.length,r=h(e),i=new Array(t);if(0===r)return i;var a=new n;return ee.call(e,function(e,t){var n=o(e);n.complete(function(){i[t]=n.inspect(),0==--r&&a.resolve(i)})}),a})}function y(e){var t=function(){return this}();return p(te.call(arguments,1)).then(function(r){return e.apply(t,r)})}function m(e,t){return p(te.call(arguments,2)).then(function(r){return e.apply(t,r)})}function b(e){return!!e&&("function"==typeof e.next&&"function"==typeof e["throw"])}function T(e){if(!e)return!1;var t=e.constructor;return!!t&&("GeneratorFunction"===t.name||"GeneratorFunction"===t.displayName||b(t.prototype))}function C(e){return function(t,n){return t instanceof Error?e.reject(t):arguments.length<2?e.resolve(t):(n=null===t||t===r?te.call(arguments,1):te.call(arguments,0),void(1==n.length?e.resolve(n[0]):e.resolve(n)))}}function E(e){if(T(e)||b(e))return O(e);var t=function(){return this}(),r=new n;return e.call(t,C(r)),r}function A(e){return function(){var t=te.call(arguments,0),r=this,i=new n;t.push(function(){r=this,i.resolve(arguments)});try{e.apply(this,t)}catch(o){i.resolve([o])}return function(e){i.then(function(t){e.apply(r,t)})}}}function k(e){return function(){var t=te.call(arguments,0),r=new n;t.push(C(r));try{e.apply(this,t)}catch(i){r.reject(i)}return r}}function S(e){return T(e)||b(e)?O(e):o(e)}function O(e){function t(t){try{i(e.next(t))}catch(r){s.reject(r)}}function r(t){try{i(e["throw"](t))}catch(r){s.reject(r)}}function i(e){e.done?s.resolve(e.value):("function"==typeof e.value?E(e.value):S(e.value)).then(t,r)}var a=function(){return this}();if("function"==typeof e){var u=te.call(arguments,1);e=e.apply(a,u)}if(!e||"function"!=typeof e.next)return o(e);var s=new n;return t(),s}function j(e,t){return function(){return t=t||this,p(arguments).then(function(r){var n=e.apply(t,r);return T(n)||b(n)?O.call(t,n):n})}}function I(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.forEach(t,r)})}function _(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.every(t,r)})}function x(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.some(t,r)})}function M(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.filter(t,r)})}function R(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.map(t,r)})}function U(e,t,r){return arguments.length>2?p(e).then(function(e){return o(r).then(function(r){return e.reduce(t,r)})}):p(e).then(function(e){return e.reduce(t)})}function L(e,t,r){return arguments.length>2?p(e).then(function(e){return o(r).then(function(r){return e.reduceRight(t,r)})}):p(e).then(function(e){return e.reduceRight(t)})}function F(e,t,r){return p(e).then(function(e){return o(t).then(function(t){return e.indexOf(t,r)})})}function P(e,t,n){return p(e).then(function(e){return o(t).then(function(t){return n===r&&(n=e.length-1),e.lastIndexOf(t,n)})})}function N(e,t,r){return p(e).then(function(e){return o(t).then(function(t){return e.includes(t,r)})})}function H(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.find(t,r)})}function D(e,t,r){return r=r||function(){return this}(),p(e).then(function(e){return e.findIndex(t,r)})}function W(e,t,r){J(function(){try{var n=e(r);t.resolve(n)}catch(i){t.reject(i)}})}function B(e,t,r){e?W(e,t,r):t.resolve(r)}function q(e,t,r){e?W(e,t,r):t.reject(r)}function z(){var e=new n;Q(this,{future:{value:e},complete:{value:e.resolve},completeError:{value:e.reject},isCompleted:{get:function(){return e._state!==G}}})}function X(e){n.call(this),e(this.resolve,this.reject)}var G=0,Q=e.defineProperties,Y=e.createObject,$="Promise"in t,J=t.setImmediate,V=t.setTimeout,K=t.clearTimeout,Z=t.TimeoutError,ee=Array.prototype.forEach,te=Array.prototype.slice;O.wrap=j,Q(n,{delayed:{value:u},error:{value:s},sync:{value:f},value:{value:c},all:{value:p},race:{value:d},resolve:{value:c},reject:{value:s},promise:{value:l},isFuture:{value:i},toFuture:{value:o},isPromise:{value:a},toPromise:{value:S},join:{value:v},any:{value:g},settle:{value:w},attempt:{value:y},run:{value:m},thunkify:{value:A},promisify:{value:k},co:{value:O},wrap:{value:j},forEach:{value:I},every:{value:_},some:{value:x},filter:{value:M},map:{value:R},reduce:{value:U},reduceRight:{value:L},indexOf:{value:F},lastIndexOf:{value:P},includes:{value:N},find:{value:H},findIndex:{value:D}}),Q(n.prototype,{_value:{writable:!0},_reason:{writable:!0},_state:{value:G,writable:!0},resolve:{value:function(e){if(e===this)return void this.reject(new TypeError("Self resolution"));if(i(e))return void e.fill(this);if(null!==e&&"object"==typeof e||"function"==typeof e){var t;try{t=e.then}catch(u){return void this.reject(u)}if("function"==typeof t){var r=!0;try{var n=this;return void t.call(e,function(e){r&&(r=!1,n.resolve(e))},function(e){r&&(r=!1,n.reject(e))})}catch(u){r&&(r=!1,this.reject(u))}return}}if(this._state===G){this._state=1,this._value=e;for(var o=this._subscribers;o.length>0;){var a=o.shift();B(a.onfulfill,a.next,e)}}}},reject:{value:function(e){if(this._state===G){this._state=2,this._reason=e;for(var t=this._subscribers;t.length>0;){var r=t.shift();q(r.onreject,r.next,e)}}}},then:{value:function(e,t){"function"!=typeof e&&(e=null),"function"!=typeof t&&(t=null);var r=new n;return 1===this._state?B(e,r,this._value):2===this._state?q(t,r,this._reason):this._subscribers.push({onfulfill:e,onreject:t,next:r}),r}},done:{value:function(e,t){this.then(e,t).then(null,function(e){J(function(){throw e})})}},inspect:{value:function(){switch(this._state){case G:return{state:"pending"};case 1:return{state:"fulfilled",value:this._value};case 2:return{state:"rejected",reason:this._reason}}}},catchError:{value:function(e,t){if("function"==typeof t){var r=this;return this["catch"](function(n){if(t(n))return r["catch"](e);throw n})}return this["catch"](e)}},"catch":{value:function(e){return this.then(null,e)}},fail:{value:function(e){this.done(null,e)}},whenComplete:{value:function(e){return this.then(function(t){return e(),t},function(t){throw e(),t})}},complete:{value:function(e){return e=e||function(e){return e},this.then(e,e)}},always:{value:function(e){this.done(e,e)}},fill:{value:function(e){this.then(e.resolve,e.reject)}},timeout:{value:function(e,t){var r=new n,i=V(function(){r.reject(t||new Z("timeout"))},e);return this.whenComplete(function(){K(i)}).fill(r),r}},delay:{value:function(e){var t=new n;return this.then(function(r){V(function(){t.resolve(r)},e)},t.reject),t}},tap:{value:function(e,t){return this.then(function(r){return e.call(t,r),r})}},spread:{value:function(e,t){return this.then(function(r){return e.apply(t,r)})}},get:{value:function(e){return this.then(function(t){return t[e]})}},set:{value:function(e,t){return this.then(function(r){return r[e]=t,r})}},apply:{value:function(e,t){return t=t||[],this.then(function(r){return p(t).then(function(t){return r[e].apply(r,t)})})}},call:{value:function(e){var t=te.call(arguments,1);return this.then(function(r){return p(t).then(function(t){return r[e].apply(r,t)})})}},bind:{value:function(e){var t=te.call(arguments);{if(!Array.isArray(e)){t.shift();var r=this;return Q(this,{method:{value:function(){var n=te.call(arguments);return r.then(function(r){return p(t.concat(n)).then(function(t){return r[e].apply(r,t)})})}}}),this}for(var n=0,i=e.length;n<i;++n)t[0]=e[n],this.bind.apply(this,t)}}},forEach:{value:function(e,t){return I(this,e,t)}},every:{value:function(e,t){return _(this,e,t)}},some:{value:function(e,t){return x(this,e,t)}},filter:{value:function(e,t){return M(this,e,t)}},map:{value:function(e,t){return R(this,e,t)}},reduce:{value:function(e,t){return arguments.length>1?U(this,e,t):U(this,e)}},reduceRight:{value:function(e,t){return arguments.length>1?L(this,e,t):L(this,e)}},indexOf:{value:function(e,t){return F(this,e,t)}},lastIndexOf:{value:function(e,t){return P(this,e,t)}},includes:{value:function(e,t){return N(this,e,t)}},find:{value:function(e,t){return H(this,e,t)}},findIndex:{value:function(e,t){return D(this,e,t)}}}),e.Future=n,e.thunkify=A,e.promisify=k,e.co=O,e.co.wrap=e.wrap=j,e.Completer=z,e.resolved=c,e.rejected=s,e.deferred=function(){var e=new n;return Y(null,{promise:{value:e},resolve:{value:e.resolve},reject:{value:e.reject}})},$||(X.prototype=Y(n.prototype),X.prototype.constructor=n,Q(X,{all:{value:p},race:{value:d},resolve:{value:c},reject:{value:s}}),t.Promise=X)}(hprose,hprose.global),function(e){"use strict";function t(e,t){if(t&&!/^[\x00-\xff]*$/.test(e))throw new Error("argument is not a binary string.");r(this,{length:{value:e.length},toString:{value:function(){return e}},valueOf:{value:function(){return e},writable:!0,configurable:!0,enumerable:!1}})}var r=e.defineProperties,n=e.createObject,i={};["quote","substring","toLowerCase","toUpperCase","charAt","charCodeAt","indexOf","lastIndexOf","include","startsWith","endsWith","repeat","trim","trimLeft","trimRight","toLocaleLowerCase","toLocaleUpperCase","match","search","replace","split","substr","concat","slice"].forEach(function(e){i[e]={value:String.prototype[e]}}),t.prototype=n(null,i),t.prototype.constructor=t,e.BinaryString=t,e.binary=function(e){return new t(e,!0)}}(hprose),function(e,t){"use strict";function r(e){return String.fromCharCode(e>>>24&255,e>>>16&255,e>>>8&255,255&e)}function n(e){return String.fromCharCode(255&e,e>>>8&255,e>>>16&255,e>>>24&255)}function i(e){for(var t=[],r=e.length,n=0,i=0;n<r;++n,++i){var o=e.charCodeAt(n);if(o<128)t[i]=e.charAt(n);else if(o<2048)t[i]=String.fromCharCode(192|o>>6,128|63&o);else{if(!(o<55296||o>57343)){// FIXED: if(n+1<r){var a=e.charCodeAt(n+1);if(o<56320&&56320<=a&&a<=57343){var u=65536+((1023&o)<<10|1023&a);t[i]=String.fromCharCode(240|u>>18&63,128|u>>12&63,128|u>>6&63,128|63&u),++n;continue}}throw new Error("Malformed string")}t[i]=String.fromCharCode(224|o>>12,128|o>>6&63,128|63&o)}}return t.join("")}function o(e,t){for(var r=new Array(t),n=0,i=0,o=e.length;n<t&&i<o;n++){var a=e.charCodeAt(i++);switch(a>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:r[n]=a;break;case 12:case 13:if(i<o){r[n]=(31&a)<<6|63&e.charCodeAt(i++);break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(i+1<o){r[n]=(15&a)<<12|(63&e.charCodeAt(i++))<<6|63&e.charCodeAt(i++);break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(i+2<o){var u=((7&a)<<18|(63&e.charCodeAt(i++))<<12|(63&e.charCodeAt(i++))<<6|63&e.charCodeAt(i++))-65536;if(0<=u&&u<=1048575){r[n++]=u>>10&1023|55296,r[n]=1023&u|56320;break}throw new Error("Character outside valid Unicode range: 0x"+u.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+a.toString(16))}}return n<t&&(r.length=n),[String.fromCharCode.apply(String,r),i]}function a(e,t){for(var r=[],n=new Array(32768),i=0,o=0,a=e.length;i<t&&o<a;i++){var u=e.charCodeAt(o++);switch(u>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n[i]=u;break;case 12:case 13:if(o<a){n[i]=(31&u)<<6|63&e.charCodeAt(o++);break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(o+1<a){n[i]=(15&u)<<12|(63&e.charCodeAt(o++))<<6|63&e.charCodeAt(o++);break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(o+2<a){var s=((7&u)<<18|(63&e.charCodeAt(o++))<<12|(63&e.charCodeAt(o++))<<6|63&e.charCodeAt(o++))-65536;if(0<=s&&s<=1048575){n[i++]=s>>10&1023|55296,n[i]=1023&s|56320;break}throw new Error("Character outside valid Unicode range: 0x"+s.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+u.toString(16))}if(i>=32766){var c=i+1;n.length=c,r[r.length]=String.fromCharCode.apply(String,n),t-=c,i=-1}}return i>0&&(n.length=i,r[r.length]=String.fromCharCode.apply(String,n)),[r.join(""),o]}function u(e,r){return(r===t||null===r||r<0)&&(r=e.length),0===r?["",0]:r<65535?o(e,r):a(e,r)}function s(e,r){if((r===t||null===r||r<0)&&(r=e.length),0===r)return"";for(var n=0,i=0,o=e.length;n<r&&i<o;n++){var a=e.charCodeAt(i++);switch(a>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:break;case 12:case 13:if(i<o){++i;break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(i+1<o){i+=2;break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(i+2<o){var u=((7&a)<<18|(63&e.charCodeAt(i++))<<12|(63&e.charCodeAt(i++))<<6|63&e.charCodeAt(i++))-65536;if(0<=u&&u<=1048575)break;throw new Error("Character outside valid Unicode range: 0x"+u.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+a.toString(16))}}return e.substr(0,i)}function c(e){return u(e)[0]}function f(e){for(var t=e.length,r=0,n=0;n<t;++n){var i=e.charCodeAt(n);if(i<128)++r;else if(i<2048)r+=2;else{if(!(i<55296||i>57343)){if(n+1<t){var o=e.charCodeAt(n+1);if(i<56320&&56320<=o&&o<=57343){++n,r+=4;continue}}throw new Error("Malformed string")}r+=3}}return r}function l(e){for(var t=e.length,r=0,n=0;n<t;++n,++r){var i=e.charCodeAt(n);switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:break;case 12:case 13:if(n<t){++n;break}throw new Error("Unfinished UTF-8 octet sequence");case 14:if(n+1<t){n+=2;break}throw new Error("Unfinished UTF-8 octet sequence");case 15:if(n+2<t){var o=((7&i)<<18|(63&e.charCodeAt(n++))<<12|(63&e.charCodeAt(n++))<<6|63&e.charCodeAt(n++))-65536;if(0<=o&&o<=1048575){++r;break}throw new Error("Character outside valid Unicode range: 0x"+o.toString(16))}throw new Error("Unfinished UTF-8 octet sequence");default:throw new Error("Bad UTF-8 encoding 0x"+i.toString(16))}}return r}function h(e){for(var t=0,r=e.length;t<r;++t){var n=e.charCodeAt(t);switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:break;case 12:case 13:if(t<r){++t;break}return!1;case 14:if(t+1<r){t+=2;break}return!1;case 15:if(t+2<r){var i=((7&n)<<18|(63&e.charCodeAt(t++))<<12|(63&e.charCodeAt(t++))<<6|63&e.charCodeAt(t++))-65536;if(0<=i&&i<=1048575)break}return!1;default:return!1}}return!0}function p(){var e=arguments;switch(e.length){case 1:this._buffer=[e[0].toString()];break;case 2:this._buffer=[e[0].toString().substr(e[1])];break;case 3:this._buffer=[e[0].toString().substr(e[1],e[2])];break;default:this._buffer=[""]}this.mark()}var v=e.defineProperties;v(p.prototype,{_buffer:{writable:!0},_off:{value:0,writable:!0},_wmark:{writable:!0},_rmark:{writable:!0},toString:{value:function(){return this._buffer.length>1&&(this._buffer=[this._buffer.join("")]),this._buffer[0]}},length:{get:function(){return this.toString().length}},position:{get:function(){return this._off}},mark:{value:function(){this._wmark=this.length(),this._rmark=this._off}},reset:{value:function(){this._buffer=[this.toString().substr(0,this._wmark)],this._off=this._rmark}},clear:{value:function(){this._buffer=[""],this._wmark=0,this._off=0,this._rmark=0}},writeByte:{value:function(e){this._buffer.push(String.fromCharCode(255&e))}},writeInt32BE:{value:function(e){if(e===(0|e)&&e<=2147483647)return void this._buffer.push(r(e));throw new TypeError("value is out of bounds")}},writeUInt32BE:{value:function(e){if(2147483648+(2147483647&e)===e&&e>=0)return void this._buffer.push(r(0|e));throw new TypeError("value is out of bounds")}},writeInt32LE:{value:function(e){if(e===(0|e)&&e<=2147483647)return void this._buffer.push(n(e));throw new TypeError("value is out of bounds")}},writeUInt32LE:{value:function(e){if(2147483648+(2147483647&e)===e&&e>=0)return void this._buffer.push(n(0|e));throw new TypeError("value is out of bounds")}},writeUTF16AsUTF8:{value:function(e){this._buffer.push(i(e))}},writeUTF8AsUTF16:{value:function(e){this._buffer.push(c(e))}},write:{value:function(e){this._buffer.push(e)}},readByte:{value:function(){return this._off<this.length()?this._buffer[0].charCodeAt(this._off++):-1}},readChar:{value:function(){return this._off<this.length()?this._buffer[0].charAt(this._off++):""}},readInt32BE:{value:function(){var e=this.length(),t=this._buffer[0],r=this._off;if(r+3<e){var n=t.charCodeAt(r++)<<24|t.charCodeAt(r++)<<16|t.charCodeAt(r++)<<8|t.charCodeAt(r++);return this._off=r,n}throw new Error("EOF")}},readUInt32BE:{value:function(){var e=this.readInt32BE();return e<0?2147483648+(2147483647&e):e}},readInt32LE:{value:function(){var e=this.length(),t=this._buffer[0],r=this._off;if(r+3<e){var n=t.charCodeAt(r++)|t.charCodeAt(r++)<<8|t.charCodeAt(r++)<<16|t.charCodeAt(r++)<<24;return this._off=r,n}throw new Error("EOF")}},readUInt32LE:{value:function(){var e=this.readInt32LE();return e<0?2147483648+(2147483647&e):e}},read:{value:function(e){var t=this._off,r=this.length();return t+e>r&&(e=r-t),0===e?"":(this._off=t+e,this._buffer[0].substring(t,this._off))}},skip:{value:function(e){var t=this.length();return this._off+e>t?(e=t-this._off,this._off=t):this._off+=e,e}},readString:{value:function(e){var t=this.length(),r=this._off,n=this._buffer[0],i=n.indexOf(e,r);return-1===i?(n=n.substr(r),this._off=t):(n=n.substring(r,i+1),this._off=i+1),n}},readUntil:{value:function(e){var t=this.length(),r=this._off,n=this._buffer[0],i=n.indexOf(e,r);return i===this._off?(n="",this._off++):-1===i?(n=n.substr(r),this._off=t):(n=n.substring(r,i),this._off=i+1),n}},readUTF8:{value:function(e){var t=this.length(),r=s(this._buffer[0].substring(this._off,Math.min(this._off+3*e,t)),e);return this._off+=r.length,r}},readUTF8AsUTF16:{value:function(e){var t=this.length(),r=u(this._buffer[0].substring(this._off,Math.min(this._off+3*e,t)),e);return this._off+=r[1],r[0]}},readUTF16AsUTF8:{value:function(e){return i(this.read(e))}},take:{value:function(){var e=this.toString();return this.clear(),e}},clone:{value:function(){return new p(this.toString())}},trunc:{value:function(){var e=this.toString().substring(this._off,this._length);this._buffer[0]=e,this._off=0,this._wmark=0,this._rmark=0}}}),v(p,{utf8Encode:{value:i},utf8Decode:{value:c},utf8Length:{value:f},utf16Length:{value:l},isUTF8:{value:h}}),e.StringIO=p}(hprose),function(e,t){"use strict";t.HproseTags=e.Tags={TagInteger:"i",TagLong:"l",TagDouble:"d",TagNull:"n",TagEmpty:"e",TagTrue:"t",TagFalse:"f",TagNaN:"N",TagInfinity:"I",TagDate:"D",TagTime:"T",TagUTC:"Z",TagBytes:"b",TagUTF8Char:"u",TagString:"s",TagGuid:"g",TagList:"a",TagMap:"m",TagClass:"c",TagObject:"o",TagRef:"r",TagPos:"+",TagNeg:"-",TagSemicolon:";",TagOpenbrace:"{",TagClosebrace:"}",TagQuote:'"',TagPoint:".",TagFunctions:"F",TagCall:"C",TagResult:"R",TagArgument:"A",TagError:"E",TagEnd:"z"}}(hprose,hprose.global),function(e,t){"use strict";function r(e,t){s.set(e,t),u[t]=e}function n(e){return s.get(e)}function i(e){return u[e]}var o=t.WeakMap,a=e.createObject,u=a(null),s=new o;t.HproseClassManager=e.ClassManager=a(null,{register:{value:r},getClassAlias:{value:n},getClass:{value:i}}),e.register=r,r(Object,"Object")}(hprose,hprose.global),function(e,t,r){"use strict";function n(e){var t=e.constructor;if(!t)return"Object";var r=S.getClassAlias(t);if(r)return r;if(t.name)r=t.name;else{var n=t.toString();if(""===(r=n.substr(0,n.indexOf("(")).replace(/(^\s*function\s*)|(\s*$)/gi,""))||"Object"===r)return"function"==typeof e.getClassName?e.getClassName():"Object"}return"Object"!==r&&S.register(t,r),r}function i(e){O(this,{_stream:{value:e},_ref:{value:new C,writable:!0}})}function o(e){return new i(e)}function a(e,t,r){this.binary=!!r,O(this,{stream:{value:e},_classref:{value:j(null),writable:!0},_fieldsref:{value:[],writable:!0},_refer:{value:t?_:o(e)}})}function u(e,t){var i=e.stream;if(t===r||null===t||t.constructor===Function)return void i.write(k.TagNull);if(""===t)return void i.write(k.TagEmpty);switch(t.constructor){case Number:s(e,t);break;case Boolean:l(e,t);break;case String:1===t.length?(i.write(k.TagUTF8Char),i.write(e.binary?I(t):t)):e.writeStringWithRef(t);break;case A:if(!e.binary)throw new Error("The binary string does not support serialization in text mode.");e.writeBinaryWithRef(t);break;case Date:e.writeDateWithRef(t);break;case C:e.writeMapWithRef(t);break;default:if(Array.isArray(t))e.writeListWithRef(t);else{"Object"===n(t)?e.writeMapWithRef(t):e.writeObjectWithRef(t)}}}function s(e,t){var r=e.stream;t=t.valueOf(),t===(0|t)?0<=t&&t<=9?r.write(t):(r.write(k.TagInteger),r.write(t),r.write(k.TagSemicolon)):f(e,t)}function c(e,t){var r=e.stream;0<=t&&t<=9?r.write(t):(t<-2147483648||t>2147483647?r.write(k.TagLong):r.write(k.TagInteger),r.write(t),r.write(k.TagSemicolon))}function f(e,t){var r=e.stream;t!==t?r.write(k.TagNaN):t!==Infinity&&t!==-Infinity?(r.write(k.TagDouble),r.write(t),r.write(k.TagSemicolon)):(r.write(k.TagInfinity),r.write(t>0?k.TagPos:k.TagNeg))}function l(e,t){e.stream.write(t.valueOf()?k.TagTrue:k.TagFalse)}function h(e,t){e._refer.set(t);var r=e.stream;r.write(k.TagDate),r.write(("0000"+t.getUTCFullYear()).slice(-4)),r.write(("00"+(t.getUTCMonth()+1)).slice(-2)),r.write(("00"+t.getUTCDate()).slice(-2)),r.write(k.TagTime),r.write(("00"+t.getUTCHours()).slice(-2)),r.write(("00"+t.getUTCMinutes()).slice(-2)),r.write(("00"+t.getUTCSeconds()).slice(-2));var n=t.getUTCMilliseconds();0!==n&&(r.write(k.TagPoint),r.write(("000"+n).slice(-3))),r.write(k.TagUTC)}function p(e,t){e._refer.set(t);var r=e.stream,n=("0000"+t.getFullYear()).slice(-4),i=("00"+(t.getMonth()+1)).slice(-2),o=("00"+t.getDate()).slice(-2),a=("00"+t.getHours()).slice(-2),u=("00"+t.getMinutes()).slice(-2),s=("00"+t.getSeconds()).slice(-2),c=("000"+t.getMilliseconds()).slice(-3);"00"===a&&"00"===u&&"00"===s&&"000"===c?(r.write(k.TagDate),r.write(n),r.write(i),r.write(o)):"1970"===n&&"01"===i&&"01"===o?(r.write(k.TagTime),r.write(a),r.write(u),r.write(s),"000"!==c&&(r.write(k.TagPoint),r.write(c))):(r.write(k.TagDate),r.write(n),r.write(i),r.write(o),r.write(k.TagTime),r.write(a),r.write(u),r.write(s),"000"!==c&&(r.write(k.TagPoint),r.write(c))),r.write(k.TagSemicolon)}function v(e,t){e._refer.set(t);var r=e.stream,n=("00"+t.getHours()).slice(-2),i=("00"+t.getMinutes()).slice(-2),o=("00"+t.getSeconds()).slice(-2),a=("000"+t.getMilliseconds()).slice(-3);r.write(k.TagTime),r.write(n),r.write(i),r.write(o),"000"!==a&&(r.write(k.TagPoint),r.write(a)),r.write(k.TagSemicolon)}function d(e,t){e._refer.set(t);var r=e.stream;r.write(k.TagBytes);var n=t.length;n>0?(r.write(n),r.write(k.TagQuote),r.write(t)):r.write(k.TagQuote),r.write(k.TagQuote)}function g(e,t){e._refer.set(t);var r=e.stream,n=t.length;r.write(k.TagString),n>0?(r.write(n),r.write(k.TagQuote),r.write(e.binary?I(t):t)):r.write(k.TagQuote),r.write(k.TagQuote)}function w(e,t){e._refer.set(t);var r=e.stream,n=t.length;if(r.write(k.TagList),n>0){r.write(n),r.write(k.TagOpenbrace);for(var i=0;i<n;i++)u(e,t[i])}else r.write(k.TagOpenbrace);r.write(k.TagClosebrace)}function y(e,t){e._refer.set(t);var r=e.stream,n=[];for(var i in t)t.hasOwnProperty(i)&&"function"!=typeof t[i]&&(n[n.length]=i);var o=n.length;if(r.write(k.TagMap),o>0){r.write(o),r.write(k.TagOpenbrace);for(var a=0;a<o;a++)u(e,n[a]),u(e,t[n[a]])}else r.write(k.TagOpenbrace);r.write(k.TagClosebrace)}function m(e,t){e._refer.set(t);var r=e.stream,n=t.size;r.write(k.TagMap),n>0?(r.write(n),r.write(k.TagOpenbrace),t.forEach(function(t,r){u(e,r),u(e,t)})):r.write(k.TagOpenbrace),r.write(k.TagClosebrace)}function b(e,t){var r,i,o=e.stream,a=n(t);if(a in e._classref)i=e._classref[a],r=e._fieldsref[i];else{r=[];for(var s in t)t.hasOwnProperty(s)&&"function"!=typeof t[s]&&(r[r.length]=s.toString());i=T(e,a,r)}o.write(k.TagObject),o.write(i),o.write(k.TagOpenbrace),e._refer.set(t);for(var c=r.length,f=0;f<c;f++)u(e,t[r[f]]);o.write(k.TagClosebrace)}function T(e,t,r){var n=e.stream,i=r.length;if(n.write(k.TagClass),n.write(t.length),n.write(k.TagQuote),n.write(e.binary?I(t):t),n.write(k.TagQuote),i>0){n.write(i),n.write(k.TagOpenbrace);for(var o=0;o<i;o++)g(e,r[o])}else n.write(k.TagOpenbrace);n.write(k.TagClosebrace);var a=e._fieldsref.length;return e._classref[t]=a,e._fieldsref[a]=r,a}var C=t.Map,E=e.StringIO,A=e.BinaryString,k=e.Tags,S=e.ClassManager,O=e.defineProperties,j=e.createObject,I=E.utf8Encode,_=j(null,{set:{value:function(){}},write:{value:function(){return!1}},reset:{value:function(){}}});O(i.prototype,{_refcount:{value:0,writable:!0},set:{value:function(e){this._ref.set(e,this._refcount++)}},write:{value:function(e){var t=this._ref.get(e);return t!==r&&(this._stream.write(k.TagRef),this._stream.write(t),this._stream.write(k.TagSemicolon),!0)}},reset:{value:function(){this._ref=new C,this._refcount=0}}}),O(a.prototype,{binary:{value:!1,writable:!0},serialize:{value:function(e){u(this,e)}},writeInteger:{value:function(e){c(this,e)}},writeDouble:{value:function(e){f(this,e)}},writeBoolean:{value:function(e){l(this,e)}},writeUTCDate:{value:function(e){h(this,e)}},writeUTCDateWithRef:{value:function(e){this._refer.write(e)||h(this,e)}},writeDate:{value:function(e){p(this,e)}},writeDateWithRef:{value:function(e){this._refer.write(e)||p(this,e)}},writeTime:{value:function(e){v(this,e)}},writeTimeWithRef:{value:function(e){this._refer.write(e)||v(this,e)}},writeBinary:{value:function(e){d(this,e)}},writeBinaryWithRef:{value:function(e){this._refer.write(e)||d(this,e)}},writeString:{value:function(e){g(this,e)}},writeStringWithRef:{value:function(e){this._refer.write(e)||g(this,e)}},writeList:{value:function(e){w(this,e)}},writeListWithRef:{value:function(e){this._refer.write(e)||w(this,e)}},writeMap:{value:function(e){e instanceof C?m(this,e):y(this,e)}},writeMapWithRef:{value:function(e){this._refer.write(e)||this.writeMap(e)}},writeObject:{value:function(e){b(this,e)}},writeObjectWithRef:{value:function(e){this._refer.write(e)||b(this,e)}},reset:{value:function(){this._classref=j(null),this._fieldsref.length=0,this._refer.reset()}}}),t.HproseWriter=e.Writer=a}(hprose,hprose.global),function(e,t,r){"use strict";function n(e,t){if(e&&t)throw new Error('Tag "'+t+'" expected, but "'+e+'" found in stream');if(e)throw new Error('Unexpected serialize tag "'+e+'" in stream');throw new Error("No byte found in stream")}function i(e,t){var r=new ee;return o(e,r,t),r.take()}function o(e,t,r){a(e,t,e.readChar(),r)}function a(e,t,r,i){switch(t.write(r),r){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case re.TagNull:case re.TagEmpty:case re.TagTrue:case re.TagFalse:case re.TagNaN:break;case re.TagInfinity:t.write(e.read());break;case re.TagInteger:case re.TagLong:case re.TagDouble:case re.TagRef:u(e,t);break;case re.TagDate:case re.TagTime:s(e,t);break;case re.TagUTF8Char:c(e,t,i);break;case re.TagBytes:f(e,t,i);break;case re.TagString:l(e,t,i);break;case re.TagGuid:h(e,t);break;case re.TagList:case re.TagMap:case re.TagObject:p(e,t,i);break;case re.TagClass:p(e,t,i),o(e,t,i);break;case re.TagError:o(e,t,i);break;default:n(r)}}function u(e,t){var r;do{r=e.read(),t.write(r)}while(r!==re.TagSemicolon)}function s(e,t){var r;do{r=e.read(),t.write(r)}while(r!==re.TagSemicolon&&r!==re.TagUTC)}function c(e,t,r){r?t.write(e.readUTF8(1)):t.write(e.readChar())}function f(e,t,r){if(!r)throw new Error("The binary string does not support to unserialize in text mode.");var n=e.readUntil(re.TagQuote);t.write(n),t.write(re.TagQuote);var i=0;n.length>0&&(i=parseInt(n,10)),t.write(e.read(i+1))}function l(e,t,r){var n=e.readUntil(re.TagQuote);t.write(n),t.write(re.TagQuote);var i=0;n.length>0&&(i=parseInt(n,10)),r?t.write(e.readUTF8(i+1)):t.write(e.read(i+1))}function h(e,t){t.write(e.read(38))}function p(e,t,r){var n;do{n=e.readChar(),t.write(n)}while(n!==re.TagOpenbrace);for(;(n=e.readChar())!==re.TagClosebrace;)a(e,t,n,r);t.write(n)}function v(e,t){ie(this,{stream:{value:e},binary:{value:!!t,writable:!0},readRaw:{value:function(){return i(e,this.binary)}}})}function d(){ie(this,{ref:{value:[]}})}function g(){return new d}function w(e){var n,i=t,o=e.split(".");for(n=0;n<o.length;n++)if((i=i[o[n]])===r)return null;return i}function y(e,t,r,n){if(r<t.length){e[t[r]]=n;var i=y(e,t,r+1,".");return r+1<t.length&&null===i&&(i=y(e,t,r+1,"_")),i}var o=e.join("");try{var a=w(o);return"function"==typeof a?a:null}catch(u){return null}}function m(e){var t=ne.getClass(e);if(t)return t;if("function"==typeof(t=w(e)))return ne.register(t,e),t;for(var r=[],n=e.indexOf("_");n>=0;)r[r.length]=n,n=e.indexOf("_",n+1);if(r.length>0){var i=e.split("");if(t=y(i,r,0,"."),null===t&&(t=y(i,r,0,"_")),"function"==typeof t)return ne.register(t,e),t}return t=function(){},ie(t.prototype,{getClassName:{value:function(){return e}}}),ne.register(t,e),t}function b(e,t){var r=e.readUntil(t);return 0===r.length?0:parseInt(r,10)}function T(e){var t=e.stream,r=t.readChar();switch(r){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:return C(t);case re.TagLong:return A(t);case re.TagDouble:return S(t);case re.TagNull:return null;case re.TagEmpty:return"";case re.TagTrue:return!0;case re.TagFalse:return!1;case re.TagNaN:return NaN;case re.TagInfinity:return j(t);case re.TagDate:return _(e);case re.TagTime:return M(e);case re.TagBytes:return U(e);case re.TagUTF8Char:return F(e);case re.TagString:return N(e);case re.TagGuid:return D(e);case re.TagList:return B(e);case re.TagMap:return e.useHarmonyMap?G(e):z(e);case re.TagClass:return J(e),$(e);case re.TagObject:return Y(e);case re.TagRef:return V(e);case re.TagError:throw new Error(H(e));default:n(r)}}function C(e){return b(e,re.TagSemicolon)}function E(e){var t=e.readChar();switch(t){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:return C(e);default:n(t)}}function A(e){var t=e.readUntil(re.TagSemicolon),r=parseInt(t,10);return r.toString()===t?r:t}function k(e){var t=e.readChar();switch(t){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:case re.TagLong:return A(e);default:n(t)}}function S(e){return parseFloat(e.readUntil(re.TagSemicolon))}function O(e){var t=e.readChar();switch(t){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case re.TagInteger:case re.TagLong:case re.TagDouble:return S(e);case re.TagNaN:return NaN;case re.TagInfinity:return j(e);default:n(t)}}function j(e){return e.readChar()===re.TagNeg?-Infinity:Infinity}function I(e){var t=e.readChar();switch(t){case re.TagTrue:return!0;case re.TagFalse:return!1;default:n(t)}}function _(e){var t,r=e.stream,n=parseInt(r.read(4),10),i=parseInt(r.read(2),10)-1,o=parseInt(r.read(2),10),a=r.readChar();if(a===re.TagTime){var u=parseInt(r.read(2),10),s=parseInt(r.read(2),10),c=parseInt(r.read(2),10),f=0;a=r.readChar(),a===re.TagPoint&&(f=parseInt(r.read(3),10),(a=r.readChar())>="0"&&a<="9"&&(r.skip(2),(a=r.readChar())>="0"&&a<="9"&&(r.skip(2),a=r.readChar()))),t=a===re.TagUTC?new Date(Date.UTC(n,i,o,u,s,c,f)):new Date(n,i,o,u,s,c,f)}else t=a===re.TagUTC?new Date(Date.UTC(n,i,o)):new Date(n,i,o);return e.refer.set(t),t}function x(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagDate:return _(e);case re.TagRef:return V(e);default:n(t)}}function M(e){var t,r=e.stream,n=parseInt(r.read(2),10),i=parseInt(r.read(2),10),o=parseInt(r.read(2),10),a=0,u=r.readChar();return u===re.TagPoint&&(a=parseInt(r.read(3),10),(u=r.readChar())>="0"&&u<="9"&&(r.skip(2),(u=r.readChar())>="0"&&u<="9"&&(r.skip(2),u=r.readChar()))),t=u===re.TagUTC?new Date(Date.UTC(1970,0,1,n,i,o,a)):new Date(1970,0,1,n,i,o,a),e.refer.set(t),t}function R(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagTime:return M(e);case re.TagRef:return V(e);default:n(t)}}function U(e){if(!e.binary)throw new Error("The binary string does not support to unserialize in text mode.");var t=e.stream,r=b(t,re.TagQuote),n=new te(t.read(r));return t.skip(1),e.refer.set(n),n}function L(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagEmpty:return new te("");case re.TagBytes:return U(e);case re.TagRef:return V(e);default:n(t)}}function F(e){return e.binary?e.stream.readUTF8AsUTF16(1):e.stream.read(1)}function P(e){var t,r=e.stream,n=b(r,re.TagQuote);return t=e.binary?r.readUTF8AsUTF16(n):r.read(n),r.skip(1),t}function N(e){var t=P(e);return e.refer.set(t),t}function H(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagEmpty:return"";case re.TagUTF8Char:return F(e);case re.TagString:return N(e);case re.TagRef:return V(e);default:n(t)}}function D(e){var t=e.stream;t.skip(1);var r=t.read(36);return t.skip(1),e.refer.set(r),r}function W(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagGuid:return D(e);case re.TagRef:return V(e);default:n(t)}}function B(e){var t=e.stream,r=[];e.refer.set(r);for(var n=b(t,re.TagOpenbrace),i=0;i<n;i++)r[i]=T(e);return t.skip(1),r}function q(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagList:return B(e);case re.TagRef:return V(e);default:n(t)}}function z(e){var t=e.stream,r={};e.refer.set(r);for(var n=b(t,re.TagOpenbrace),i=0;i<n;i++){var o=T(e),a=T(e);r[o]=a}return t.skip(1),r}function X(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagMap:return z(e);case re.TagRef:return V(e);default:n(t)}}function G(e){var t=e.stream,r=new Z;e.refer.set(r);for(var n=b(t,re.TagOpenbrace),i=0;i<n;i++){var o=T(e),a=T(e);r.set(o,a)}return t.skip(1),r}function Q(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagMap:return G(e);case re.TagRef:return V(e);default:n(t)}}function Y(e){var t=e.stream,r=e.classref[b(t,re.TagOpenbrace)],n=new r.classname;e.refer.set(n);for(var i=0;i<r.count;i++)n[r.fields[i]]=T(e);return t.skip(1),n}function $(e){var t=e.stream.readChar();switch(t){case re.TagNull:return null;case re.TagClass:return J(e),$(e);case re.TagObject:return Y(e);case re.TagRef:return V(e);default:n(t)}}function J(e){for(var t=e.stream,r=P(e),n=b(t,re.TagOpenbrace),i=[],o=0;o<n;o++)i[o]=H(e);t.skip(1),r=m(r),e.classref.push({classname:r,count:n,fields:i})}function V(e){return e.refer.read(b(e.stream,re.TagSemicolon))}function K(e,t,r,n){v.call(this,e,n),this.useHarmonyMap=!!r,ie(this,{classref:{value:[]},refer:{value:t?ae:g()}})}var Z=t.Map,ee=e.StringIO,te=e.BinaryString,re=e.Tags,ne=e.ClassManager,ie=e.defineProperties,oe=e.createObject;e.RawReader=v;var ae=oe(null,{set:{value:function(){}},read:{value:function(){n(re.TagRef)}},reset:{value:function(){}}});ie(d.prototype,{set:{value:function(e){this.ref.push(e)}},read:{value:function(e){return this.ref[e]}},reset:{value:function(){this.ref.length=0}}}),K.prototype=oe(v.prototype),K.prototype.constructor=K,ie(K.prototype,{useHarmonyMap:{value:!1,writable:!0},checkTag:{value:function(e,t){t===r&&(t=this.stream.readChar()),t!==e&&n(t,e)}},checkTags:{value:function(e,t){if(t===r&&(t=this.stream.readChar()),e.indexOf(t)>=0)return t;n(t,e)}},unserialize:{value:function(){return T(this)}},readInteger:{value:function(){return E(this.stream)}},readLong:{value:function(){return k(this.stream)}},readDouble:{value:function(){return O(this.stream)}},readBoolean:{value:function(){return I(this.stream)}},readDateWithoutTag:{value:function(){return _(this)}},readDate:{value:function(){return x(this)}},readTimeWithoutTag:{value:function(){return M(this)}},readTime:{value:function(){return R(this)}},readBinaryWithoutTag:{value:function(){return U(this)}},readBinary:{value:function(){return L(this)}},readStringWithoutTag:{value:function(){return N(this)}},readString:{value:function(){return H(this)}},readGuidWithoutTag:{value:function(){return D(this)}},readGuid:{value:function(){return W(this)}},readListWithoutTag:{value:function(){return B(this)}},readList:{value:function(){return q(this)}},readMapWithoutTag:{value:function(){return this.useHarmonyMap?G(this):z(this)}},readMap:{value:function(){return this.useHarmonyMap?Q(this):X(this)}},readObjectWithoutTag:{value:function(){return Y(this)}},readObject:{value:function(){return $(this)}},reset:{value:function(){this.classref.length=0,this.refer.reset()}}}),t.HproseReader=e.Reader=K}(hprose,hprose.global),function(e){"use strict";function t(e,t,r){var o=new n;return new i(o,t,r).serialize(e),o.take()}function r(e,t,r,i){return e instanceof n||(e=new n(e)),new o(e,t,r,i).unserialize()}var n=e.StringIO,i=e.Writer,o=e.Reader,a=e.createObject;e.Formatter=a(null,{serialize:{value:t},unserialize:{value:r}}),e.serialize=t,e.unserialize=r}(hprose),function(e,t){"use strict";t.HproseResultMode=e.ResultMode={Normal:0,Serialized:1,Raw:2,RawWithEndTag:3},e.Normal=e.ResultMode.Normal,e.Serialized=e.ResultMode.Serialized,e.Raw=e.ResultMode.Raw,e.RawWithEndTag=e.ResultMode.RawWithEndTag}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e,t,i){function o(e,t){for(var r=0,n=Ve.length;r<n;r++)e=Ve[r].outputFilter(e,t);return e}function a(e,t){for(var r=Ve.length-1;r>=0;r--)e=Ve[r].inputFilter(e,t);return e}function g(e,t){return e=o(e,t),ut(e,t).then(function(e){if(!t.oneway)return a(e,t)})}function A(e,t){return ht.sendAndReceive(e,t).catchError(function(r){var n=O(e,t);if(null!==n)return n;throw r})}function k(e,t,r,n){at(e,t).then(r,n)}function S(){var e=Ne.length;if(e>1){var t=He+1;t>=e&&(t=0,Qe++),He=t,Pe=Ne[He]}else Qe++;typeof ht.onfailswitch===C&&ht.onfailswitch(ht)}function O(e,t){if(t.failswitch&&S(),t.idempotent&&t.retried<t.retry){var r=500*++t.retried;return t.failswitch&&(r-=500*(Ne.length-1)),r>5e3&&(r=5e3),r>0?p.delayed(r,function(){return A(e,t)}):A(e,t)}return null}function j(e){var t=[d(null)];for(var n in e){var i=e[n].split("_"),o=i.length-1;if(o>0){for(var a=t,u=0;u<o;u++){var s=i[u];a[0][s]===r&&(a[0][s]=[d(null)]),a=a[0][s]}a.push(i[o])}t.push(e[n])}return t}function I(e){k(y,{retry:ze,retried:0,idempotent:!0,failswitch:!0,timeout:qe,client:ht,userdata:{}},function(t){var r=null;try{var n=new f(t),i=new h(n,!0);switch(n.readChar()){case s.TagError:r=new Error(i.readString());break;case s.TagFunctions:var o=j(i.readList());i.checkTag(s.TagEnd),M(e,o);break;default:r=new Error("Wrong Response:\r\n"+t)}}catch(a){r=a}null!==r?et.reject(r):et.resolve(e)},et.reject)}function _(e,t){return function(){return Ke?N(e,t,Array.slice(arguments),!0):p.all(arguments).then(function(r){return N(e,t,r,!1)})}}function x(e,t,n,i,o){if(t[i]===r&&(t[i]={},typeof o!==b&&o.constructor!==Object||(o=[o]),Array.isArray(o)))for(var a=0;a<o.length;a++){var u=o[a];if(typeof u===b)t[i][u]=_(e,n+i+"_"+u);else for(var s in u)x(e,t[i],n+i+"_",s,u[s])}}function M(e,t){for(var n=0;n<t.length;n++){var i=t[n];if(typeof i===b)e[i]===r&&(e[i]=_(e,i));else for(var o in i)x(e,e,"",o,i[o])}}function R(e,t){for(var r=Math.min(e.length,t.length),n=0;n<r;++n)t[n]=e[n]}function U(e){return e?{mode:c.Normal,binary:De,byref:We,simple:Be,onsuccess:r,onerror:r,useHarmonyMap:Je,client:ht,userdata:{}}:{mode:c.Normal,binary:De,byref:We,simple:Be,timeout:qe,retry:ze,retried:0,idempotent:Xe,failswitch:Ge,oneway:!1,sync:!1,onsuccess:r,onerror:r,useHarmonyMap:Je,client:ht,userdata:{}}}function L(e,t,r,n){var i=U(n);if(t in e){var o=e[t];for(var a in o)a in i&&(i[a]=o[a])}for(var u=0,s=r.length;u<s&&typeof r[u]!==C;++u);if(u===s)return i;var c=r.splice(u,s-u);for(i.onsuccess=c[0],s=c.length,u=1;u<s;++u){var f=c[u];switch(typeof f){case C:i.onerror=f;break;case m:i.byref=f;break;case T:i.mode=f;break;case E:for(var l in f)l in i&&(i[l]=f[l])}}return i}function F(e,t,r){var n=new f;n.write(s.TagCall);var i=new l(n,r.simple,r.binary);return i.writeString(e),(t.length>0||r.byref)&&(i.reset(),i.writeList(t),r.byref&&i.writeBoolean(!0)),n}function P(e,t,r,n){return Ye?p.promise(function(i,o){$e.push({batch:n,name:e,args:t,context:r,resolve:i,reject:o})}):n?q(e,t,r):B(e,t,r)}function N(e,t,r,n){return P(t,r,L(e,t,r,n),n)}function H(e,t,r,n){try{r.onerror?r.onerror(e,t):ht.onerror&&ht.onerror(e,t),n(t)}catch(i){n(i)}}function D(e,t,r){var n=F(e,t,r);return n.write(s.TagEnd),p.promise(function(e,i){k(n.toString(),r,function(n){if(r.oneway)return void e();var o=null,a=null;try{if(r.mode===c.RawWithEndTag)o=n;else if(r.mode===c.Raw)o=n.substring(0,n.length-1);else{var u=new f(n),l=new h(u,!1,r.useHarmonyMap,r.binary),p=u.readChar();if(p===s.TagResult){if(o=r.mode===c.Serialized?l.readRaw():l.unserialize(),(p=u.readChar())===s.TagArgument){l.reset();var v=l.readList();R(v,t),p=u.readChar()}}else p===s.TagError&&(a=new Error(l.readString()),p=u.readChar());p!==s.TagEnd&&(a=new Error("Wrong Response:\r\n"+n))}}catch(d){a=d}a?i(a):e(o)},i)})}function W(e){return function(){e&&(Ye=!1,u(function(e){e.forEach(function(e){"settings"in e?Q(e.settings).then(e.resolve,e.reject):P(e.name,e.args,e.context,e.batch).then(e.resolve,e.reject)})},$e),$e=[])}}function B(e,t,r){r.sync&&(Ye=!0);var n=p.promise(function(n,i){it(e,t,r).then(function(o){try{if(r.onsuccess)try{r.onsuccess(o,t)}catch(a){r.onerror&&r.onerror(e,a),i(a)}n(o)}catch(a){i(a)}},function(t){H(e,t,r,i)})});return n.whenComplete(W(r.sync)),n}function q(e,t,r){return p.promise(function(n,i){Ze.push({args:t,name:e,context:r,resolve:n,reject:i})})}function z(e){var t={timeout:qe,binary:De,retry:ze,retried:0,idempotent:Xe,failswitch:Ge,oneway:!1,sync:!1,client:ht,userdata:{}};for(var r in e)r in t&&(t[r]=e[r]);return t}function X(e,t){var r=e.reduce(function(e,r){return r.context.binary=t.binary,e.write(F(r.name,r.args,r.context)),e},new f);return r.write(s.TagEnd),p.promise(function(n,i){k(r.toString(),t,function(r){if(t.oneway)return void n(e);var o=-1,a=new f(r),u=new h(a,!1,!1,t.binary),l=a.readChar();try{for(;l!==s.TagEnd;){var p=null,v=null,d=e[++o].context.mode;if(d>=c.Raw&&(p=new f),l===s.TagResult){if(d===c.Serialized?p=u.readRaw():d>=c.Raw?(p.write(s.TagResult),p.write(u.readRaw())):(u.useHarmonyMap=e[o].context.useHarmonyMap,u.reset(),p=u.unserialize()),(l=a.readChar())===s.TagArgument){if(d>=c.Raw)p.write(s.TagArgument),p.write(u.readRaw());else{u.reset();var g=u.readList();R(g,e[o].args)}l=a.readChar()}}else l===s.TagError&&(d>=c.Raw?(p.write(s.TagError),p.write(u.readRaw())):(u.reset(),v=new Error(u.readString())),l=a.readChar());if([s.TagEnd,s.TagResult,s.TagError].indexOf(l)<0)return void i(new Error("Wrong Response:\r\n"+r));d>=c.Raw?(d===c.RawWithEndTag&&p.write(s.TagEnd),e[o].result=p.toString()):e[o].result=p,e[o].error=v}}catch(w){return void i(w)}n(e)},i)})}function G(){Ke=!0}function Q(e){if(e=e||{},Ke=!1,Ye)return p.promise(function(t,r){$e.push({batch:!0,settings:e,resolve:t,reject:r})});if(0===Ze.length)return p.value([]);var t=z(e);t.sync&&(Ye=!0);var r=Ze;Ze=[];var n=p.promise(function(e,n){ot(r,t).then(function(t){t.forEach(function(e){if(e.error)H(e.name,e.error,e.context,e.reject);else try{if(e.context.onsuccess)try{e.context.onsuccess(e.result,e.args)}catch(t){e.context.onerror&&e.context.onerror(e.name,t),e.reject(t)}e.resolve(e.result)}catch(t){e.reject(t)}delete e.context,delete e.resolve,delete e.reject}),e(t)},function(e){r.forEach(function(t){"reject"in t&&H(t.name,e,t.context,t.reject)}),n(e)})});return n.whenComplete(W(t.sync)),n}function Y(){return Pe}function $(){return Ne}function J(e){if(typeof e===b)Ne=[e];else{if(!Array.isArray(e))return;Ne=e.slice(0),Ne.sort(function(){return Math.random()-.5})}He=0,Pe=Ne[He]}function V(){return De}function K(e){De=!!e}function Z(){return Ge}function ee(e){Ge=!!e}function te(){return Qe}function re(){return qe}function ne(e){qe="number"==typeof e?0|e:0}function ie(){return ze}function oe(e){ze="number"==typeof e?0|e:0}function ae(){return Xe}function ue(e){Xe=!!e}function se(e){nt=!!e}function ce(){return nt}function fe(){return We}function le(e){We=!!e}function he(){return Be}function pe(e){Be=!!e}function ve(){return Je}function de(e){Je=!!e}function ge(){return 0===Ve.length?null:1===Ve.length?Ve[0]:Ve.slice()}function we(e){Ve.length=0,Array.isArray(e)?e.forEach(function(e){ye(e)}):ye(e)}function ye(e){e&&"function"==typeof e.inputFilter&&"function"==typeof e.outputFilter&&Ve.push(e)}function me(e){var t=Ve.indexOf(e);return-1!==t&&(Ve.splice(t,1),!0)}function be(){return Ve}function Te(e,t,n){n===r&&(typeof t===m&&(n=t,t=!1),t||(typeof e===m?(n=e,e=!1):(e&&e.constructor===Object||Array.isArray(e))&&(t=e,e=!1)));var i=ht;return n&&(i={}),e||Pe?(e&&(Pe=e),(typeof t===b||t&&t.constructor===Object)&&(t=[t]),Array.isArray(t)?(M(i,t),et.resolve(i),i):(u(I,i),et)):new Error("You should set server uri first!")}function Ce(e,t,r){var i=arguments.length;if(i<1||typeof e!==b)throw new Error("name must be a string");if(1===i&&(t=[]),2===i&&!Array.isArray(t)){var o=[];typeof t!==C&&o.push(n),o.push(t),t=o}if(i>2){typeof r!==C&&t.push(n);for(var a=2;a<i;a++)t.push(arguments[a])}return N(ht,e,t,Ke)}function Ee(e,t){return et.then(e,t)}function Ae(e,t){if(tt[e]){var r=tt[e];if(r[t])return r[t]}return null}function ke(e,t,n,i,o){if(typeof e!==b)throw new TypeError("topic name must be a string.");if(t===r||null===t){if(typeof n!==C)throw new TypeError("callback must be a function.");t=n}if(tt[e]||(tt[e]=d(null)),typeof t===C)return i=n,n=t,void xe().then(function(t){ke(e,t,n,i,o)});if(typeof n!==C)throw new TypeError("callback must be a function.");if(p.isPromise(t))return void t.then(function(t){ke(e,t,n,i,o)});i===r&&(i=3e5);var a=Ae(e,t);if(null===a){var u=function(){N(ht,e,[t,a.handler,u,{idempotent:!0,failswitch:o,timeout:i}],!1)};a={handler:function(r){var n=Ae(e,t);if(n){if(null!==r)for(var i=n.callbacks,o=0,a=i.length;o<a;++o)try{i[o](r)}catch(s){}null!==Ae(e,t)&&u()}},callbacks:[n]},tt[e][t]=a,u()}else a.callbacks.indexOf(n)<0&&a.callbacks.push(n)}function Se(e,t,r){if(e)if(typeof r===C){var n=e[t];if(n){var i=n.callbacks,o=i.indexOf(r);o>=0&&(i[o]=i[i.length-1],i.length--),0===i.length&&delete e[t]}}else delete e[t]}function Oe(e,t,n){if(typeof e!==b)throw new TypeError("topic name must be a string.");if(t===r||null===t){if(typeof n!==C)return void delete tt[e];t=n}if(typeof t===C&&(n=t,t=null),null===t)if(null===rt){if(tt[e]){var i=tt[e];for(t in i)Se(i,t,n)}}else rt.then(function(t){Oe(e,t,n)});else p.isPromise(t)?t.then(function(t){Oe(e,t,n)}):Se(tt[e],t,n);w(tt[e])&&delete tt[e]}function je(e){return!!tt[e]}function Ie(){var e=[];for(var t in tt)e.push(t);return e}function _e(){return rt}function xe(){return null===rt&&(rt=N(ht,"#",[],!1)),rt}function Me(e){st.push(e),it=st.reduceRight(function(e,t){return function(r,n,i){return p.toPromise(t(r,n,i,e))}},D)}function Re(e){ct.push(e),ot=ct.reduceRight(function(e,t){return function(r,n){return p.toPromise(t(r,n,e))}},X)}function Ue(e){ft.push(e),at=ft.reduceRight(function(e,t){return function(r,n){return p.toPromise(t(r,n,e))}},g)}function Le(e){lt.push(e),ut=lt.reduceRight(function(e,t){return function(r,n){return p.toPromise(t(r,n,e))}},A)}function Fe(e){return Me(e),ht}var Pe,Ne=[],He=-1,De=!1,We=!1,Be=!1,qe=3e4,ze=10,Xe=!1,Ge=!1,Qe=0,Ye=!1,$e=[],Je=!1,Ve=[],Ke=!1,Ze=[],et=new p,tt=d(null),rt=null,nt=!0,it=D,ot=X,at=g,ut=A,st=[],ct=[],ft=[],lt=[],ht=this;xe.sync=!0,xe.idempotent=!0,xe.failswitch=!0;var pt=d(null,{begin:{value:G},end:{value:Q},use:{value:function(e){return Re(e),pt}}}),vt=d(null,{use:{value:function(e){return Ue(e),vt}}}),dt=d(null,{use:{value:function(e){return Le(e),dt}}});v(this,{"#":{value:xe},onerror:{value:null,writable:!0},onfailswitch:{value:null,writable:!0},uri:{get:Y},uriList:{get:$,set:J},id:{get:_e},binary:{get:V,set:K},failswitch:{get:Z,set:ee},failround:{get:te},timeout:{get:re,set:ne},retry:{get:ie,set:oe},idempotent:{get:ae,set:ue},keepAlive:{get:ce,set:se},byref:{get:fe,set:le},simple:{get:he,set:pe},useHarmonyMap:{get:ve,set:de},filter:{get:ge,set:we},addFilter:{value:ye},removeFilter:{value:me},filters:{get:be},useService:{value:Te},invoke:{value:Ce},ready:{value:Ee},subscribe:{value:ke},unsubscribe:{value:Oe},isSubscribed:{value:je},subscribedList:{value:Ie},use:{value:Fe},batch:{value:pt},beforeFilter:{value:vt},afterFilter:{value:dt}}),i&&typeof i===E&&["failswitch","timeout","retry","idempotent","keepAlive","byref","simple","useHarmonyMap","filter","binary"].forEach(function(e){e in i&&ht[e](i[e])}),e&&(J(e),Te(t))}function o(e){var t=g(e),r=t.protocol;if("http:"!==r&&"https:"!==r&&"tcp:"!==r&&"tcp4:"!==r&&"tcp6:"!==r&&"tcps:"!==r&&"tcp4s:"!==r&&"tcp6s:"!==r&&"tls:"!==r&&"ws:"!==r&&"wss:"!==r)throw new Error("The "+r+" client isn't implemented.")}function a(t,r,n){try{return e.HttpClient.create(t,r,n)}catch(i){}try{return e.TcpClient.create(t,r,n)}catch(i){}try{return e.WebSocketClient.create(t,r,n)}catch(i){}if("string"==typeof t)o(t);else if(Array.isArray(t))throw t.forEach(function(e){o(e)}),new Error("Not support multiple protocol.");throw new Error("You should set server uri first!")}var u=t.setImmediate,s=e.Tags,c=e.ResultMode,f=e.StringIO,l=e.Writer,h=e.Reader,p=e.Future,v=e.defineProperties,d=e.createObject,g=e.parseuri,w=e.isObjectEmpty,y=s.TagEnd,m="boolean",b="string",T="number",C="function",E="object";v(i,{create:{value:a}}),t.HproseClient=e.Client=i}(hprose,hprose.global),function(e){"use strict";function t(){if(!navigator)return 0;var t="application/x-shockwave-flash",r=navigator.plugins,n=navigator.mimeTypes,i=0,o=!1;if(r&&r["Shockwave Flash"])!(i=r["Shockwave Flash"].description)||n&&n[t]&&!n[t].enabledPlugin||(i=i.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),i=parseInt(i.replace(/^(.*)\..*$/,"$1"),10));else if(e.ActiveXObject)try{o=!0;var a=new e.ActiveXObject("ShockwaveFlash.ShockwaveFlash");a&&(i=a.GetVariable("$version"))&&(i=i.split(" ")[1].split(","),i=parseInt(i[0],10))}catch(u){}return i<10?0:o?1:2}function r(){var e=t();if(h=e>0){var r=i.createElement("div");r.style.width=0,r.style.height=0,r.innerHTML=1===e?["<object ",'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ','type="application/x-shockwave-flash" ','width="0" height="0" id="',l,'" name="',l,'">','<param name="movie" value="',a,"FlashHttpRequest.swf?",+new Date,'" />','<param name="allowScriptAccess" value="always" />','<param name="quality" value="high" />','<param name="wmode" value="opaque" />',"</object>"].join(""):'<embed id="'+l+'" src="'+a+"FlashHttpRequest.swf?"+ +new Date+'" type="application/x-shockwave-flash" width="0" height="0" name="'+l+'" allowScriptAccess="always" />',i.documentElement.appendChild(r)}}function n(e,t,r,n,i,o){r=encodeURIComponent(r),y?p.post(e,t,r,n,i,o):g.push(function(){p.post(e,t,r,n,i,o)})}if("undefined"==typeof e.document)return void(e.FlashHttpRequest={flashSupport:function(){return!1}});var i=e.document,o=i.getElementsByTagName("script"),a=o.length>0&&o[o.length-1].getAttribute("flashpath")||e.hproseFlashPath||"";o=null;var u=e.location!==undefined&&"file:"===e.location.protocol,s=e.XMLHttpRequest,c=void 0!==s,f=!u&&c&&"withCredentials"in new s,l="flashhttprequest_as3",h=!1,p=null,v=[],d=[],g=[],w=!1,y=!1,m={};m.flashSupport=function(){return h},m.post=function(e,t,r,i,o,a){var u=-1;i&&(u=v.length,v[u]=i),w?n(e,t,r,u,o,a):d.push(function(){n(e,t,r,u,o,a)})},m.__callback=function(e,t,r){t=null!==t?decodeURIComponent(t):null,r=null!==r?decodeURIComponent(r):null,"function"==typeof v[e]&&v[e](t,r),delete v[e]},m.__jsReady=function(){return w},m.__setSwfReady=function(){for(p=-1!==navigator.appName.indexOf("Microsoft")?e[l]:i[l],y=!0,e.__flash__removeCallback=function(e,t){try{e&&(e[t]=null)}catch(r){}};g.length>0;){var t=g.shift();"function"==typeof t&&t()}},e.FlashHttpRequest=m,function(){if(!w)for(u||f||r(),w=!0;d.length>0;){var e=d.shift();"function"==typeof e&&e()}}()}(hprose.global),function(e){"use strict";function t(e,t){function r(e){var t,r,n;for(t=e.replace(/(^\s*)|(\s*$)/g,"").split(";"),r={},e=t[0].replace(/(^\s*)|(\s*$)/g,"").split("=",2),e[1]===undefined&&(e[1]=null),r.name=e[0],r.value=e[1],n=1;n<t.length;n++)e=t[n].replace(/(^\s*)|(\s*$)/g,"").split("=",2),e[1]===undefined&&(e[1]=null),r[e[0].toUpperCase()]=e[1];r.PATH?('"'===r.PATH.charAt(0)&&(r.PATH=r.PATH.substr(1)),'"'===r.PATH.charAt(r.PATH.length-1)&&(r.PATH=r.PATH.substr(0,r.PATH.length-1))):r.PATH="/",r.EXPIRES&&(r.EXPIRES=Date.parse(r.EXPIRES)),r.DOMAIN?r.DOMAIN=r.DOMAIN.toLowerCase():r.DOMAIN=s,r.SECURE=r.SECURE!==undefined,i[r.DOMAIN]===undefined&&(i[r.DOMAIN]={}),i[r.DOMAIN][r.name]=r}var o,a,u=n(t),s=u.host;for(o in e)a=e[o],"set-cookie"!==(o=o.toLowerCase())&&"set-cookie2"!==o||("string"==typeof a&&(a=[a]),a.forEach(r))}function r(e){var t=n(e),r=t.host,o=t.path,a="https:"===t.protocol,u=[];for(var s in i)if(r.indexOf(s)>-1){var c=[];for(var f in i[s]){var l=i[s][f];l.EXPIRES&&(new Date).getTime()>l.EXPIRES?c.push(f):0===o.indexOf(l.PATH)&&(a&&l.SECURE||!l.SECURE)&&null!==l.value&&u.push(l.name+"="+l.value)}for(var h in c)delete i[s][c[h]]}return u.length>0?u.join("; "):""}var n=e.parseuri,i={};e.cookieManager={setCookie:t,getCookie:r}}(hprose),function(e,t,r){"use strict";function n(){if(null!==S)return new k(S);for(var e=["MSXML2.XMLHTTP","MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MsXML2.XMLHTTP.2.6","Microsoft.XMLHTTP","Microsoft.XMLHTTP.1.0","Microsoft.XMLHTTP.1"],t=e.length,r=0;r<t;r++)try{var n=new k(e[r]);return S=e[r],n}catch(i){}throw new Error("Could not find an installed XML parser")}function i(){if(E)return new b;if(k)return n();throw new Error("XMLHttpRequest is not supported by this browser.")}function o(){}function a(e){var t=h(null);if(e){e=e.split("\r\n");for(var r=0,n=e.length;r<n;r++)if(""!==e[r]){var i=e[r].split(": ",2),o=i[0].trim(),a=i[1].trim();o in t?Array.isArray(t[o])?t[o].push(a):t[o]=[t[o],a]:t[o]=a}}return t}function u(e,n,s){function c(e){var t,r,n=h(null);for(t in I)n[t]=I[t];if(e)for(t in e)r=e[t],Array.isArray(r)?n[t]=r.join(", "):n[t]=r;return n}function d(e,t){var r=new l,n=i();n.open("POST",_.uri(),!0),A&&(n.withCredentials="true");var u=c(t.httpHeader);for(var s in u)n.setRequestHeader(s,u[s]);return t.binary||n.setRequestHeader("Content-Type","text/plain; charset=UTF-8"),n.onreadystatechange=function(){if(4===n.readyState&&(n.onreadystatechange=o,n.status)){var e=n.getAllResponseHeaders();t.httpHeader=a(e),200===n.status?t.binary?r.resolve(v(n.response)):r.resolve(n.responseText):r.reject(new Error(n.status+":"+n.statusText))}},n.onerror=function(){r.reject(new Error("error"))},t.timeout>0&&(r=r.timeout(t.timeout).catchError(function(e){throw n.onreadystatechange=o,n.onerror=o,n.abort(),e},function(e){return e instanceof y})),t.binary?(n.responseType="arraybuffer",n.sendAsBinary(e)):n.send(e),r}function b(e,t){var r=new l,n=function(e,n){t.httpHeader=h(null),null===n?r.resolve(e):r.reject(new Error(n))},i=c(t.httpHeader);return m.post(_.uri(),i,e,n,t.timeout,t.binary),r}function E(e,r){var n=new l,i=c(r.httpHeader),o=w.getCookie(_.uri());return""!==o&&(i.Cookie=o),t.api.ajax({url:_.uri(),method:"post",data:{body:e},timeout:r.timeout,dataType:"text",headers:i,returnAll:!0,certificate:_.certificate},function(e,t){e?(r.httpHeader=e.headers,200===e.statusCode?(w.setCookie(e.headers,_.uri()),n.resolve(e.body)):n.reject(new Error(e.statusCode+":"+e.body))):n.reject(new Error(t.msg))}),n}function k(e,t){var r=new l,n=T.mm("do_Http");n.method="POST",n.timeout=t.timeout,n.contentType="text/plain; charset=UTF-8",n.url=_.uri(),n.body=e;var i=c(t.httpHeader);for(var o in i)n.setRequestHeader(o,i[o]);var a=w.getCookie(_.uri());return""!==a&&n.setRequestHeader("Cookie",a),n.on("success",function(e){var t=n.getResponseHeader("set-cookie");t&&w.setCookie({"set-cookie":t},_.uri()),r.resolve(e)}),n.on("fail",function(e){r.reject(new Error(e.status+":"+e.data))}),n.request(),t.httpHeader=h(null),r}function S(){if(t.location===r)return!0;var e=g(_.uri());return e.protocol!==t.location.protocol||e.host!==t.location.host}function O(e,r){var n=m.flashSupport()&&!C&&!A&&(r.binary||S()),i="undefined"!=typeof t.api&&"undefined"!=typeof t.api.ajax,o=n?b(e,r):i?E(e,r):T?k(e,r):d(e,r);return r.oneway&&o.resolve(),o}function j(e,t){"content-type"!==e.toLowerCase()&&(t?I[e]=t:delete I[e])}if(this.constructor!==u)return new u(e,n,s);f.call(this,e,n,s);var I=h(null),_=this;p(this,{certificate:{value:null,writable:!0},setHeader:{value:j},sendAndReceive:{value:O}})}function s(e){var t=g(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error("This client desn't support "+t.protocol+" scheme.")}function c(e,t,r){if("string"==typeof e)s(e);else{if(!Array.isArray(e))throw new Error("You should set server uri first!");e.forEach(function(e){s(e)})}return new u(e,t,r)}var f=e.Client,l=e.Future,h=e.createObject,p=e.defineProperties,v=e.toBinaryString,d=e.toUint8Array,g=e.parseuri,w=e.cookieManager,y=t.TimeoutError,m=t.FlashHttpRequest,b=t.XMLHttpRequest;t.plus&&t.plus.net&&t.plus.net.XMLHttpRequest?b=t.plus.net.XMLHttpRequest:t.document&&t.document.addEventListener&&t.document.addEventListener("plusready",function(){b=t.plus.net.XMLHttpRequest},!1);var T;try{T=t.require("deviceone")}catch(O){}var C=t.location!==r&&"file:"===t.location.protocol,E=void 0!==b,A=!C&&E&&"withCredentials"in new b,k=t.ActiveXObject,S=null;E&&"undefined"!=typeof Uint8Array&&!b.prototype.sendAsBinary&&(b.prototype.sendAsBinary=function(e){var t=d(e);this.send(ArrayBuffer.isView?t:t.buffer)}),p(u,{create:{value:c}}),t.HproseHttpClient=e.HttpClient=u}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e,t,o){function a(){return C<2147483647?++C:C=0}function v(e,t){var r=new u;r.writeInt32BE(e),k[e].binary?r.write(t):r.writeUTF16AsUTF8(t);var n=p(r.take());ArrayBuffer.isView?j.send(n):j.send(n.buffer)}function g(e){O.resolve(e)}function w(e){var t;t=new u("string"==typeof e.data?u.utf8Encode(e.data):h(e.data));var n=t.readInt32BE(),i=A[n],o=k[n];if(delete A[n],delete k[n],i!==r){--E;var a=t.read(t.length()-4);o.binary||(a=u.utf8Decode(a)),i.resolve(a)}if(E<100&&S.length>0){++E;var s=S.pop();O.then(function(){v(s[0],s[1])})}0!==E||I.keepAlive()||T()}function y(e){A.forEach(function(t,r){t.reject(new Error(e.code+":"+e.reason)),delete A[r]}),E=0,j=null}function m(){O=new c,j=new d(I.uri()),j.binaryType="arraybuffer",j.onopen=g,j.onmessage=w,j.onerror=n,j.onclose=y}function b(e,t){var r=a(),n=new c;return A[r]=n,k[r]=t,t.timeout>0&&(n=n.timeout(t.timeout).catchError(function(e){throw delete A[r],--E,T(),e},function(e){return e instanceof f})),null!==j&&j.readyState!==d.CLOSING&&j.readyState!==d.CLOSED||m(),E<100?(++E,O.then(function(){v(r,e)})):S.push([r,e]),t.oneway&&n.resolve(),n}function T(){null!==j&&(j.onopen=n,j.onmessage=n,j.onclose=n,j.close())}if(void 0===d)throw new Error("WebSocket is not supported by this browser.");if(this.constructor!==i)return new i(e,t,o);s.call(this,e,t,o);var C=0,E=0,A=[],k=[],S=[],O=null,j=null,I=this;l(this,{sendAndReceive:{value:b},close:{value:T}})}function o(e){var t=v(e);if("ws:"!==t.protocol&&"wss:"!==t.protocol)throw new Error("This client desn't support "+t.protocol+" scheme.")}function a(e,t,r){if("string"==typeof e)o(e);else{if(!Array.isArray(e))throw new Error("You should set server uri first!");e.forEach(function(e){o(e)})}return new i(e,t,r)}var u=e.StringIO,s=e.Client,c=e.Future,f=t.TimeoutError,l=e.defineProperties,h=e.toBinaryString,p=e.toUint8Array,v=e.parseuri,d=t.WebSocket||t.MozWebSocket;l(i,{create:{value:a}}),t.HproseWebSocketClient=e.WebSocketClient=i}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e){l[e.socketId].onreceive(f(e.data))}function o(e){var t=l[e.socketId];t.onerror(e.resultCode),t.destroy()}function a(){null===h&&(h=t.chrome.sockets.tcp,h.onReceive.addListener(i),h.onReceiveError.addListener(o)),this.socketId=new u,this.connected=!1,this.timeid=r,this.onclose=n,this.onconnect=n,this.onreceive=n,this.onerror=n}var u=e.Future,s=e.defineProperties,c=e.toUint8Array,f=e.toBinaryString,l={},h=null;s(a.prototype,{connect:{value:function(e,t,r){var n=this;h.create({persistent:r&&r.persistent},function(i){r&&("noDelay"in r&&h.setNoDelay(i.socketId,r.noDelay,function(e){e<0&&(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose())}),"keepAlive"in r&&h.setKeepAlive(i.socketId,r.keepAlive,function(e){e<0&&(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose())})),r&&r.tls?h.setPaused(i.socketId,!0,function(){h.connect(i.socketId,e,t,function(e){e<0?(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose()):h.secure(i.socketId,function(t){0!==t?(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose()):h.setPaused(i.socketId,!1,function(){n.socketId.resolve(i.socketId)})})})}):h.connect(i.socketId,e,t,function(e){e<0?(n.socketId.reject(e),h.disconnect(i.socketId),h.close(i.socketId),n.onclose()):n.socketId.resolve(i.socketId)})}),this.socketId.then(function(e){l[e]=n,n.connected=!0,n.onconnect(e)},function(e){n.onerror(e)})}},send:{value:function(e){e=c(e).buffer;var t=this,r=new u;return this.socketId.then(function(n){h.send(n,e,function(e){e.resultCode<0?(t.onerror(e.resultCode),r.reject(e.resultCode),t.destroy()):r.resolve(e.bytesSent)})}),r}},destroy:{value:function(){var e=this;this.connected=!1,this.socketId.then(function(t){h.disconnect(t),h.close(t),delete l[t],e.onclose()})}},ref:{value:function(){this.socketId.then(function(e){h.setPaused(e,!1)})}},unref:{value:function(){this.socketId.then(function(e){h.setPaused(e,!0)})}},clearTimeout:{value:function(){this.timeid!==r&&t.clearTimeout(this.timeid)}},setTimeout:{value:function(e,r){this.clearTimeout(),this.timeid=t.setTimeout(r,e)}}}),e.ChromeTcpSocket=a}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(){null===f&&(f=t.api.require("socketManager")),this.socketId=new o,this.connected=!1,this.timeid=r,this.onclose=n,this.onconnect=n,this.onreceive=n,this.onerror=n}var o=e.Future,a=e.defineProperties,u=t.atob,s=t.btoa,c={},f=null;a(i.prototype,{connect:{value:function(e,t,r){var n=this;f.createSocket({type:"tcp",host:e,port:t,timeout:r.timeout,returnBase64:!0},function(e){if(e)switch(e.state){case 101:break;case 102:n.socketId.resolve(e.sid);break;case 103:n.onreceive(u(e.data.replace(/\s+/g,"")));break;case 201:n.socketId.reject(new Error("Create TCP socket failed"));break;case 202:n.socketId.reject(new Error("TCP connection failed"));break;case 203:n.onclose(),n.onerror(new Error("Abnormal disconnect connection"));break;case 204:n.onclose();break;case 205:n.onclose(),n.onerror(new Error("Unknown error"))}}),this.socketId.then(function(e){c[e]=n,n.connected=!0,n.onconnect(e)},function(e){n.onerror(e)})}},send:{value:function(e){var t=this,r=new o;return this.socketId.then(function(n){f.write({sid:n,data:s(e),base64:!0},function(e,n){e.status?r.resolve():(t.onerror(new Error(n.msg)),r.reject(n.msg),t.destroy())})}),r}},destroy:{value:function(){var e=this;this.connected=!1,this.socketId.then(function(t){f.closeSocket({sid:t},function(t,r){t.status||e.onerror(new Error(r.msg))}),delete c[t]})}},ref:{value:n},unref:{value:n},clearTimeout:{value:function(){this.timeid!==r&&t.clearTimeout(this.timeid)}},setTimeout:{value:function(e,r){this.clearTimeout(),this.timeid=t.setTimeout(r,e)}}}),e.APICloudTcpSocket=i}(hprose,hprose.global),function(e,t,r){"use strict";function n(){}function i(e,t){e.onreceive=function(r){"receiveEntry"in e||(e.receiveEntry={stream:new d,headerLength:4,dataLength:-1,id:null});var n=e.receiveEntry,i=n.stream,o=n.headerLength,a=n.dataLength,u=n.id;for(i.write(r);;){if(a<0&&i.length()>=o&&0!=(2147483648&(a=i.readInt32BE()))&&(a&=2147483647,o=8),8===o&&null===u&&i.length()>=o&&(u=i.readInt32BE()),!(a>=0&&i.length()-o>=a))break;t(i.read(a),u),o=4,u=null,i.trunc(),a=-1}n.stream=i,n.headerLength=o,n.dataLength=a,n.id=u}}function o(e){e&&(this.client=e,this.uri=this.client.uri(),this.size=0,this.pool=[],this.requests=[])}function a(e){o.call(this,e)}function u(e){o.call(this,e)}function s(e,t,r){function n(){return m}function i(e){m=!!e}function o(){return b}function c(e){b=!!e}function f(){return T}function l(e){"number"==typeof e?(T=0|e)<1&&(T=10):T=10}function h(){return C}function p(e){C="number"==typeof e?0|e:0}function d(e,t){var r=new g;return b?(null!==E&&E.uri===w.uri||(E=new a(w)),E.sendAndReceive(e,r,t)):(null!==A&&A.uri===w.uri||(A=new u(w)),A.sendAndReceive(e,r,t)),t.oneway&&r.resolve(),r}if(this.constructor!==s)return new s(e,t,r);v.call(this,e,t,r);var w=this,m=!0,b=!1,T=10,C=3e4,E=null,A=null;y(this,{noDelay:{get:n,set:i},fullDuplex:{get:o,set:c},maxPoolSize:{get:f,set:l},poolTimeout:{get:h,set:p},sendAndReceive:{value:d}})}function c(e){var t=m(e),r=t.protocol;if("tcp:"!==r&&"tcp4:"!==r&&"tcp6:"!==r&&"tcps:"!==r&&"tcp4s:"!==r&&"tcp6s:"!==r&&"tls:"!==r)throw new Error("This client desn't support "+r+" scheme.")}function f(e,t,r){if("string"==typeof e)c(e);else{if(!Array.isArray(e))throw new Error("You should set server uri first!");e.forEach(function(e){c(e)})}return new s(e,t,r)}var l=t.TimeoutError,h=e.ChromeTcpSocket,p=e.APICloudTcpSocket,v=e.Client,d=e.StringIO,g=e.Future,w=e.createObject,y=e.defineProperties,m=e.parseuri;y(o.prototype,{create:{value:function(){var e,r=m(this.uri),n=r.protocol,i=r.hostname,o=parseInt(r.port,10);if("tcp:"===n||"tcp4:"===n||"tcp6:"===n)e=!1;else{if("tcps:"!==n&&"tcp4s:"!==n&&"tcp6s:"!==n&&"tls:"!==n)throw new Error("Unsupported "+n+" protocol!");e=!0}var a;if(t.chrome&&t.chrome.sockets&&t.chrome.sockets.tcp)a=new h;else{if(!t.api||!t.api.require)throw new Error("TCP Socket is not supported by this browser or platform.");a=new p}var u=this;return a.connect(i,o,{persistent:!0,tls:e,timeout:this.client.timeout(),noDelay:this.client.noDelay(),keepAlive:this.client.keepAlive()}),a.onclose=function(){--u.size},++this.size,a}}}),a.prototype=w(o.prototype,{fetch:{value:function(){for(var e=this.pool;e.length>0;){var t=e.pop();if(t.connected)return 0===t.count&&(t.clearTimeout(),t.ref()),t}return null}},init:{value:function(e){var t=this;e.count=0,e.futures={},e.contexts={},e.timeoutIds={},i(e,function(r,n){var i=e.futures[n],o=e.contexts[n];i&&(t.clean(e,n),0===e.count&&t.recycle(e),o.binary||(r=d.utf8Decode(r)),i.resolve(r))}),e.onerror=function(r){var n=e.futures;for(var i in n){var o=n[i];t.clean(e,i),o.reject(r)}}}},recycle:{value:function(e){e.unref(),e.setTimeout(this.client.poolTimeout(),function(){e.destroy()})}},clean:{value:function(e,r){void 0!==e.timeoutIds[r]&&(t.clearTimeout(e.timeoutIds[r]),delete e.timeoutIds[r]),delete e.futures[r],delete e.contexts[r],--e.count,this.sendNext(e)}},sendNext:{value:function(e){if(e.count<10)if(this.requests.length>0){var t=this.requests.pop();t.push(e),this.send.apply(this,t)}else this.pool.lastIndexOf(e)<0&&this.pool.push(e)}},send:{value:function(e,r,n,i,o){var a=this,u=i.timeout;u>0&&(o.timeoutIds[n]=t.setTimeout(function(){a.clean(o,n),0===o.count&&a.recycle(o),r.reject(new l("timeout"))},u)),o.count++,o.futures[n]=r,o.contexts[n]=i;var s=e.length,c=new d;c.writeInt32BE(2147483648|s),c.writeInt32BE(n),i.binary?c.write(e):c.writeUTF16AsUTF8(e),o.send(c.take()).then(function(){a.sendNext(o)})}},getNextId:{value:function(){return this.nextid<2147483647?++this.nextid:this.nextid=0}},sendAndReceive:{value:function(e,t,r){var n=this.fetch(),i=this.getNextId();if(n)this.send(e,t,i,r,n);else if(this.size<this.client.maxPoolSize()){n=this.create(),n.onerror=function(e){t.reject(e)};var o=this;n.onconnect=function(){o.init(n),o.send(e,t,i,r,n)}}else this.requests.push([e,t,i,r])}}}),a.prototype.constructor=o,u.prototype=w(o.prototype,{fetch:{value:function(){for(var e=this.pool;e.length>0;){var t=e.pop();if(t.connected)return t.clearTimeout(),t.ref(),t}return null}},recycle:{value:function(e){this.pool.lastIndexOf(e)<0&&(e.unref(),e.setTimeout(this.client.poolTimeout(),function(){e.destroy()}),this.pool.push(e))}},clean:{value:function(e){e.onreceive=n,e.onerror=n,void 0!==e.timeoutId&&(t.clearTimeout(e.timeoutId),delete e.timeoutId)}},sendNext:{value:function(e){if(this.requests.length>0){var t=this.requests.pop();t.push(e),this.send.apply(this,t)}else this.recycle(e)}},send:{value:function(e,r,n,o){var a=this,u=n.timeout;u>0&&(o.timeoutId=t.setTimeout(function(){a.clean(o),o.destroy(),r.reject(new l("timeout"))},u)),i(o,function(e){a.clean(o),a.sendNext(o),n.binary||(e=d.utf8Decode(e)),r.resolve(e)}),o.onerror=function(e){a.clean(o),r.reject(e)};var s=e.length,c=new d;c.writeInt32BE(s),n.binary?c.write(e):c.writeUTF16AsUTF8(e),o.send(c.take())}},sendAndReceive:{value:function(e,t,r){var n=this.fetch();if(n)this.send(e,t,r,n);else if(this.size<this.client.maxPoolSize()){n=this.create();var i=this;n.onerror=function(e){t.reject(e)},n.onconnect=function(){i.send(e,t,r,n)}}else this.requests.push([e,t,r])}}}),u.prototype.constructor=o,y(s,{create:{value:f}}),t.HproseTcpClient=e.TcpClient=s}(hprose,hprose.global),function(e){"use strict";function t(e){this.version=e||"2.0"}var r=e.Tags,n=e.StringIO,i=e.Writer,o=e.Reader,a=1;t.prototype.inputFilter=function(e){"{"===e.charAt(0)&&(e="["+e+"]");for(var t=JSON.parse(e),o=new n,a=new i(o,!0),u=0,s=t.length;u<s;++u){var c=t[u];c.error?(o.write(r.TagError),a.writeString(c.error.message)):(o.write(r.TagResult),a.serialize(c.result))}return o.write(r.TagEnd),o.take()},t.prototype.outputFilter=function(e){var t=[],i=new n(e),u=new o(i,!1,!1),s=i.readChar();do{var c={};s===r.TagCall&&(c.method=u.readString(),s=i.readChar(),s===r.TagList&&(c.params=u.readListWithoutTag(),s=i.readChar()),s===r.TagTrue&&(s=i.readChar())),"1.1"===this.version?c.version="1.1":"2.0"===this.version&&(c.jsonrpc="2.0"),c.id=a++,t.push(c)}while(s===r.TagCall);return t.length>1?JSON.stringify(t):JSON.stringify(t[0])},e.JSONRPCClientFilter=t}(hprose),function(e){"use strict";e.common={Completer:e.Completer,Future:e.Future,ResultMode:e.ResultMode},e.io={StringIO:e.StringIO,ClassManager:e.ClassManager,Tags:e.Tags,RawReader:e.RawReader,Reader:e.Reader,Writer:e.Writer,Formatter:e.Formatter},e.client={Client:e.Client,HttpClient:e.HttpClient,TcpClient:e.TcpClient,WebSocketClient:e.WebSocketClient},e.filter={JSONRPCClientFilter:e.JSONRPCClientFilter},"function"==typeof define&&(define.cmd?define("hprose",[],e):define.amd&&define("hprose",[],function(){return e})),"object"==typeof module&&(module.exports=e)}(hprose),function(e){"use strict";function t(e,t,r,i){var o=t&&t.prototype instanceof n?t:n,a=Object.create(o.prototype),u=new h(i||[]);return a._invoke=c(e,r,u),a}function r(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(n){return{type:"throw",arg:n}}}function n(){}function i(){}function o(){}function a(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function u(e){this.arg=e}function s(e){function t(n,i,o,a){var s=r(e[n],e,i);if("throw"!==s.type){var c=s.arg,f=c.value;return f instanceof u?Promise.resolve(f.arg).then(function(e){t("next",e,o,a)},function(e){t("throw",e,o,a)}):Promise.resolve(f).then(function(e){c.value=e,o(c)},a)}a(s.arg)}function n(e,r){function n(){return new Promise(function(n,i){t(e,r,n,i)})}return i=i?i.then(n,n):n()}"object"==typeof process&&process.domain&&(t=process.domain.bind(t));var i;this._invoke=n}function c(e,t,n){var i=C;return function(o,a){if(i===A)throw new Error("Generator is already running");if(i===k){if("throw"===o)throw a;return v()}for(;;){var u=n.delegate;if(u){if("return"===o||"throw"===o&&u.iterator[o]===d){n.delegate=null;var s=u.iterator["return"];if(s){var c=r(s,u.iterator,a);if("throw"===c.type){o="throw",a=c.arg;continue}}if("return"===o)continue}var c=r(u.iterator[o],u.iterator,a);if("throw"===c.type){n.delegate=null,o="throw",a=c.arg;continue}o="next",a=d;var f=c.arg;if(!f.done)return i=E,f;n[u.resultName]=f.value,n.next=u.nextLoc,n.delegate=null}if("next"===o)n.sent=n._sent=a;else if("throw"===o){if(i===C)throw i=k,a;n.dispatchException(a)&&(o="next",a=d)}else"return"===o&&n.abrupt("return",a);i=A;var c=r(e,t,n);if("normal"===c.type){i=n.done?k:E;var f={value:c.arg,done:n.done};if(c.arg!==S)return f;n.delegate&&"next"===o&&(a=d)}else"throw"===c.type&&(i=k,o="throw",a=c.arg)}}}function f(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function l(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function h(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(f,this),this.reset(!0)}function p(e){if(e){var t=e[y];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,n=function i(){for(;++r<e.length;)if(g.call(e,r))return i.value=e[r],i.done=!1,i;return i.value=d,i.done=!0,i};return n.next=n}}return{next:v}}function v(){return{value:d,done:!0}}var d,g=Object.prototype.hasOwnProperty,w="function"==typeof Symbol?Symbol:{},y=w.iterator||"@@iterator",m=w.toStringTag||"@@toStringTag",b="object"==typeof module,T=e.regeneratorRuntime;if(T)return void(b&&(module.exports=T));T=e.regeneratorRuntime=b?module.exports:{},T.wrap=t;var C="suspendedStart",E="suspendedYield",A="executing",k="completed",S={},O=o.prototype=n.prototype;i.prototype=O.constructor=o,o.constructor=i,o[m]=i.displayName="GeneratorFunction",T.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===i||"GeneratorFunction"===(t.displayName||t.name))},T.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,o):(e.__proto__=o,m in e||(e[m]="GeneratorFunction")),e.prototype=Object.create(O),e},T.awrap=function(e){return new u(e)},a(s.prototype),T.async=function(e,r,n,i){var o=new s(t(e,r,n,i));return T.isGeneratorFunction(r)?o:o.next().then(function(e){return e.done?e.value:o.next()})},a(O),O[y]=function(){return this},O[m]="Generator",O.toString=function(){return"[object Generator]"},T.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},T.values=p,h.prototype={constructor:h,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=d,this.done=!1,this.delegate=null,this.tryEntries.forEach(l),!e)for(var t in this)"t"===t.charAt(0)&&g.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=d)},stop:function(){this.done=!0;var e=this.tryEntries[0],t=e.completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){function t(t,n){return o.type="throw",o.arg=e,r.next=t,!!n}if(this.done)throw e;for(var r=this,n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n],o=i.completion;if("root"===i.tryLoc)return t("end");if(i.tryLoc<=this.prev){var a=g.call(i,"catchLoc"),u=g.call(i,"finallyLoc");if(a&&u){if(this.prev<i.catchLoc)return t(i.catchLoc,!0);if(this.prev<i.finallyLoc)return t(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return t(i.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return t(i.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&g.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?this.next=i.finallyLoc:this.complete(o),S},complete:function(e,t){if("throw"===e.type)throw e.arg;"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=e.arg,this.next="end"):"normal"===e.type&&t&&(this.next=t)},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),l(r),S}},"catch":function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;l(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:p(e),resultName:t,nextLoc:r},S}}}("object"==typeof global?global:"object"==typeof window?window:"object"==typeof self?self:this);
|
data/javascript/140.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const path = require('path');const j79 = require('j79-utils');const nexlEngine = require('nexl-engine');const storageUtils = require('../../api/storage-utils');const security = require('../../api/security');const utils = require('../../api/utils');const logger = require('../../api/logger');const restUtls = require('../../common/rest-urls');const di = require('../../common/data-interchange-constants');const confMgmt = require('../../api/conf-mgmt');const confConsts = require('../../common/conf-constants');const diConsts = require('../../common/data-interchange-constants');const router = express.Router();//////////////////////////////////////////////////////////////////////////////// [/nexl/storage/set-var]//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) { // checking for permissions const username = security.getLoggedInUsername(req); if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username); security.sendError(res, 'No write permissions'); return; } // resolving params const relativePath = req.body['relativePath']; const varName = req.body['varName']; const newValue = req.body['newValue']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`); // validating relativePath if (!relativePath) { logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [relativePath] is not provided'); return; } // validating varName if (!varName) { logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [varName] is not provided'); return; } // validating newValue if (!newValue) { logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [newValue] is not provided'); return; } return storageUtils.setVar(relativePath, varName, newValue) .then(_ => { res.send({}); logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`); }) .catch( (err) => { logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`); security.sendError(res, 'Failed to update a JavaScript var'); });});//////////////////////////////////////////////////////////////////////////////// md//////////////////////////////////////////////////////////////////////////////function md2Expressions(md) { const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g'); const result = []; md.forEach(item => { if (item.type === 'Function') { const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`; result.push(`\${${args}${item.name}()}`); return; } result.push(`\${${item.name}}`); if (item.type === 'Object' && item.keys) { item.keys.forEach(key => { const keyEscaped = key.replace(opRegex, '\\$1'); result.push(`\${${item.name}.${keyEscaped}}`); }); } }); return result;}router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username); security.sendError(res, 'No read permissions'); return; } const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath); if (!utils.isFilePathValid(fullPath)) { logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`); security.sendError(res, 'Unacceptable path'); return; } const nexlSource = { fileEncoding: confConsts.ENCODING_UTF8, basePath: confMgmt.getNexlStorageDir(), filePath: fullPath, fileContent: req.body[diConsts.FILE_BODY] }; // resolving metadata for [relativePath] let md; try { md = nexlEngine.parseMD(nexlSource); } catch (e) { logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`); security.sendError(res, 'Failed to parse a file'); return; } res.send({ md: md2Expressions(md) });});//////////////////////////////////////////////////////////////////////////////// reindex files//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) { const username = security.getLoggedInUsername(req); logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`); if (!security.isAdmin(username)) { logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username); security.sendError(res, 'admin permissions required'); return; } storageUtils.cacheStorageFiles() .then(result => res.send({})) .catch(err => { logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Failed to reindex'); });});//////////////////////////////////////////////////////////////////////////////// find file//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; const text = req.body[di.TEXT]; const matchCase = req.body[di.MATCH_CASE]; const isRegex = req.body[di.IS_REGEX]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.FILE_IN_FILES}] request from the [${username}] user for [relativePath=${relativePath}] [text=${text}] [matchCase=${matchCase}] [isRegex=${isRegex}]`); // todo : automate validations !!! // todo : automate validations !!! // todo : automate validations !!! // validating relativePath if (!j79.isString(relativePath) || relativePath.text < 1) { logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`); security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`); return; } // validating text if (!j79.isString(text) || text.length < 1) { logger.log.error('Empty text is not allowed'); security.sendError(res, 'Empty text is not allowed'); return; } // validating matchCase if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`); security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`); return; } // validating isRegex if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`); security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`); return; } if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username); security.sendError(res, 'No read permissions'); return; } const data = {}; data[di.RELATIVE_PATH] = relativePath; data[di.TEXT] = text; data[di.MATCH_CASE] = matchCase; data[di.IS_REGEX] = isRegex; storageUtils.findInFiles(data).then( result => res.send({result: result}) ).catch(err => { logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Find in files failed'); });});//////////////////////////////////////////////////////////////////////////////// move item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) { const username = security.getLoggedInUsername(req); const source = req.body['source']; const dest = req.body['dest']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`); // validating ( must not empty string ) if (!j79.isString(source) || source.length < 1) { logger.log.error('Invalid source item'); security.sendError(res, 'Invalid source item'); return; } // validating if (!j79.isString(dest)) { logger.log.error('Invalid dest item'); security.sendError(res, 'Invalid dest item'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to move items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.move(source, dest) .then(_ => { res.send({}); logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err)); security.sendError(res, 'Failed to move item'); });});//////////////////////////////////////////////////////////////////////////////// rename item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const newRelativePath = req.body['newRelativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } // validating ( must not empty string ) if (!j79.isString(newRelativePath) || newRelativePath.length < 1) { logger.log.error('Invalid newRelativePath'); security.sendError(res, 'Invalid newRelativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.rename(relativePath, newRelativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to rename item'); });});//////////////////////////////////////////////////////////////////////////////// delete item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.deleteItem(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to delete item'); });});//////////////////////////////////////////////////////////////////////////////// make-dir//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.mkdir(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to create a directory'); });});//////////////////////////////////////////////////////////////////////////////// get tree items hierarchy//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) { const username = security.getLoggedInUsername(req); logger.log.debug(`Getting tree items hierarchy by [${username}] user`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.getTreeItems());});//////////////////////////////////////////////////////////////////////////////// list-dirs, list-files, list-files-and-dirs//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// res.send(storageUtils.listFiles(relativePath));// FIXED: });router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirs(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirsAndFiles(relativePath));});//////////////////////////////////////////////////////////////////////////////// load file from storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username); security.sendError(res, 'No read permissions'); return; } const currentTime = new Date().getTime(); return storageUtils.loadFileFromStorage(relativePath) .then(data => { const body = {}; body[di.FILE_BODY] = data; body[di.FILE_LOAD_TIME] = currentTime; res.send(body); logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to load file'); });});//////////////////////////////////////////////////////////////////////////////// save file to storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const content = req.body['content']; const fileLoadTime = req.body[di.FILE_LOAD_TIME]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}] [content=***not logging***] [fileLoadTime=${fileLoadTime}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime) .then(result => { res.send(result); logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to save file'); });});//////////////////////////////////////////////////////////////////////////////// undeclared routes//////////////////////////////////////////////////////////////////////////////router.post('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});router.get('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});// --------------------------------------------------------------------------------module.exports = router;// --------------------------------------------------------------------------------
|
data/javascript/141.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const path = require('path');const j79 = require('j79-utils');const nexlEngine = require('nexl-engine');const storageUtils = require('../../api/storage-utils');const security = require('../../api/security');const utils = require('../../api/utils');const logger = require('../../api/logger');const restUtls = require('../../common/rest-urls');const di = require('../../common/data-interchange-constants');const confMgmt = require('../../api/conf-mgmt');const confConsts = require('../../common/conf-constants');const diConsts = require('../../common/data-interchange-constants');const router = express.Router();//////////////////////////////////////////////////////////////////////////////// [/nexl/storage/set-var]//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) { // checking for permissions const username = security.getLoggedInUsername(req); if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username); security.sendError(res, 'No write permissions'); return; } // resolving params const relativePath = req.body['relativePath']; const varName = req.body['varName']; const newValue = req.body['newValue']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`); // validating relativePath if (!relativePath) { logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [relativePath] is not provided'); return; } // validating varName if (!varName) { logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [varName] is not provided'); return; } // validating newValue if (!newValue) { logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [newValue] is not provided'); return; } return storageUtils.setVar(relativePath, varName, newValue) .then(_ => { res.send({}); logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`); }) .catch( (err) => { logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`); security.sendError(res, 'Failed to update a JavaScript var'); });});//////////////////////////////////////////////////////////////////////////////// md//////////////////////////////////////////////////////////////////////////////function md2Expressions(md) { const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g'); const result = []; md.forEach(item => { if (item.type === 'Function') { const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`; result.push(`\${${args}${item.name}()}`); return; } result.push(`\${${item.name}}`); if (item.type === 'Object' && item.keys) { item.keys.forEach(key => { const keyEscaped = key.replace(opRegex, '\\$1'); result.push(`\${${item.name}.${keyEscaped}}`); }); } }); return result;}router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username); security.sendError(res, 'No read permissions'); return; } const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath); if (!utils.isFilePathValid(fullPath)) { logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`); security.sendError(res, 'Unacceptable path'); return; } const nexlSource = { fileEncoding: confConsts.ENCODING_UTF8, basePath: confMgmt.getNexlStorageDir(), filePath: fullPath, fileContent: req.body[diConsts.FILE_BODY] }; // resolving metadata for [relativePath] let md; try { md = nexlEngine.parseMD(nexlSource); } catch (e) { logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`); security.sendError(res, 'Failed to parse a file'); return; } res.send({ md: md2Expressions(md) });});//////////////////////////////////////////////////////////////////////////////// reindex files//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) { const username = security.getLoggedInUsername(req); logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`); if (!security.isAdmin(username)) { logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username); security.sendError(res, 'admin permissions required'); return; } storageUtils.cacheStorageFiles() .then(result => res.send({})) .catch(err => { logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Failed to reindex'); });});//////////////////////////////////////////////////////////////////////////////// find file//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; const text = req.body[di.TEXT]; const matchCase = req.body[di.MATCH_CASE]; const isRegex = req.body[di.IS_REGEX]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.FILE_IN_FILES}] request from the [${username}] user for [relativePath=${relativePath}] [text=${text}] [matchCase=${matchCase}] [isRegex=${isRegex}]`); // todo : automate validations !!! // todo : automate validations !!! // todo : automate validations !!! // validating relativePath if (!j79.isString(relativePath) || relativePath.text < 1) { logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`); security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`); return; } // validating text if (!j79.isString(text) || text.length < 1) { logger.log.error('Empty text is not allowed'); security.sendError(res, 'Empty text is not allowed'); return; } // validating matchCase if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`); security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`); return; } // validating isRegex if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`); security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`); return; } if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username); security.sendError(res, 'No read permissions'); return; } const data = {}; data[di.RELATIVE_PATH] = relativePath; data[di.TEXT] = text; data[di.MATCH_CASE] = matchCase; data[di.IS_REGEX] = isRegex; storageUtils.findInFiles(data).then( result => res.send({result: result}) ).catch(err => { logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Find in files failed'); });});//////////////////////////////////////////////////////////////////////////////// move item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) { const username = security.getLoggedInUsername(req); const source = req.body['source']; const dest = req.body['dest']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`); // validating ( must not empty string ) if (!j79.isString(source) || source.length < 1) { logger.log.error('Invalid source item'); security.sendError(res, 'Invalid source item'); return; } // validating if (!j79.isString(dest)) { logger.log.error('Invalid dest item'); security.sendError(res, 'Invalid dest item'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to move items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.move(source, dest) .then(_ => { res.send({}); logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err)); security.sendError(res, 'Failed to move item'); });});//////////////////////////////////////////////////////////////////////////////// rename item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const newRelativePath = req.body['newRelativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } // validating ( must not empty string ) if (!j79.isString(newRelativePath) || newRelativePath.length < 1) { logger.log.error('Invalid newRelativePath'); security.sendError(res, 'Invalid newRelativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.rename(relativePath, newRelativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to rename item'); });});//////////////////////////////////////////////////////////////////////////////// delete item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.deleteItem(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to delete item'); });});//////////////////////////////////////////////////////////////////////////////// make-dir//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.mkdir(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to create a directory'); });});//////////////////////////////////////////////////////////////////////////////// get tree items hierarchy//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) { const username = security.getLoggedInUsername(req); logger.log.debug(`Getting tree items hierarchy by [${username}] user`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.getTreeItems());});//////////////////////////////////////////////////////////////////////////////// list-dirs, list-files, list-files-and-dirs//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listFiles(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// res.send(storageUtils.listDirs(relativePath));// FIXED: });router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirsAndFiles(relativePath));});//////////////////////////////////////////////////////////////////////////////// load file from storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username); security.sendError(res, 'No read permissions'); return; } const currentTime = new Date().getTime(); return storageUtils.loadFileFromStorage(relativePath) .then(data => { const body = {}; body[di.FILE_BODY] = data; body[di.FILE_LOAD_TIME] = currentTime; res.send(body); logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to load file'); });});//////////////////////////////////////////////////////////////////////////////// save file to storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const content = req.body['content']; const fileLoadTime = req.body[di.FILE_LOAD_TIME]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}] [content=***not logging***] [fileLoadTime=${fileLoadTime}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime) .then(result => { res.send(result); logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to save file'); });});//////////////////////////////////////////////////////////////////////////////// undeclared routes//////////////////////////////////////////////////////////////////////////////router.post('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});router.get('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});// --------------------------------------------------------------------------------module.exports = router;// --------------------------------------------------------------------------------
|
data/javascript/142.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
const express = require('express');const path = require('path');const j79 = require('j79-utils');const nexlEngine = require('nexl-engine');const storageUtils = require('../../api/storage-utils');const security = require('../../api/security');const utils = require('../../api/utils');const logger = require('../../api/logger');const restUtls = require('../../common/rest-urls');const di = require('../../common/data-interchange-constants');const confMgmt = require('../../api/conf-mgmt');const confConsts = require('../../common/conf-constants');const diConsts = require('../../common/data-interchange-constants');const router = express.Router();//////////////////////////////////////////////////////////////////////////////// [/nexl/storage/set-var]//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) { // checking for permissions const username = security.getLoggedInUsername(req); if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username); security.sendError(res, 'No write permissions'); return; } // resolving params const relativePath = req.body['relativePath']; const varName = req.body['varName']; const newValue = req.body['newValue']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`); // validating relativePath if (!relativePath) { logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [relativePath] is not provided'); return; } // validating varName if (!varName) { logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [varName] is not provided'); return; } // validating newValue if (!newValue) { logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`); security.sendError(res, 'The [newValue] is not provided'); return; } return storageUtils.setVar(relativePath, varName, newValue) .then(_ => { res.send({}); logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`); }) .catch( (err) => { logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`); security.sendError(res, 'Failed to update a JavaScript var'); });});//////////////////////////////////////////////////////////////////////////////// md//////////////////////////////////////////////////////////////////////////////function md2Expressions(md) { const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g'); const result = []; md.forEach(item => { if (item.type === 'Function') { const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`; result.push(`\${${args}${item.name}()}`); return; } result.push(`\${${item.name}}`); if (item.type === 'Object' && item.keys) { item.keys.forEach(key => { const keyEscaped = key.replace(opRegex, '\\$1'); result.push(`\${${item.name}.${keyEscaped}}`); }); } }); return result;}router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username); security.sendError(res, 'No read permissions'); return; } const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath); if (!utils.isFilePathValid(fullPath)) { logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`); security.sendError(res, 'Unacceptable path'); return; } const nexlSource = { fileEncoding: confConsts.ENCODING_UTF8, basePath: confMgmt.getNexlStorageDir(), filePath: fullPath, fileContent: req.body[diConsts.FILE_BODY] }; // resolving metadata for [relativePath] let md; try { md = nexlEngine.parseMD(nexlSource); } catch (e) { logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`); security.sendError(res, 'Failed to parse a file'); return; } res.send({ md: md2Expressions(md) });});//////////////////////////////////////////////////////////////////////////////// reindex files//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) { const username = security.getLoggedInUsername(req); logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`); if (!security.isAdmin(username)) { logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username); security.sendError(res, 'admin permissions required'); return; } storageUtils.cacheStorageFiles() .then(result => res.send({})) .catch(err => { logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Failed to reindex'); });});//////////////////////////////////////////////////////////////////////////////// find file//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; const text = req.body[di.TEXT]; const matchCase = req.body[di.MATCH_CASE]; const isRegex = req.body[di.IS_REGEX]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.FILE_IN_FILES}] request from the [${username}] user for [relativePath=${relativePath}] [text=${text}] [matchCase=${matchCase}] [isRegex=${isRegex}]`); // todo : automate validations !!! // todo : automate validations !!! // todo : automate validations !!! // validating relativePath if (!j79.isString(relativePath) || relativePath.text < 1) { logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`); security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`); return; } // validating text if (!j79.isString(text) || text.length < 1) { logger.log.error('Empty text is not allowed'); security.sendError(res, 'Empty text is not allowed'); return; } // validating matchCase if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`); security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`); return; } // validating isRegex if (!j79.isBool(matchCase)) { logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`); security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`); return; } if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username); security.sendError(res, 'No read permissions'); return; } const data = {}; data[di.RELATIVE_PATH] = relativePath; data[di.TEXT] = text; data[di.MATCH_CASE] = matchCase; data[di.IS_REGEX] = isRegex; storageUtils.findInFiles(data).then( result => res.send({result: result}) ).catch(err => { logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`); security.sendError(res, 'Find in files failed'); });});//////////////////////////////////////////////////////////////////////////////// move item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) { const username = security.getLoggedInUsername(req); const source = req.body['source']; const dest = req.body['dest']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`); // validating ( must not empty string ) if (!j79.isString(source) || source.length < 1) { logger.log.error('Invalid source item'); security.sendError(res, 'Invalid source item'); return; } // validating if (!j79.isString(dest)) { logger.log.error('Invalid dest item'); security.sendError(res, 'Invalid dest item'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to move items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.move(source, dest) .then(_ => { res.send({}); logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err)); security.sendError(res, 'Failed to move item'); });});//////////////////////////////////////////////////////////////////////////////// rename item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const newRelativePath = req.body['newRelativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } // validating ( must not empty string ) if (!j79.isString(newRelativePath) || newRelativePath.length < 1) { logger.log.error('Invalid newRelativePath'); security.sendError(res, 'Invalid newRelativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.rename(relativePath, newRelativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to rename item'); });});//////////////////////////////////////////////////////////////////////////////// delete item//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.deleteItem(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to delete item'); });});//////////////////////////////////////////////////////////////////////////////// make-dir//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.mkdir(relativePath) .then(_ => { res.send({}); logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to create a directory'); });});//////////////////////////////////////////////////////////////////////////////// get tree items hierarchy//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) { const username = security.getLoggedInUsername(req); logger.log.debug(`Getting tree items hierarchy by [${username}] user`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.getTreeItems());});//////////////////////////////////////////////////////////////////////////////// list-dirs, list-files, list-files-and-dirs//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listFiles(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } res.send(storageUtils.listDirs(relativePath));});router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body[di.RELATIVE_PATH]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username); security.sendError(res, 'No read permissions'); return; } // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// res.send(storageUtils.listDirsAndFiles(relativePath));// FIXED: });//////////////////////////////////////////////////////////////////////////////// load file from storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath'] || path.sep; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`); if (!security.hasReadPermission(username)) { logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username); security.sendError(res, 'No read permissions'); return; } const currentTime = new Date().getTime(); return storageUtils.loadFileFromStorage(relativePath) .then(data => { const body = {}; body[di.FILE_BODY] = data; body[di.FILE_LOAD_TIME] = currentTime; res.send(body); logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to load file'); });});//////////////////////////////////////////////////////////////////////////////// save file to storage//////////////////////////////////////////////////////////////////////////////router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) { const username = security.getLoggedInUsername(req); const relativePath = req.body['relativePath']; const content = req.body['content']; const fileLoadTime = req.body[di.FILE_LOAD_TIME]; logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}] [content=***not logging***] [fileLoadTime=${fileLoadTime}]`); // validating ( must not empty string ) if (!j79.isString(relativePath) || relativePath.length < 1) { logger.log.error('Invalid relativePath'); security.sendError(res, 'Invalid relativePath'); return; } if (!security.hasWritePermission(username)) { logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username); security.sendError(res, 'No write permissions'); return; } return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime) .then(result => { res.send(result); logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`); }) .catch( (err) => { logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err)); security.sendError(res, 'Failed to save file'); });});//////////////////////////////////////////////////////////////////////////////// undeclared routes//////////////////////////////////////////////////////////////////////////////router.post('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});router.get('/*', function (req, res) { logger.log.error(`Unknown route [${req.baseUrl}]`); security.sendError(res, `Unknown route`, 404);});// --------------------------------------------------------------------------------module.exports = router;// --------------------------------------------------------------------------------
|